Kargi-Sitesi/node_modules/firebase/firebase-firestore-lite.js

3 lines
116 KiB
JavaScript

import{_registerComponent as e,registerVersion as t,_getProvider,getApp as r,_removeServiceInstance as n,SDK_VERSION as i}from"https://www.gstatic.com/firebasejs/11.0.1/firebase-app.js";const stringToByteArray$1=function(e){const t=[];let r=0;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);i<128?t[r++]=i:i<2048?(t[r++]=i>>6|192,t[r++]=63&i|128):55296==(64512&i)&&n+1<e.length&&56320==(64512&e.charCodeAt(n+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++n)),t[r++]=i>>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=63&i|128):(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=63&i|128)}return t},s={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let t=0;t<e.length;t+=3){const i=e[t],s=t+1<e.length,o=s?e[t+1]:0,a=t+2<e.length,u=a?e[t+2]:0,l=i>>2,c=(3&i)<<4|o>>4;let _=(15&o)<<2|u>>6,h=63&u;a||(h=64,s||(_=64)),n.push(r[l],r[c],r[_],r[h])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(stringToByteArray$1(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r<e.length;){const i=e[r++];if(i<128)t[n++]=String.fromCharCode(i);else if(i>191&&i<224){const s=e[r++];t[n++]=String.fromCharCode((31&i)<<6|63&s)}else if(i>239&&i<365){const s=((7&i)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536;t[n++]=String.fromCharCode(55296+(s>>10)),t[n++]=String.fromCharCode(56320+(1023&s))}else{const s=e[r++],o=e[r++];t[n++]=String.fromCharCode((15&i)<<12|(63&s)<<6|63&o)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let t=0;t<e.length;){const i=r[e.charAt(t++)],s=t<e.length?r[e.charAt(t)]:0;++t;const o=t<e.length?r[e.charAt(t)]:64;++t;const a=t<e.length?r[e.charAt(t)]:64;if(++t,null==i||null==s||null==o||null==a)throw new DecodeBase64StringError;const u=i<<2|s>>4;if(n.push(u),64!==o){const e=s<<4&240|o>>2;if(n.push(e),64!==a){const e=o<<6&192|a;n.push(e)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64urlEncodeWithoutPadding=function(e){return function(e){const t=stringToByteArray$1(e);return s.encodeByteArray(t,!0)}(e).replace(/\./g,"")};const getDefaultsFromGlobal=()=>function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__,getDefaultsFromCookie=()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&function(e){try{return s.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return t&&JSON.parse(t)},getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||getDefaultsFromCookie()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getDefaultEmulatorHostnameAndPort=e=>{const t=(e=>{var t,r;return null===(r=null===(t=getDefaults())||void 0===t?void 0:t.emulatorHosts)||void 0===r?void 0:r[e]})(e);if(!t)return;const r=t.lastIndexOf(":");if(r<=0||r+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const n=parseInt(t.substring(r+1),10);return"["===t[0]?[t.substring(1,r-1),n]:[t.substring(0,r),n]};class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){const r=t[0]||{},n=`${this.service}/${e}`,i=this.errors[e],s=i?function replaceTemplate(e,t){return e.replace(o,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(i,r):"Error",a=`${this.serviceName}: ${s} (${n}).`;return new FirebaseError(n,a,r)}}const o=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const r=Object.keys(e),n=Object.keys(t);for(const i of r){if(!n.includes(i))return!1;const r=e[i],s=t[i];if(isObject(r)&&isObject(s)){if(!deepEqual(r,s))return!1}else if(r!==s)return!1}for(const e of n)if(!r.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var a;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(a||(a={}));const u={debug:a.DEBUG,verbose:a.VERBOSE,info:a.INFO,warn:a.WARN,error:a.ERROR,silent:a.SILENT},l=a.INFO,c={[a.DEBUG]:"log",[a.VERBOSE]:"log",[a.INFO]:"info",[a.WARN]:"warn",[a.ERROR]:"error"},defaultLogHandler=(e,t,...r)=>{if(t<e.logLevel)return;const n=(new Date).toISOString(),i=c[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${n}] ${e.name}:`,...r)};class User{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}}User.UNAUTHENTICATED=new User(null),User.GOOGLE_CREDENTIALS=new User("google-credentials-uid"),User.FIRST_PARTY=new User("first-party-uid"),User.MOCK_USER=new User("mock-user");let _="11.0.1";const h=new class Logger{constructor(e){this.name=e,this._logLevel=l,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in a))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?u[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,a.DEBUG,...e),this._logHandler(this,a.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,a.VERBOSE,...e),this._logHandler(this,a.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,a.INFO,...e),this._logHandler(this,a.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,a.WARN,...e),this._logHandler(this,a.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,a.ERROR,...e),this._logHandler(this,a.ERROR,...e)}}("@firebase/firestore");function setLogLevel(e){h.setLogLevel(e)}function __PRIVATE_logDebug(e,...t){if(h.logLevel<=a.DEBUG){const r=t.map(__PRIVATE_argToString);h.debug(`Firestore (${_}): ${e}`,...r)}}function __PRIVATE_logError(e,...t){if(h.logLevel<=a.ERROR){const r=t.map(__PRIVATE_argToString);h.error(`Firestore (${_}): ${e}`,...r)}}function __PRIVATE_logWarn(e,...t){if(h.logLevel<=a.WARN){const r=t.map(__PRIVATE_argToString);h.warn(`Firestore (${_}): ${e}`,...r)}}function __PRIVATE_argToString(e){if("string"==typeof e)return e;try{return function __PRIVATE_formatJSON(e){return JSON.stringify(e)}(e)}catch(t){return e}}function fail(e="Unexpected state"){const t=`FIRESTORE (${_}) INTERNAL ASSERTION FAILED: `+e;throw __PRIVATE_logError(t),new Error(t)}function __PRIVATE_hardAssert(e,t){e||fail()}function __PRIVATE_debugCast(e,t){return e}const d="cancelled",f="unknown",m="invalid-argument",p="deadline-exceeded",g="not-found",E="permission-denied",T="unauthenticated",A="resource-exhausted",y="failed-precondition",I="aborted",V="out-of-range",P="unimplemented",R="internal",v="unavailable";class FirestoreError extends FirebaseError{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class __PRIVATE_Deferred{constructor(){this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class __PRIVATE_OAuthToken{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class __PRIVATE_EmptyAuthCredentialsProvider{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(User.UNAUTHENTICATED)))}shutdown(){}}class __PRIVATE_EmulatorAuthCredentialsProvider{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable((()=>t(this.token.user)))}shutdown(){this.changeListener=null}}class __PRIVATE_LiteAuthCredentialsProvider{constructor(e){this.auth=null,e.onInit((e=>{this.auth=e}))}getToken(){return this.auth?this.auth.getToken().then((e=>e?(__PRIVATE_hardAssert("string"==typeof e.accessToken),new __PRIVATE_OAuthToken(e.accessToken,new User(this.auth.getUid()))):null)):Promise.resolve(null)}invalidateToken(){}start(e,t){}shutdown(){}}class __PRIVATE_FirstPartyToken{constructor(e,t,r){this.t=e,this.i=t,this.o=r,this.type="FirstParty",this.user=User.FIRST_PARTY,this.u=new Map}l(){return this.o?this.o():null}get headers(){this.u.set("X-Goog-AuthUser",this.t);const e=this.l();return e&&this.u.set("Authorization",e),this.i&&this.u.set("X-Goog-Iam-Authorization-Token",this.i),this.u}}class __PRIVATE_FirstPartyAuthCredentialsProvider{constructor(e,t,r){this.t=e,this.i=t,this.o=r}getToken(){return Promise.resolve(new __PRIVATE_FirstPartyToken(this.t,this.i,this.o))}start(e,t){e.enqueueRetryable((()=>t(User.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class AppCheckToken{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 __PRIVATE_LiteAppCheckTokenProvider{constructor(e){this.h=e,this.appCheck=null,e.onInit((e=>{this.appCheck=e}))}getToken(){return this.appCheck?this.appCheck.getToken().then((e=>e?(__PRIVATE_hardAssert("string"==typeof e.token),new AppCheckToken(e.token)):null)):Promise.resolve(null)}invalidateToken(){}start(e,t){}shutdown(){}}class DatabaseInfo{constructor(e,t,r,n,i,s,o,a,u){this.databaseId=e,this.appId=t,this.persistenceKey=r,this.host=n,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=o,this.longPollingOptions=a,this.useFetchStreams=u}}class DatabaseId{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new DatabaseId("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof DatabaseId&&e.projectId===this.projectId&&e.database===this.database}}class BasePath{constructor(e,t,r){void 0===t?t=0:t>e.length&&fail(),void 0===r?r=e.length-t:r>e.length-t&&fail(),this.segments=e,this.offset=t,this.len=r}get length(){return this.len}isEqual(e){return 0===BasePath.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof BasePath?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,r=this.limit();t<r;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const r=Math.min(e.length,t.length);for(let n=0;n<r;n++){const r=e.get(n),i=t.get(n);if(r<i)return-1;if(r>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class ResourcePath extends BasePath{construct(e,t,r){return new ResourcePath(e,t,r)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){const t=[];for(const r of e){if(r.indexOf("//")>=0)throw new FirestoreError(m,`Invalid segment (${r}). Paths must not contain // in them.`);t.push(...r.split("/").filter((e=>e.length>0)))}return new ResourcePath(t)}static emptyPath(){return new ResourcePath([])}}const w=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class FieldPath$1 extends BasePath{construct(e,t,r){return new FieldPath$1(e,t,r)}static isValidIdentifier(e){return w.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),FieldPath$1.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new FieldPath$1(["__name__"])}static fromServerFormat(e){const t=[];let r="",n=0;const __PRIVATE_addCurrentSegment=()=>{if(0===r.length)throw new FirestoreError(m,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(r),r=""};let i=!1;for(;n<e.length;){const t=e[n];if("\\"===t){if(n+1===e.length)throw new FirestoreError(m,"Path has trailing escape character: "+e);const t=e[n+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new FirestoreError(m,"Path has invalid escape sequence: "+e);r+=t,n+=2}else"`"===t?(i=!i,n++):"."!==t||i?(r+=t,n++):(__PRIVATE_addCurrentSegment(),n++)}if(__PRIVATE_addCurrentSegment(),i)throw new FirestoreError(m,"Unterminated ` in path: "+e);return new FieldPath$1(t)}static emptyPath(){return new FieldPath$1([])}}class DocumentKey{constructor(e){this.path=e}static fromPath(e){return new DocumentKey(ResourcePath.fromString(e))}static fromName(e){return new DocumentKey(ResourcePath.fromString(e).popFirst(5))}static empty(){return new DocumentKey(ResourcePath.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===ResourcePath.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return ResourcePath.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new DocumentKey(new ResourcePath(e.slice()))}}function __PRIVATE_validateNonEmptyArgument(e,t,r){if(!r)throw new FirestoreError(m,`Function ${e}() cannot be called with an empty ${t}.`)}function __PRIVATE_validateDocumentPath(e){if(!DocumentKey.isDocumentKey(e))throw new FirestoreError(m,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function __PRIVATE_validateCollectionPath(e){if(DocumentKey.isDocumentKey(e))throw new FirestoreError(m,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function __PRIVATE_valueDescription(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{const t=function __PRIVATE_tryGetCustomObjectType(e){return e.constructor?e.constructor.name:null}(e);return t?`a custom ${t} object`:"an object"}}return"function"==typeof e?"a function":fail()}function __PRIVATE_cast(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new FirestoreError(m,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const r=__PRIVATE_valueDescription(e);throw new FirestoreError(m,`Expected type '${t.name}', but it was: ${r}`)}}return e}function __PRIVATE_validatePositiveNumber(e,t){if(t<=0)throw new FirestoreError(m,`Function ${e}() requires a positive number, but it was: ${t}.`)}function __PRIVATE_cloneLongPollingOptions(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}let F=null;function __PRIVATE_isNullOrUndefined(e){return null==e}function __PRIVATE_isNegativeZero(e){return 0===e&&1/e==-1/0}const S={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};var b,D;function __PRIVATE_mapCodeFromHttpStatus(e){if(void 0===e)return __PRIVATE_logError("RPC_ERROR","HTTP error has no status"),f;switch(e){case 200:return"ok";case 400:return y;case 401:return T;case 403:return E;case 404:return g;case 409:return I;case 416:return V;case 429:return A;case 499:return d;case 500:return f;case 501:return P;case 503:return v;case 504:return p;default:return e>=200&&e<300?"ok":e>=400&&e<500?y:e>=500&&e<600?R:f}}(D=b||(b={}))[D.OK=0]="OK",D[D.CANCELLED=1]="CANCELLED",D[D.UNKNOWN=2]="UNKNOWN",D[D.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",D[D.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",D[D.NOT_FOUND=5]="NOT_FOUND",D[D.ALREADY_EXISTS=6]="ALREADY_EXISTS",D[D.PERMISSION_DENIED=7]="PERMISSION_DENIED",D[D.UNAUTHENTICATED=16]="UNAUTHENTICATED",D[D.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",D[D.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",D[D.ABORTED=10]="ABORTED",D[D.OUT_OF_RANGE=11]="OUT_OF_RANGE",D[D.UNIMPLEMENTED=12]="UNIMPLEMENTED",D[D.INTERNAL=13]="INTERNAL",D[D.UNAVAILABLE=14]="UNAVAILABLE",D[D.DATA_LOSS=15]="DATA_LOSS";class __PRIVATE_FetchConnection extends class __PRIVATE_RestConnection{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http",r=encodeURIComponent(this.databaseId.projectId),n=encodeURIComponent(this.databaseId.database);this.m=t+"://"+e.host,this.A=`projects/${r}/databases/${n}`,this.T="(default)"===this.databaseId.database?`project_id=${r}`:`project_id=${r}&database_id=${n}`}get R(){return!1}P(e,t,r,n,i){const s=function __PRIVATE_generateUniqueDebugId(){return null===F?F=function __PRIVATE_generateInitialUniqueDebugId(){return 268435456+Math.round(2147483648*Math.random())}():F++,"0x"+F.toString(16)}(),o=this.V(e,t.toUriEncodedString());__PRIVATE_logDebug("RestConnection",`Sending RPC '${e}' ${s}:`,o,r);const a={"google-cloud-resource-prefix":this.A,"x-goog-request-params":this.T};return this.I(a,n,i),this.p(e,o,a,r).then((t=>(__PRIVATE_logDebug("RestConnection",`Received RPC '${e}' ${s}: `,t),t)),(t=>{throw __PRIVATE_logWarn("RestConnection",`RPC '${e}' ${s} failed with error: `,t,"url: ",o,"request:",r),t}))}g(e,t,r,n,i,s){return this.P(e,t,r,n,i)}I(e,t,r){e["X-Goog-Api-Client"]=function __PRIVATE_getGoogApiClientValue(){return"gl-js/ fire/"+_}(),e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach(((t,r)=>e[r]=t)),r&&r.headers.forEach(((t,r)=>e[r]=t))}V(e,t){const r=S[e];return`${this.m}/v1/${t}:${r}`}terminate(){}}{F(e,t){throw new Error("Not supported by FetchConnection")}async p(e,t,r,n){var i;const s=JSON.stringify(n);let o;try{o=await fetch(t,{method:"POST",headers:r,body:s})}catch(e){const t=e;throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(t.status),"Request failed with error: "+t.statusText)}if(!o.ok){let e=await o.json();Array.isArray(e)&&(e=e[0]);const t=null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.message;throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(o.status),`Request failed with error: ${null!=t?t:o.statusText}`)}return o.json()}}class __PRIVATE_AggregateImpl{constructor(e,t,r){this.alias=e,this.aggregateType=t,this.fieldPath=r}}function __PRIVATE_randomBytes(e){const t="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(e);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(r);else for(let t=0;t<e;t++)r[t]=Math.floor(256*Math.random());return r}class __PRIVATE_AutoId{static newId(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=Math.floor(256/e.length)*e.length;let r="";for(;r.length<20;){const n=__PRIVATE_randomBytes(40);for(let i=0;i<n.length;++i)r.length<20&&n[i]<t&&(r+=e.charAt(n[i]%e.length))}return r}}function __PRIVATE_primitiveComparator(e,t){return e<t?-1:e>t?1:0}function __PRIVATE_arrayEquals(e,t,r){return e.length===t.length&&e.every(((e,n)=>r(e,t[n])))}function __PRIVATE_objectSize(e){let t=0;for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function forEach(e,t){for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t(r,e[r])}class __PRIVATE_Base64DecodeError extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class ByteString{constructor(e){this.binaryString=e}static fromBase64String(e){const t=function __PRIVATE_decodeBase64(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new __PRIVATE_Base64DecodeError("Invalid base64 string: "+e):e}}(e);return new ByteString(t)}static fromUint8Array(e){const t=function __PRIVATE_binaryStringFromUint8Array(e){let t="";for(let r=0;r<e.length;++r)t+=String.fromCharCode(e[r]);return t}(e);return new ByteString(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return function __PRIVATE_encodeBase64(e){return btoa(e)}(this.binaryString)}toUint8Array(){return function __PRIVATE_uint8ArrayFromBinaryString(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return __PRIVATE_primitiveComparator(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}ByteString.EMPTY_BYTE_STRING=new ByteString("");const C=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function __PRIVATE_normalizeTimestamp(e){if(__PRIVATE_hardAssert(!!e),"string"==typeof e){let t=0;const r=C.exec(e);if(__PRIVATE_hardAssert(!!r),r[1]){let e=r[1];e=(e+"000000000").substr(0,9),t=Number(e)}const n=new Date(e);return{seconds:Math.floor(n.getTime()/1e3),nanos:t}}return{seconds:__PRIVATE_normalizeNumber(e.seconds),nanos:__PRIVATE_normalizeNumber(e.nanos)}}function __PRIVATE_normalizeNumber(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function __PRIVATE_normalizeByteString(e){return"string"==typeof e?ByteString.fromBase64String(e):ByteString.fromUint8Array(e)}class Timestamp{constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new FirestoreError(m,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new FirestoreError(m,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new FirestoreError(m,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new FirestoreError(m,"Timestamp seconds out of range: "+e)}static now(){return Timestamp.fromMillis(Date.now())}static fromDate(e){return Timestamp.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),r=Math.floor(1e6*(e-1e3*t));return new Timestamp(t,r)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?__PRIVATE_primitiveComparator(this.nanoseconds,e.nanoseconds):__PRIVATE_primitiveComparator(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}function __PRIVATE_isServerTimestamp(e){var t,r;return"server_timestamp"===(null===(r=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===r?void 0:r.stringValue)}function __PRIVATE_getPreviousValue(e){const t=e.mapValue.fields.__previous_value__;return __PRIVATE_isServerTimestamp(t)?__PRIVATE_getPreviousValue(t):t}function __PRIVATE_getLocalWriteTime(e){const t=__PRIVATE_normalizeTimestamp(e.mapValue.fields.__local_write_time__.timestampValue);return new Timestamp(t.seconds,t.nanos)}const N={fields:{__type__:{stringValue:"__max__"}}};function __PRIVATE_typeOrder(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?__PRIVATE_isServerTimestamp(e)?4:function __PRIVATE_isMaxValue(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}(e)?9007199254740991:function __PRIVATE_isVectorValue(e){var t,r;return"__vector__"===(null===(r=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===r?void 0:r.stringValue)}(e)?10:11:fail()}function __PRIVATE_valueEquals(e,t){if(e===t)return!0;const r=__PRIVATE_typeOrder(e);if(r!==__PRIVATE_typeOrder(t))return!1;switch(r){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return __PRIVATE_getLocalWriteTime(e).isEqual(__PRIVATE_getLocalWriteTime(t));case 3:return function __PRIVATE_timestampEquals(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;const r=__PRIVATE_normalizeTimestamp(e.timestampValue),n=__PRIVATE_normalizeTimestamp(t.timestampValue);return r.seconds===n.seconds&&r.nanos===n.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return function __PRIVATE_blobEquals(e,t){return __PRIVATE_normalizeByteString(e.bytesValue).isEqual(__PRIVATE_normalizeByteString(t.bytesValue))}(e,t);case 7:return e.referenceValue===t.referenceValue;case 8:return function __PRIVATE_geoPointEquals(e,t){return __PRIVATE_normalizeNumber(e.geoPointValue.latitude)===__PRIVATE_normalizeNumber(t.geoPointValue.latitude)&&__PRIVATE_normalizeNumber(e.geoPointValue.longitude)===__PRIVATE_normalizeNumber(t.geoPointValue.longitude)}(e,t);case 2:return function __PRIVATE_numberEquals(e,t){if("integerValue"in e&&"integerValue"in t)return __PRIVATE_normalizeNumber(e.integerValue)===__PRIVATE_normalizeNumber(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){const r=__PRIVATE_normalizeNumber(e.doubleValue),n=__PRIVATE_normalizeNumber(t.doubleValue);return r===n?__PRIVATE_isNegativeZero(r)===__PRIVATE_isNegativeZero(n):isNaN(r)&&isNaN(n)}return!1}(e,t);case 9:return __PRIVATE_arrayEquals(e.arrayValue.values||[],t.arrayValue.values||[],__PRIVATE_valueEquals);case 10:case 11:return function __PRIVATE_objectEquals(e,t){const r=e.mapValue.fields||{},n=t.mapValue.fields||{};if(__PRIVATE_objectSize(r)!==__PRIVATE_objectSize(n))return!1;for(const e in r)if(r.hasOwnProperty(e)&&(void 0===n[e]||!__PRIVATE_valueEquals(r[e],n[e])))return!1;return!0}(e,t);default:return fail()}}function __PRIVATE_arrayValueContains(e,t){return void 0!==(e.values||[]).find((e=>__PRIVATE_valueEquals(e,t)))}function __PRIVATE_valueCompare(e,t){if(e===t)return 0;const r=__PRIVATE_typeOrder(e),n=__PRIVATE_typeOrder(t);if(r!==n)return __PRIVATE_primitiveComparator(r,n);switch(r){case 0:case 9007199254740991:return 0;case 1:return __PRIVATE_primitiveComparator(e.booleanValue,t.booleanValue);case 2:return function __PRIVATE_compareNumbers(e,t){const r=__PRIVATE_normalizeNumber(e.integerValue||e.doubleValue),n=__PRIVATE_normalizeNumber(t.integerValue||t.doubleValue);return r<n?-1:r>n?1:r===n?0:isNaN(r)?isNaN(n)?0:-1:1}(e,t);case 3:return __PRIVATE_compareTimestamps(e.timestampValue,t.timestampValue);case 4:return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(e),__PRIVATE_getLocalWriteTime(t));case 5:return __PRIVATE_primitiveComparator(e.stringValue,t.stringValue);case 6:return function __PRIVATE_compareBlobs(e,t){const r=__PRIVATE_normalizeByteString(e),n=__PRIVATE_normalizeByteString(t);return r.compareTo(n)}(e.bytesValue,t.bytesValue);case 7:return function __PRIVATE_compareReferences(e,t){const r=e.split("/"),n=t.split("/");for(let e=0;e<r.length&&e<n.length;e++){const t=__PRIVATE_primitiveComparator(r[e],n[e]);if(0!==t)return t}return __PRIVATE_primitiveComparator(r.length,n.length)}(e.referenceValue,t.referenceValue);case 8:return function __PRIVATE_compareGeoPoints(e,t){const r=__PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.latitude),__PRIVATE_normalizeNumber(t.latitude));return 0!==r?r:__PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.longitude),__PRIVATE_normalizeNumber(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return __PRIVATE_compareArrays(e.arrayValue,t.arrayValue);case 10:return function __PRIVATE_compareVectors(e,t){var r,n,i,s;const o=e.fields||{},a=t.fields||{},u=null===(r=o.value)||void 0===r?void 0:r.arrayValue,l=null===(n=a.value)||void 0===n?void 0:n.arrayValue,c=__PRIVATE_primitiveComparator((null===(i=null==u?void 0:u.values)||void 0===i?void 0:i.length)||0,(null===(s=null==l?void 0:l.values)||void 0===s?void 0:s.length)||0);return 0!==c?c:__PRIVATE_compareArrays(u,l)}(e.mapValue,t.mapValue);case 11:return function __PRIVATE_compareMaps(e,t){if(e===N&&t===N)return 0;if(e===N)return 1;if(t===N)return-1;const r=e.fields||{},n=Object.keys(r),i=t.fields||{},s=Object.keys(i);n.sort(),s.sort();for(let e=0;e<n.length&&e<s.length;++e){const t=__PRIVATE_primitiveComparator(n[e],s[e]);if(0!==t)return t;const o=__PRIVATE_valueCompare(r[n[e]],i[s[e]]);if(0!==o)return o}return __PRIVATE_primitiveComparator(n.length,s.length)}(e.mapValue,t.mapValue);default:throw fail()}}function __PRIVATE_compareTimestamps(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return __PRIVATE_primitiveComparator(e,t);const r=__PRIVATE_normalizeTimestamp(e),n=__PRIVATE_normalizeTimestamp(t),i=__PRIVATE_primitiveComparator(r.seconds,n.seconds);return 0!==i?i:__PRIVATE_primitiveComparator(r.nanos,n.nanos)}function __PRIVATE_compareArrays(e,t){const r=e.values||[],n=t.values||[];for(let e=0;e<r.length&&e<n.length;++e){const t=__PRIVATE_valueCompare(r[e],n[e]);if(t)return t}return __PRIVATE_primitiveComparator(r.length,n.length)}function __PRIVATE_refValue(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function isArray(e){return!!e&&"arrayValue"in e}function __PRIVATE_isNullValue(e){return!!e&&"nullValue"in e}function __PRIVATE_isNanValue(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function __PRIVATE_isMapValue(e){return!!e&&"mapValue"in e}function __PRIVATE_deepClone(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){const t={mapValue:{fields:{}}};return forEach(e.mapValue.fields,((e,r)=>t.mapValue.fields[e]=__PRIVATE_deepClone(r))),t}if(e.arrayValue){const t={arrayValue:{values:[]}};for(let r=0;r<(e.arrayValue.values||[]).length;++r)t.arrayValue.values[r]=__PRIVATE_deepClone(e.arrayValue.values[r]);return t}return Object.assign({},e)}class Bound{constructor(e,t){this.position=e,this.inclusive=t}}function __PRIVATE_boundEquals(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let r=0;r<e.position.length;r++)if(!__PRIVATE_valueEquals(e.position[r],t.position[r]))return!1;return!0}class Filter{}class FieldFilter extends Filter{constructor(e,t,r){super(),this.field=e,this.op=t,this.value=r}static create(e,t,r){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,r):new __PRIVATE_KeyFieldFilter(e,t,r):"array-contains"===t?new __PRIVATE_ArrayContainsFilter(e,r):"in"===t?new __PRIVATE_InFilter(e,r):"not-in"===t?new __PRIVATE_NotInFilter(e,r):"array-contains-any"===t?new __PRIVATE_ArrayContainsAnyFilter(e,r):new FieldFilter(e,t,r)}static createKeyFieldInFilter(e,t,r){return"in"===t?new __PRIVATE_KeyFieldInFilter(e,r):new __PRIVATE_KeyFieldNotInFilter(e,r)}matches(e){const t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(__PRIVATE_valueCompare(t,this.value)):null!==t&&__PRIVATE_typeOrder(this.value)===__PRIVATE_typeOrder(t)&&this.matchesComparison(__PRIVATE_valueCompare(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 fail()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class CompositeFilter extends Filter{constructor(e,t){super(),this.filters=e,this.op=t,this.v=null}static create(e,t){return new CompositeFilter(e,t)}matches(e){return function __PRIVATE_compositeFilterIsConjunction(e){return"and"===e.op}(this)?void 0===this.filters.find((t=>!t.matches(e))):void 0!==this.filters.find((t=>t.matches(e)))}getFlattenedFilters(){return null!==this.v||(this.v=this.filters.reduce(((e,t)=>e.concat(t.getFlattenedFilters())),[])),this.v}getFilters(){return Object.assign([],this.filters)}}function __PRIVATE_filterEquals(e,t){return e instanceof FieldFilter?function __PRIVATE_fieldFilterEquals(e,t){return t instanceof FieldFilter&&e.op===t.op&&e.field.isEqual(t.field)&&__PRIVATE_valueEquals(e.value,t.value)}(e,t):e instanceof CompositeFilter?function __PRIVATE_compositeFilterEquals(e,t){return t instanceof CompositeFilter&&e.op===t.op&&e.filters.length===t.filters.length&&e.filters.reduce(((e,r,n)=>e&&__PRIVATE_filterEquals(r,t.filters[n])),!0)}(e,t):void fail()}class __PRIVATE_KeyFieldFilter extends FieldFilter{constructor(e,t,r){super(e,t,r),this.key=DocumentKey.fromName(r.referenceValue)}matches(e){const t=DocumentKey.comparator(e.key,this.key);return this.matchesComparison(t)}}class __PRIVATE_KeyFieldInFilter extends FieldFilter{constructor(e,t){super(e,"in",t),this.keys=__PRIVATE_extractDocumentKeysFromArrayValue("in",t)}matches(e){return this.keys.some((t=>t.isEqual(e.key)))}}class __PRIVATE_KeyFieldNotInFilter extends FieldFilter{constructor(e,t){super(e,"not-in",t),this.keys=__PRIVATE_extractDocumentKeysFromArrayValue("not-in",t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}}function __PRIVATE_extractDocumentKeysFromArrayValue(e,t){var r;return((null===(r=t.arrayValue)||void 0===r?void 0:r.values)||[]).map((e=>DocumentKey.fromName(e.referenceValue)))}class __PRIVATE_ArrayContainsFilter extends FieldFilter{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return isArray(t)&&__PRIVATE_arrayValueContains(t.arrayValue,this.value)}}class __PRIVATE_InFilter extends FieldFilter{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return null!==t&&__PRIVATE_arrayValueContains(this.value.arrayValue,t)}}class __PRIVATE_NotInFilter extends FieldFilter{constructor(e,t){super(e,"not-in",t)}matches(e){if(__PRIVATE_arrayValueContains(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!__PRIVATE_arrayValueContains(this.value.arrayValue,t)}}class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!isArray(t)||!t.arrayValue.values)&&t.arrayValue.values.some((e=>__PRIVATE_arrayValueContains(this.value.arrayValue,e)))}}class OrderBy{constructor(e,t="asc"){this.field=e,this.dir=t}}function __PRIVATE_orderByEquals(e,t){return e.dir===t.dir&&e.field.isEqual(t.field)}class SnapshotVersion{constructor(e){this.timestamp=e}static fromTimestamp(e){return new SnapshotVersion(e)}static min(){return new SnapshotVersion(new Timestamp(0,0))}static max(){return new SnapshotVersion(new Timestamp(253402300799,999999999))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class SortedMap{constructor(e,t){this.comparator=e,this.root=t||LLRBNode.EMPTY}insert(e,t){return new SortedMap(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,LLRBNode.BLACK,null,null))}remove(e){return new SortedMap(this.comparator,this.root.remove(e,this.comparator).copy(null,null,LLRBNode.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){const r=this.comparator(e,t.key);if(0===r)return t.value;r<0?t=t.left:r>0&&(t=t.right)}return null}indexOf(e){let t=0,r=this.root;for(;!r.isEmpty();){const n=this.comparator(e,r.key);if(0===n)return t+r.left.size;n<0?r=r.left:(t+=r.left.size+1,r=r.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,r)=>(e(t,r),!1)))}toString(){const e=[];return this.inorderTraversal(((t,r)=>(e.push(`${t}:${r}`),!1))),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new SortedMapIterator(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new SortedMapIterator(this.root,e,this.comparator,!1)}getReverseIterator(){return new SortedMapIterator(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new SortedMapIterator(this.root,e,this.comparator,!0)}}class SortedMapIterator{constructor(e,t,r,n){this.isReverse=n,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?r(e.key,t):1,t&&n&&(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();const t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class LLRBNode{constructor(e,t,r,n,i){this.key=e,this.value=t,this.color=null!=r?r:LLRBNode.RED,this.left=null!=n?n:LLRBNode.EMPTY,this.right=null!=i?i:LLRBNode.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,r,n,i){return new LLRBNode(null!=e?e:this.key,null!=t?t:this.value,null!=r?r:this.color,null!=n?n: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,r){let n=this;const i=r(e,n.key);return n=i<0?n.copy(null,null,null,n.left.insert(e,t,r),null):0===i?n.copy(null,t,null,null,null):n.copy(null,null,null,null,n.right.insert(e,t,r)),n.fixUp()}removeMin(){if(this.left.isEmpty())return LLRBNode.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let r,n=this;if(t(e,n.key)<0)n.left.isEmpty()||n.left.isRed()||n.left.left.isRed()||(n=n.moveRedLeft()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed()&&(n=n.rotateRight()),n.right.isEmpty()||n.right.isRed()||n.right.left.isRed()||(n=n.moveRedRight()),0===t(e,n.key)){if(n.right.isEmpty())return LLRBNode.EMPTY;r=n.right.min(),n=n.copy(r.key,r.value,null,null,n.right.removeMin())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){const e=this.copy(null,null,LLRBNode.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,LLRBNode.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw fail();if(this.right.isRed())throw fail();const e=this.left.check();if(e!==this.right.check())throw fail();return e+(this.isRed()?0:1)}}LLRBNode.EMPTY=null,LLRBNode.RED=!0,LLRBNode.BLACK=!1,LLRBNode.EMPTY=new class LLRBEmptyNode{constructor(){this.size=0}get key(){throw fail()}get value(){throw fail()}get color(){throw fail()}get left(){throw fail()}get right(){throw fail()}copy(e,t,r,n,i){return this}insert(e,t,r){return new LLRBNode(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 SortedSet{constructor(e){this.comparator=e,this.data=new SortedMap(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,r)=>(e(t),!1)))}forEachInRange(e,t){const r=this.data.getIteratorFrom(e[0]);for(;r.hasNext();){const n=r.getNext();if(this.comparator(n.key,e[1])>=0)return;t(n.key)}}forEachWhile(e,t){let r;for(r=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();r.hasNext();)if(!e(r.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new SortedSetIterator(this.data.getIterator())}getIteratorFrom(e){return new SortedSetIterator(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 SortedSet))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),r=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,n=r.getNext().key;if(0!==this.comparator(e,n))return!1}return!0}toArray(){const e=[];return this.forEach((t=>{e.push(t)})),e}toString(){const e=[];return this.forEach((t=>e.push(t))),"SortedSet("+e.toString()+")"}copy(e){const t=new SortedSet(this.comparator);return t.data=e,t}}class SortedSetIterator{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}class FieldMask{constructor(e){this.fields=e,e.sort(FieldPath$1.comparator)}static empty(){return new FieldMask([])}unionWith(e){let t=new SortedSet(FieldPath$1.comparator);for(const e of this.fields)t=t.add(e);for(const r of e)t=t.add(r);return new FieldMask(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return __PRIVATE_arrayEquals(this.fields,e.fields,((e,t)=>e.isEqual(t)))}}class ObjectValue{constructor(e){this.value=e}static empty(){return new ObjectValue({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let r=0;r<e.length-1;++r)if(t=(t.mapValue.fields||{})[e.get(r)],!__PRIVATE_isMapValue(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=__PRIVATE_deepClone(t)}setAll(e){let t=FieldPath$1.emptyPath(),r={},n=[];e.forEach(((e,i)=>{if(!t.isImmediateParentOf(i)){const e=this.getFieldsMap(t);this.applyChanges(e,r,n),r={},n=[],t=i.popLast()}e?r[i.lastSegment()]=__PRIVATE_deepClone(e):n.push(i.lastSegment())}));const i=this.getFieldsMap(t);this.applyChanges(i,r,n)}delete(e){const t=this.field(e.popLast());__PRIVATE_isMapValue(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return __PRIVATE_valueEquals(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let r=0;r<e.length;++r){let n=t.mapValue.fields[e.get(r)];__PRIVATE_isMapValue(n)&&n.mapValue.fields||(n={mapValue:{fields:{}}},t.mapValue.fields[e.get(r)]=n),t=n}return t.mapValue.fields}applyChanges(e,t,r){forEach(t,((t,r)=>e[t]=r));for(const t of r)delete e[t]}clone(){return new ObjectValue(__PRIVATE_deepClone(this.value))}}class MutableDocument{constructor(e,t,r,n,i,s,o){this.key=e,this.documentType=t,this.version=r,this.readTime=n,this.createTime=i,this.data=s,this.documentState=o}static newInvalidDocument(e){return new MutableDocument(e,0,SnapshotVersion.min(),SnapshotVersion.min(),SnapshotVersion.min(),ObjectValue.empty(),0)}static newFoundDocument(e,t,r,n){return new MutableDocument(e,1,t,SnapshotVersion.min(),r,n,0)}static newNoDocument(e,t){return new MutableDocument(e,2,t,SnapshotVersion.min(),SnapshotVersion.min(),ObjectValue.empty(),0)}static newUnknownDocument(e,t){return new MutableDocument(e,3,t,SnapshotVersion.min(),SnapshotVersion.min(),ObjectValue.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(SnapshotVersion.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=ObjectValue.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=ObjectValue.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=SnapshotVersion.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 MutableDocument&&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 MutableDocument(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 __PRIVATE_TargetImpl{constructor(e,t=null,r=[],n=[],i=null,s=null,o=null){this.path=e,this.collectionGroup=t,this.orderBy=r,this.filters=n,this.limit=i,this.startAt=s,this.endAt=o,this.D=null}}function __PRIVATE_newTarget(e,t=null,r=[],n=[],i=null,s=null,o=null){return new __PRIVATE_TargetImpl(e,t,r,n,i,s,o)}class __PRIVATE_QueryImpl{constructor(e,t=null,r=[],n=[],i=null,s="F",o=null,a=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=r,this.filters=n,this.limit=i,this.limitType=s,this.startAt=o,this.endAt=a,this.C=null,this.S=null,this.N=null,this.startAt,this.endAt}}function __PRIVATE_isCollectionGroupQuery(e){return null!==e.collectionGroup}function __PRIVATE_queryNormalizedOrderBy(e){const t=__PRIVATE_debugCast(e);if(null===t.C){t.C=[];const e=new Set;for(const r of t.explicitOrderBy)t.C.push(r),e.add(r.field.canonicalString());const r=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc",n=function __PRIVATE_getInequalityFilterFields(e){let t=new SortedSet(FieldPath$1.comparator);return e.filters.forEach((e=>{e.getFlattenedFilters().forEach((e=>{e.isInequality()&&(t=t.add(e.field))}))})),t}(t);n.forEach((n=>{e.has(n.canonicalString())||n.isKeyField()||t.C.push(new OrderBy(n,r))})),e.has(FieldPath$1.keyField().canonicalString())||t.C.push(new OrderBy(FieldPath$1.keyField(),r))}return t.C}function __PRIVATE_queryToTarget(e){const t=__PRIVATE_debugCast(e);return t.S||(t.S=__PRIVATE__queryToTarget(t,__PRIVATE_queryNormalizedOrderBy(e))),t.S}function __PRIVATE__queryToTarget(e,t){if("F"===e.limitType)return __PRIVATE_newTarget(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map((e=>{const t="desc"===e.dir?"asc":"desc";return new OrderBy(e.field,t)}));const r=e.endAt?new Bound(e.endAt.position,e.endAt.inclusive):null,n=e.startAt?new Bound(e.startAt.position,e.startAt.inclusive):null;return __PRIVATE_newTarget(e.path,e.collectionGroup,t,e.filters,e.limit,r,n)}}function __PRIVATE_queryWithAddedFilter(e,t){const r=e.filters.concat([t]);return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),r,e.limit,e.limitType,e.startAt,e.endAt)}function __PRIVATE_toDouble(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:__PRIVATE_isNegativeZero(t)?"-0":t}}function toNumber(e,t){return function isSafeInteger(e){return"number"==typeof e&&Number.isInteger(e)&&!__PRIVATE_isNegativeZero(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}(t)?function __PRIVATE_toInteger(e){return{integerValue:""+e}}(t):__PRIVATE_toDouble(e,t)}class TransformOperation{constructor(){this._=void 0}}class __PRIVATE_ServerTimestampTransform extends TransformOperation{}class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation{constructor(e){super(),this.elements=e}}class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation{constructor(e){super(),this.elements=e}}class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation{constructor(e,t){super(),this.serializer=e,this.O=t}}class FieldTransform{constructor(e,t){this.field=e,this.transform=t}}class Precondition{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new Precondition}static exists(e){return new Precondition(void 0,e)}static updateTime(e){return new Precondition(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)}}class Mutation{}class __PRIVATE_SetMutation extends Mutation{constructor(e,t,r,n=[]){super(),this.key=e,this.value=t,this.precondition=r,this.fieldTransforms=n,this.type=0}getFieldMask(){return null}}class __PRIVATE_PatchMutation extends Mutation{constructor(e,t,r,n,i=[]){super(),this.key=e,this.data=t,this.fieldMask=r,this.precondition=n,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}class __PRIVATE_DeleteMutation extends Mutation{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class __PRIVATE_VerifyMutation extends Mutation{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}const k={asc:"ASCENDING",desc:"DESCENDING"},O={"<":"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"},L={and:"AND",or:"OR"};class JsonProtoSerializer{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function toTimestamp(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 __PRIVATE_toBytes(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function __PRIVATE_toVersion(e,t){return toTimestamp(e,t.toTimestamp())}function __PRIVATE_fromVersion(e){return __PRIVATE_hardAssert(!!e),SnapshotVersion.fromTimestamp(function fromTimestamp(e){const t=__PRIVATE_normalizeTimestamp(e);return new Timestamp(t.seconds,t.nanos)}(e))}function __PRIVATE_toResourceName(e,t){return __PRIVATE_toResourcePath(e,t).canonicalString()}function __PRIVATE_toResourcePath(e,t){const r=function __PRIVATE_fullyQualifiedPrefixPath(e){return new ResourcePath(["projects",e.projectId,"databases",e.database])}(e).child("documents");return void 0===t?r:r.child(t)}function __PRIVATE_toName(e,t){return __PRIVATE_toResourceName(e.databaseId,t.path)}function fromName(e,t){const r=function __PRIVATE_fromResourceName(e){const t=ResourcePath.fromString(e);return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(t)),t}(t);if(r.get(1)!==e.databaseId.projectId)throw new FirestoreError(m,"Tried to deserialize key from different project: "+r.get(1)+" vs "+e.databaseId.projectId);if(r.get(3)!==e.databaseId.database)throw new FirestoreError(m,"Tried to deserialize key from different database: "+r.get(3)+" vs "+e.databaseId.database);return new DocumentKey(function __PRIVATE_extractLocalPathFromResourceName(e){return __PRIVATE_hardAssert(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}(r))}function __PRIVATE_toMutationDocument(e,t,r){return{name:__PRIVATE_toName(e,t),fields:r.value.mapValue.fields}}function __PRIVATE_toQueryTarget(e,t){const r={structuredQuery:{}},n=t.path;let i;null!==t.collectionGroup?(i=n,r.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(i=n.popLast(),r.structuredQuery.from=[{collectionId:n.lastSegment()}]),r.parent=function __PRIVATE_toQueryPath(e,t){return __PRIVATE_toResourceName(e.databaseId,t)}(e,i);const s=function __PRIVATE_toFilters(e){if(0!==e.length)return __PRIVATE_toFilter(CompositeFilter.create(e,"and"))}(t.filters);s&&(r.structuredQuery.where=s);const o=function __PRIVATE_toOrder(e){if(0!==e.length)return e.map((e=>function __PRIVATE_toPropertyOrder(e){return{field:__PRIVATE_toFieldPathReference(e.field),direction:__PRIVATE_toDirection(e.dir)}}(e)))}(t.orderBy);o&&(r.structuredQuery.orderBy=o);const a=function __PRIVATE_toInt32Proto(e,t){return e.useProto3Json||__PRIVATE_isNullOrUndefined(t)?t:{value:t}}(e,t.limit);return null!==a&&(r.structuredQuery.limit=a),t.startAt&&(r.structuredQuery.startAt=function __PRIVATE_toStartAtCursor(e){return{before:e.inclusive,values:e.position}}(t.startAt)),t.endAt&&(r.structuredQuery.endAt=function __PRIVATE_toEndAtCursor(e){return{before:!e.inclusive,values:e.position}}(t.endAt)),{q:r,parent:i}}function __PRIVATE_toDirection(e){return k[e]}function __PRIVATE_toOperatorName(e){return O[e]}function __PRIVATE_toCompositeOperatorName(e){return L[e]}function __PRIVATE_toFieldPathReference(e){return{fieldPath:e.canonicalString()}}function __PRIVATE_toFilter(e){return e instanceof FieldFilter?function __PRIVATE_toUnaryOrFieldFilter(e){if("=="===e.op){if(__PRIVATE_isNanValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NAN"}};if(__PRIVATE_isNullValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(__PRIVATE_isNanValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NOT_NAN"}};if(__PRIVATE_isNullValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:__PRIVATE_toOperatorName(e.op),value:e.value}}}(e):e instanceof CompositeFilter?function __PRIVATE_toCompositeFilter(e){const t=e.getFilters().map((e=>__PRIVATE_toFilter(e)));return 1===t.length?t[0]:{compositeFilter:{op:__PRIVATE_toCompositeOperatorName(e.op),filters:t}}}(e):fail()}function __PRIVATE_toDocumentMask(e){const t=[];return e.fields.forEach((e=>t.push(e.canonicalString()))),{fieldPaths:t}}function __PRIVATE_isValidResourceName(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}function __PRIVATE_newSerializer(e){return new JsonProtoSerializer(e,!0)}class __PRIVATE_ExponentialBackoff{constructor(e,t,r=1e3,n=1.5,i=6e4){this.B=e,this.timerId=t,this.$=r,this.L=n,this.M=i,this.k=0,this.U=null,this.j=Date.now(),this.reset()}reset(){this.k=0}W(){this.k=this.M}K(e){this.cancel();const t=Math.floor(this.k+this.G()),r=Math.max(0,Date.now()-this.j),n=Math.max(0,t-r);n>0&&__PRIVATE_logDebug("ExponentialBackoff",`Backing off for ${n} ms (base delay: ${this.k} ms, delay with jitter: ${t} ms, last attempt: ${r} ms ago)`),this.U=this.B.enqueueAfterDelay(this.timerId,n,(()=>(this.j=Date.now(),e()))),this.k*=this.L,this.k<this.$&&(this.k=this.$),this.k>this.M&&(this.k=this.M)}H(){null!==this.U&&(this.U.skipDelay(),this.U=null)}cancel(){null!==this.U&&(this.U.cancel(),this.U=null)}G(){return(Math.random()-.5)*this.k}}class __PRIVATE_DatastoreImpl extends class Datastore{}{constructor(e,t,r,n){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=r,this.serializer=n,this.J=!1}Y(){if(this.J)throw new FirestoreError(y,"The client has already been terminated.")}P(e,t,r,n){return this.Y(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([i,s])=>this.connection.P(e,__PRIVATE_toResourcePath(t,r),n,i,s))).catch((e=>{throw"FirebaseError"===e.name?(e.code===T&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new FirestoreError(f,e.toString())}))}g(e,t,r,n,i){return this.Y(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([s,o])=>this.connection.g(e,__PRIVATE_toResourcePath(t,r),n,s,o,i))).catch((e=>{throw"FirebaseError"===e.name?(e.code===T&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new FirestoreError(f,e.toString())}))}terminate(){this.J=!0,this.connection.terminate()}}async function __PRIVATE_invokeCommitRpc(e,t){const r=__PRIVATE_debugCast(e),n={writes:t.map((e=>function toMutation(e,t){let r;if(t instanceof __PRIVATE_SetMutation)r={update:__PRIVATE_toMutationDocument(e,t.key,t.value)};else if(t instanceof __PRIVATE_DeleteMutation)r={delete:__PRIVATE_toName(e,t.key)};else if(t instanceof __PRIVATE_PatchMutation)r={update:__PRIVATE_toMutationDocument(e,t.key,t.data),updateMask:__PRIVATE_toDocumentMask(t.fieldMask)};else{if(!(t instanceof __PRIVATE_VerifyMutation))return fail();r={verify:__PRIVATE_toName(e,t.key)}}return t.fieldTransforms.length>0&&(r.updateTransforms=t.fieldTransforms.map((e=>function __PRIVATE_toFieldTransform(e,t){const r=t.transform;if(r instanceof __PRIVATE_ServerTimestampTransform)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(r instanceof __PRIVATE_ArrayUnionTransformOperation)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:r.elements}};if(r instanceof __PRIVATE_ArrayRemoveTransformOperation)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:r.elements}};if(r instanceof __PRIVATE_NumericIncrementTransformOperation)return{fieldPath:t.field.canonicalString(),increment:r.O};throw fail()}(0,e)))),t.precondition.isNone||(r.currentDocument=function __PRIVATE_toPrecondition(e,t){return void 0!==t.updateTime?{updateTime:__PRIVATE_toVersion(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:fail()}(e,t.precondition)),r}(r.serializer,e)))};await r.P("Commit",r.serializer.databaseId,ResourcePath.emptyPath(),n)}async function __PRIVATE_invokeBatchGetDocumentsRpc(e,t){const r=__PRIVATE_debugCast(e),n={documents:t.map((e=>__PRIVATE_toName(r.serializer,e)))},i=await r.g("BatchGetDocuments",r.serializer.databaseId,ResourcePath.emptyPath(),n,t.length),s=new Map;i.forEach((e=>{const t=function __PRIVATE_fromBatchGetDocumentsResponse(e,t){return"found"in t?function __PRIVATE_fromFound(e,t){__PRIVATE_hardAssert(!!t.found),t.found.name,t.found.updateTime;const r=fromName(e,t.found.name),n=__PRIVATE_fromVersion(t.found.updateTime),i=t.found.createTime?__PRIVATE_fromVersion(t.found.createTime):SnapshotVersion.min(),s=new ObjectValue({mapValue:{fields:t.found.fields}});return MutableDocument.newFoundDocument(r,n,i,s)}(e,t):"missing"in t?function __PRIVATE_fromMissing(e,t){__PRIVATE_hardAssert(!!t.missing),__PRIVATE_hardAssert(!!t.readTime);const r=fromName(e,t.missing),n=__PRIVATE_fromVersion(t.readTime);return MutableDocument.newNoDocument(r,n)}(e,t):fail()}(r.serializer,e);s.set(t.key.toString(),t)}));const o=[];return t.forEach((e=>{const t=s.get(e.toString());__PRIVATE_hardAssert(!!t),o.push(t)})),o}const q=new Map;function __PRIVATE_getDatastore(e){if(e._terminated)throw new FirestoreError(y,"The client has already been terminated.");if(!q.has(e)){__PRIVATE_logDebug("ComponentProvider","Initializing Datastore");const t=function __PRIVATE_newConnection(e){return new __PRIVATE_FetchConnection(e)}(function __PRIVATE_makeDatabaseInfo(e,t,r,n){return new DatabaseInfo(e,t,r,n.host,n.ssl,n.experimentalForceLongPolling,n.experimentalAutoDetectLongPolling,__PRIVATE_cloneLongPollingOptions(n.experimentalLongPollingOptions),n.useFetchStreams)}(e._databaseId,e.app.options.appId||"",e._persistenceKey,e._freezeSettings())),r=__PRIVATE_newSerializer(e._databaseId),n=function __PRIVATE_newDatastore(e,t,r,n){return new __PRIVATE_DatastoreImpl(e,t,r,n)}(e._authCredentials,e._appCheckCredentials,t,r);q.set(e,n)}return q.get(e)}class FirestoreSettingsImpl{constructor(e){var t,r;if(void 0===e.host){if(void 0!==e.ssl)throw new FirestoreError(m,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new FirestoreError(m,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}!function __PRIVATE_validateIsNotUsedTogether(e,t,r,n){if(!0===t&&!0===n)throw new FirestoreError(m,`${e} and ${r} 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=__PRIVATE_cloneLongPollingOptions(null!==(r=e.experimentalLongPollingOptions)&&void 0!==r?r:{}),function __PRIVATE_validateLongPollingOptions(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new FirestoreError(m,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new FirestoreError(m,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new FirestoreError(m,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&function __PRIVATE_longPollingOptionsEqual(e,t){return e.timeoutSeconds===t.timeoutSeconds}(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class Firestore{constructor(e,t,r,n){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=r,this._app=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new FirestoreSettingsImpl({}),this._settingsFrozen=!1,this._terminateTask="notTerminated"}get app(){if(!this._app)throw new FirestoreError(y,"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 FirestoreError(y,"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 FirestoreSettingsImpl(e),void 0!==e.credentials&&(this._authCredentials=function __PRIVATE_makeAuthCredentialsProvider(e){if(!e)return new __PRIVATE_EmptyAuthCredentialsProvider;switch(e.type){case"firstParty":return new __PRIVATE_FirstPartyAuthCredentialsProvider(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new FirestoreError(m,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_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 __PRIVATE_removeComponents(e){const t=q.get(e);t&&(__PRIVATE_logDebug("ComponentProvider","Removing Datastore"),q.delete(e),t.terminate())}(this),Promise.resolve()}}function initializeFirestore(e,t,r){r||(r="(default)");const n=_getProvider(e,"firestore/lite");if(n.isInitialized(r))throw new FirestoreError(y,"Firestore can only be initialized once per app.");return n.initialize({options:t,instanceIdentifier:r})}function getFirestore(e,t){const n="object"==typeof e?e:r(),i="string"==typeof e?e:t||"(default)",s=_getProvider(n,"firestore/lite").getImmediate({identifier:i});if(!s._initialized){const e=getDefaultEmulatorHostnameAndPort("firestore");e&&connectFirestoreEmulator(s,...e)}return s}function connectFirestoreEmulator(e,t,r,n={}){var i;const s=(e=__PRIVATE_cast(e,Firestore))._getSettings(),o=`${t}:${r}`;if("firestore.googleapis.com"!==s.host&&s.host!==o&&__PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),e._setSettings(Object.assign(Object.assign({},s),{host:o,ssl:!1})),n.mockUserToken){let t,r;if("string"==typeof n.mockUserToken)t=n.mockUserToken,r=User.MOCK_USER;else{t=function createMockUserToken(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const r=t||"demo-project",n=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const s=Object.assign({iss:`https://securetoken.google.com/${r}`,aud:r,iat:n,exp:n+3600,auth_time:n,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e);return[base64urlEncodeWithoutPadding(JSON.stringify({alg:"none",type:"JWT"})),base64urlEncodeWithoutPadding(JSON.stringify(s)),""].join(".")}(n.mockUserToken,null===(i=e._app)||void 0===i?void 0:i.options.projectId);const s=n.mockUserToken.sub||n.mockUserToken.user_id;if(!s)throw new FirestoreError(m,"mockUserToken must contain 'sub' or 'user_id' field!");r=new User(s)}e._authCredentials=new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(t,r))}}function terminate(e){return e=__PRIVATE_cast(e,Firestore),n(e.app,"firestore/lite"),e._delete()}class AggregateField{constructor(e="count",t){this._internalFieldPath=t,this.type="AggregateField",this.aggregateType=e}}class AggregateQuerySnapshot{constructor(e,t,r){this._userDataWriter=t,this._data=r,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}}class Query{constructor(e,t,r){this.converter=t,this._query=r,this.type="query",this.firestore=e}withConverter(e){return new Query(this.firestore,e,this._query)}}class DocumentReference{constructor(e,t,r){this.converter=t,this._key=r,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 CollectionReference(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new DocumentReference(this.firestore,e,this._key)}}class CollectionReference extends Query{constructor(e,t,r){super(e,t,function __PRIVATE_newQueryForPath(e){return new __PRIVATE_QueryImpl(e)}(r)),this._path=r,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new DocumentReference(this.firestore,null,new DocumentKey(e))}withConverter(e){return new CollectionReference(this.firestore,e,this._path)}}function collection(e,t,...r){if(e=getModularInstance(e),__PRIVATE_validateNonEmptyArgument("collection","path",t),e instanceof Firestore){const n=ResourcePath.fromString(t,...r);return __PRIVATE_validateCollectionPath(n),new CollectionReference(e,null,n)}{if(!(e instanceof DocumentReference||e instanceof CollectionReference))throw new FirestoreError(m,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const n=e._path.child(ResourcePath.fromString(t,...r));return __PRIVATE_validateCollectionPath(n),new CollectionReference(e.firestore,null,n)}}function collectionGroup(e,t){if(e=__PRIVATE_cast(e,Firestore),__PRIVATE_validateNonEmptyArgument("collectionGroup","collection id",t),t.indexOf("/")>=0)throw new FirestoreError(m,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Query(e,null,function __PRIVATE_newQueryForCollectionGroup(e){return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(),e)}(t))}function doc(e,t,...r){if(e=getModularInstance(e),1===arguments.length&&(t=__PRIVATE_AutoId.newId()),__PRIVATE_validateNonEmptyArgument("doc","path",t),e instanceof Firestore){const n=ResourcePath.fromString(t,...r);return __PRIVATE_validateDocumentPath(n),new DocumentReference(e,null,new DocumentKey(n))}{if(!(e instanceof DocumentReference||e instanceof CollectionReference))throw new FirestoreError(m,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const n=e._path.child(ResourcePath.fromString(t,...r));return __PRIVATE_validateDocumentPath(n),new DocumentReference(e.firestore,e instanceof CollectionReference?e.converter:null,new DocumentKey(n))}}function refEqual(e,t){return e=getModularInstance(e),t=getModularInstance(t),(e instanceof DocumentReference||e instanceof CollectionReference)&&(t instanceof DocumentReference||t instanceof CollectionReference)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function queryEqual(e,t){return e=getModularInstance(e),t=getModularInstance(t),e instanceof Query&&t instanceof Query&&e.firestore===t.firestore&&function __PRIVATE_queryEquals(e,t){return function __PRIVATE_targetEquals(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let r=0;r<e.orderBy.length;r++)if(!__PRIVATE_orderByEquals(e.orderBy[r],t.orderBy[r]))return!1;if(e.filters.length!==t.filters.length)return!1;for(let r=0;r<e.filters.length;r++)if(!__PRIVATE_filterEquals(e.filters[r],t.filters[r]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!__PRIVATE_boundEquals(e.startAt,t.startAt)&&__PRIVATE_boundEquals(e.endAt,t.endAt)}(__PRIVATE_queryToTarget(e),__PRIVATE_queryToTarget(t))&&e.limitType===t.limitType}(e._query,t._query)&&e.converter===t.converter}class Bytes{constructor(e){this._byteString=e}static fromBase64String(e){try{return new Bytes(ByteString.fromBase64String(e))}catch(e){throw new FirestoreError(m,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new Bytes(ByteString.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class FieldPath{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new FirestoreError(m,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new FieldPath$1(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}function documentId(){return new FieldPath("__name__")}class FieldValue{constructor(e){this._methodName=e}}class GeoPoint{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new FirestoreError(m,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new FirestoreError(m,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return __PRIVATE_primitiveComparator(this._lat,e._lat)||__PRIVATE_primitiveComparator(this._long,e._long)}}class VectorValue{constructor(e){this._values=(e||[]).map((e=>e))}toArray(){return this._values.map((e=>e))}isEqual(e){return function __PRIVATE_isPrimitiveArrayEqual(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;++r)if(e[r]!==t[r])return!1;return!0}(this._values,e._values)}}const M=/^__.*__$/;class ParsedSetData{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return null!==this.fieldMask?new __PRIVATE_PatchMutation(e,this.data,this.fieldMask,t,this.fieldTransforms):new __PRIVATE_SetMutation(e,this.data,t,this.fieldTransforms)}}class ParsedUpdateData{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return new __PRIVATE_PatchMutation(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function __PRIVATE_isWrite(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw fail()}}class __PRIVATE_ParseContextImpl{constructor(e,t,r,n,i,s){this.settings=e,this.databaseId=t,this.serializer=r,this.ignoreUndefinedProperties=n,void 0===i&&this.X(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get tt(){return this.settings.tt}et(e){return new __PRIVATE_ParseContextImpl(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}rt(e){var t;const r=null===(t=this.path)||void 0===t?void 0:t.child(e),n=this.et({path:r,nt:!1});return n.it(e),n}st(e){var t;const r=null===(t=this.path)||void 0===t?void 0:t.child(e),n=this.et({path:r,nt:!1});return n.X(),n}ot(e){return this.et({path:void 0,nt:!0})}ut(e){return __PRIVATE_createError(e,this.settings.methodName,this.settings._t||!1,this.path,this.settings.ct)}contains(e){return void 0!==this.fieldMask.find((t=>e.isPrefixOf(t)))||void 0!==this.fieldTransforms.find((t=>e.isPrefixOf(t.field)))}X(){if(this.path)for(let e=0;e<this.path.length;e++)this.it(this.path.get(e))}it(e){if(0===e.length)throw this.ut("Document fields must not be empty");if(__PRIVATE_isWrite(this.tt)&&M.test(e))throw this.ut('Document fields cannot begin and end with "__"')}}class __PRIVATE_UserDataReader{constructor(e,t,r){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=r||__PRIVATE_newSerializer(e)}lt(e,t,r,n=!1){return new __PRIVATE_ParseContextImpl({tt:e,methodName:t,ct:r,path:FieldPath$1.emptyPath(),nt:!1,_t:n},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function __PRIVATE_newUserDataReader(e){const t=e._freezeSettings(),r=__PRIVATE_newSerializer(e._databaseId);return new __PRIVATE_UserDataReader(e._databaseId,!!t.ignoreUndefinedProperties,r)}function __PRIVATE_parseSetData(e,t,r,n,i,s={}){const o=e.lt(s.merge||s.mergeFields?2:0,t,r,i);__PRIVATE_validatePlainObject("Data must be an object, but it was:",o,n);const a=__PRIVATE_parseObject(n,o);let u,l;if(s.merge)u=new FieldMask(o.fieldMask),l=o.fieldTransforms;else if(s.mergeFields){const e=[];for(const n of s.mergeFields){const i=__PRIVATE_fieldPathFromArgument$1(t,n,r);if(!o.contains(i))throw new FirestoreError(m,`Field '${i}' is specified in your field mask but missing from your input data.`);__PRIVATE_fieldMaskContains(e,i)||e.push(i)}u=new FieldMask(e),l=o.fieldTransforms.filter((e=>u.covers(e.field)))}else u=null,l=o.fieldTransforms;return new ParsedSetData(new ObjectValue(a),u,l)}class __PRIVATE_DeleteFieldValueImpl extends FieldValue{_toFieldTransform(e){if(2!==e.tt)throw 1===e.tt?e.ut(`${this._methodName}() can only appear at the top level of your update data`):e.ut(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof __PRIVATE_DeleteFieldValueImpl}}function __PRIVATE_createSentinelChildContext(e,t,r){return new __PRIVATE_ParseContextImpl({tt:3,ct:t.settings.ct,methodName:e._methodName,nt:r},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue{_toFieldTransform(e){return new FieldTransform(e.path,new __PRIVATE_ServerTimestampTransform)}isEqual(e){return e instanceof __PRIVATE_ServerTimestampFieldValueImpl}}class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue{constructor(e,t){super(e),this.ht=t}_toFieldTransform(e){const t=__PRIVATE_createSentinelChildContext(this,e,!0),r=this.ht.map((e=>__PRIVATE_parseData(e,t))),n=new __PRIVATE_ArrayUnionTransformOperation(r);return new FieldTransform(e.path,n)}isEqual(e){return e instanceof __PRIVATE_ArrayUnionFieldValueImpl&&deepEqual(this.ht,e.ht)}}class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue{constructor(e,t){super(e),this.ht=t}_toFieldTransform(e){const t=__PRIVATE_createSentinelChildContext(this,e,!0),r=this.ht.map((e=>__PRIVATE_parseData(e,t))),n=new __PRIVATE_ArrayRemoveTransformOperation(r);return new FieldTransform(e.path,n)}isEqual(e){return e instanceof __PRIVATE_ArrayRemoveFieldValueImpl&&deepEqual(this.ht,e.ht)}}class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue{constructor(e,t){super(e),this.dt=t}_toFieldTransform(e){const t=new __PRIVATE_NumericIncrementTransformOperation(e.serializer,toNumber(e.serializer,this.dt));return new FieldTransform(e.path,t)}isEqual(e){return e instanceof __PRIVATE_NumericIncrementFieldValueImpl&&this.dt===e.dt}}function __PRIVATE_parseUpdateData(e,t,r,n){const i=e.lt(1,t,r);__PRIVATE_validatePlainObject("Data must be an object, but it was:",i,n);const s=[],o=ObjectValue.empty();forEach(n,((e,n)=>{const a=__PRIVATE_fieldPathFromDotSeparatedString(t,e,r);n=getModularInstance(n);const u=i.st(a);if(n instanceof __PRIVATE_DeleteFieldValueImpl)s.push(a);else{const e=__PRIVATE_parseData(n,u);null!=e&&(s.push(a),o.set(a,e))}}));const a=new FieldMask(s);return new ParsedUpdateData(o,a,i.fieldTransforms)}function __PRIVATE_parseUpdateVarargs(e,t,r,n,i,s){const o=e.lt(1,t,r),a=[__PRIVATE_fieldPathFromArgument$1(t,n,r)],u=[i];if(s.length%2!=0)throw new FirestoreError(m,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let e=0;e<s.length;e+=2)a.push(__PRIVATE_fieldPathFromArgument$1(t,s[e])),u.push(s[e+1]);const l=[],c=ObjectValue.empty();for(let e=a.length-1;e>=0;--e)if(!__PRIVATE_fieldMaskContains(l,a[e])){const t=a[e];let r=u[e];r=getModularInstance(r);const n=o.st(t);if(r instanceof __PRIVATE_DeleteFieldValueImpl)l.push(t);else{const e=__PRIVATE_parseData(r,n);null!=e&&(l.push(t),c.set(t,e))}}const _=new FieldMask(l);return new ParsedUpdateData(c,_,o.fieldTransforms)}function __PRIVATE_parseQueryValue(e,t,r,n=!1){return __PRIVATE_parseData(r,e.lt(n?4:3,t))}function __PRIVATE_parseData(e,t){if(__PRIVATE_looksLikeJsonObject(e=getModularInstance(e)))return __PRIVATE_validatePlainObject("Unsupported field value:",t,e),__PRIVATE_parseObject(e,t);if(e instanceof FieldValue)return function __PRIVATE_parseSentinelFieldValue(e,t){if(!__PRIVATE_isWrite(t.tt))throw t.ut(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.ut(`${e._methodName}() is not currently supported inside arrays`);const r=e._toFieldTransform(t);r&&t.fieldTransforms.push(r)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.nt&&4!==t.tt)throw t.ut("Nested arrays are not supported");return function __PRIVATE_parseArray(e,t){const r=[];let n=0;for(const i of e){let e=__PRIVATE_parseData(i,t.ot(n));null==e&&(e={nullValue:"NULL_VALUE"}),r.push(e),n++}return{arrayValue:{values:r}}}(e,t)}return function __PRIVATE_parseScalarValue(e,t){if(null===(e=getModularInstance(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return toNumber(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const r=Timestamp.fromDate(e);return{timestampValue:toTimestamp(t.serializer,r)}}if(e instanceof Timestamp){const r=new Timestamp(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:toTimestamp(t.serializer,r)}}if(e instanceof GeoPoint)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Bytes)return{bytesValue:__PRIVATE_toBytes(t.serializer,e._byteString)};if(e instanceof DocumentReference){const r=t.databaseId,n=e.firestore._databaseId;if(!n.isEqual(r))throw t.ut(`Document reference is for database ${n.projectId}/${n.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:__PRIVATE_toResourceName(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof VectorValue)return function __PRIVATE_parseVectorValue(e,t){return{mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{values:e.toArray().map((e=>{if("number"!=typeof e)throw t.ut("VectorValues must only contain numeric values.");return __PRIVATE_toDouble(t.serializer,e)}))}}}}}}(e,t);throw t.ut(`Unsupported field value: ${__PRIVATE_valueDescription(e)}`)}(e,t)}function __PRIVATE_parseObject(e,t){const r={};return function isEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):forEach(e,((e,n)=>{const i=__PRIVATE_parseData(n,t.rt(e));null!=i&&(r[e]=i)})),{mapValue:{fields:r}}}function __PRIVATE_looksLikeJsonObject(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Timestamp||e instanceof GeoPoint||e instanceof Bytes||e instanceof DocumentReference||e instanceof FieldValue||e instanceof VectorValue)}function __PRIVATE_validatePlainObject(e,t,r){if(!__PRIVATE_looksLikeJsonObject(r)||!function __PRIVATE_isPlainObject(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(r)){const n=__PRIVATE_valueDescription(r);throw"an object"===n?t.ut(e+" a custom object"):t.ut(e+" "+n)}}function __PRIVATE_fieldPathFromArgument$1(e,t,r){if((t=getModularInstance(t))instanceof FieldPath)return t._internalPath;if("string"==typeof t)return __PRIVATE_fieldPathFromDotSeparatedString(e,t);throw __PRIVATE_createError("Field path arguments must be of type string or ",e,!1,void 0,r)}const B=new RegExp("[~\\*/\\[\\]]");function __PRIVATE_fieldPathFromDotSeparatedString(e,t,r){if(t.search(B)>=0)throw __PRIVATE_createError(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,r);try{return new FieldPath(...t.split("."))._internalPath}catch(n){throw __PRIVATE_createError(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,r)}}function __PRIVATE_createError(e,t,r,n,i){const s=n&&!n.isEmpty(),o=void 0!==i;let a=`Function ${t}() called with invalid data`;r&&(a+=" (via `toFirestore()`)"),a+=". ";let u="";return(s||o)&&(u+=" (found",s&&(u+=` in field ${n}`),o&&(u+=` in document ${i}`),u+=")"),new FirestoreError(m,a+e+u)}function __PRIVATE_fieldMaskContains(e,t){return e.some((e=>e.isEqual(t)))}class DocumentSnapshot{constructor(e,t,r,n,i){this._firestore=e,this._userDataWriter=t,this._key=r,this._document=n,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new DocumentReference(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new QueryDocumentSnapshot(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){const t=this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class QueryDocumentSnapshot extends DocumentSnapshot{data(){return super.data()}}class QuerySnapshot{constructor(e,t){this._docs=t,this.query=e}get docs(){return[...this._docs]}get size(){return this.docs.length}get empty(){return 0===this.docs.length}forEach(e,t){this._docs.forEach(e,t)}}function snapshotEqual(e,t){return e=getModularInstance(e),t=getModularInstance(t),e instanceof DocumentSnapshot&&t instanceof DocumentSnapshot?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof QuerySnapshot&&t instanceof QuerySnapshot&&queryEqual(e.query,t.query)&&__PRIVATE_arrayEquals(e.docs,t.docs,snapshotEqual)}function __PRIVATE_fieldPathFromArgument(e,t){return"string"==typeof t?__PRIVATE_fieldPathFromDotSeparatedString(e,t):t instanceof FieldPath?t._internalPath:t._delegate._internalPath}class AppliableConstraint{}class QueryConstraint extends AppliableConstraint{}function query(e,t,...r){let n=[];t instanceof AppliableConstraint&&n.push(t),n=n.concat(r),function __PRIVATE_validateQueryConstraintArray(e){const t=e.filter((e=>e instanceof QueryCompositeFilterConstraint)).length,r=e.filter((e=>e instanceof QueryFieldFilterConstraint)).length;if(t>1||t>0&&r>0)throw new FirestoreError(m,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(n);for(const t of n)e=t._apply(e);return e}class QueryFieldFilterConstraint extends QueryConstraint{constructor(e,t,r){super(),this._field=e,this._op=t,this._value=r,this.type="where"}static _create(e,t,r){return new QueryFieldFilterConstraint(e,t,r)}_apply(e){const t=this._parse(e);return __PRIVATE_validateNewFieldFilter(e._query,t),new Query(e.firestore,e.converter,__PRIVATE_queryWithAddedFilter(e._query,t))}_parse(e){const t=__PRIVATE_newUserDataReader(e.firestore),r=function __PRIVATE_newQueryFilter(e,t,r,n,i,s,o){let a;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new FirestoreError(m,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){__PRIVATE_validateDisjunctiveFilterElements(o,s);const t=[];for(const r of o)t.push(__PRIVATE_parseDocumentIdValue(n,e,r));a={arrayValue:{values:t}}}else a=__PRIVATE_parseDocumentIdValue(n,e,o)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||__PRIVATE_validateDisjunctiveFilterElements(o,s),a=__PRIVATE_parseQueryValue(r,t,o,"in"===s||"not-in"===s);return FieldFilter.create(i,s,a)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value);return r}}function where(e,t,r){const n=t,i=__PRIVATE_fieldPathFromArgument("where",e);return QueryFieldFilterConstraint._create(i,n,r)}class QueryCompositeFilterConstraint extends AppliableConstraint{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new QueryCompositeFilterConstraint(e,t)}_parse(e){const t=this._queryConstraints.map((t=>t._parse(e))).filter((e=>e.getFilters().length>0));return 1===t.length?t[0]:CompositeFilter.create(t,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function __PRIVATE_validateNewFilter(e,t){let r=e;const n=t.getFlattenedFilters();for(const e of n)__PRIVATE_validateNewFieldFilter(r,e),r=__PRIVATE_queryWithAddedFilter(r,e)}(e._query,t),new Query(e.firestore,e.converter,__PRIVATE_queryWithAddedFilter(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}function or(...e){return e.forEach((e=>__PRIVATE_validateQueryFilterConstraint("or",e))),QueryCompositeFilterConstraint._create("or",e)}function and(...e){return e.forEach((e=>__PRIVATE_validateQueryFilterConstraint("and",e))),QueryCompositeFilterConstraint._create("and",e)}class QueryOrderByConstraint extends QueryConstraint{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new QueryOrderByConstraint(e,t)}_apply(e){const t=function __PRIVATE_newQueryOrderBy(e,t,r){if(null!==e.startAt)throw new FirestoreError(m,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new FirestoreError(m,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new OrderBy(t,r)}(e._query,this._field,this._direction);return new Query(e.firestore,e.converter,function __PRIVATE_queryWithAddedOrderBy(e,t){const r=e.explicitOrderBy.concat([t]);return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,r,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,t))}}function orderBy(e,t="asc"){const r=t,n=__PRIVATE_fieldPathFromArgument("orderBy",e);return QueryOrderByConstraint._create(n,r)}class QueryLimitConstraint extends QueryConstraint{constructor(e,t,r){super(),this.type=e,this._limit=t,this._limitType=r}static _create(e,t,r){return new QueryLimitConstraint(e,t,r)}_apply(e){return new Query(e.firestore,e.converter,function __PRIVATE_queryWithLimit(e,t,r){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,r,e.startAt,e.endAt)}(e._query,this._limit,this._limitType))}}function limit(e){return __PRIVATE_validatePositiveNumber("limit",e),QueryLimitConstraint._create("limit",e,"F")}function limitToLast(e){return __PRIVATE_validatePositiveNumber("limitToLast",e),QueryLimitConstraint._create("limitToLast",e,"L")}class QueryStartAtConstraint extends QueryConstraint{constructor(e,t,r){super(),this.type=e,this._docOrFields=t,this._inclusive=r}static _create(e,t,r){return new QueryStartAtConstraint(e,t,r)}_apply(e){const t=__PRIVATE_newQueryBoundFromDocOrFields(e,this.type,this._docOrFields,this._inclusive);return new Query(e.firestore,e.converter,function __PRIVATE_queryWithStartAt(e,t){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,t,e.endAt)}(e._query,t))}}function startAt(...e){return QueryStartAtConstraint._create("startAt",e,!0)}function startAfter(...e){return QueryStartAtConstraint._create("startAfter",e,!1)}class QueryEndAtConstraint extends QueryConstraint{constructor(e,t,r){super(),this.type=e,this._docOrFields=t,this._inclusive=r}static _create(e,t,r){return new QueryEndAtConstraint(e,t,r)}_apply(e){const t=__PRIVATE_newQueryBoundFromDocOrFields(e,this.type,this._docOrFields,this._inclusive);return new Query(e.firestore,e.converter,function __PRIVATE_queryWithEndAt(e,t){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,t)}(e._query,t))}}function endBefore(...e){return QueryEndAtConstraint._create("endBefore",e,!1)}function endAt(...e){return QueryEndAtConstraint._create("endAt",e,!0)}function __PRIVATE_newQueryBoundFromDocOrFields(e,t,r,n){if(r[0]=getModularInstance(r[0]),r[0]instanceof DocumentSnapshot)return function __PRIVATE_newQueryBoundFromDocument(e,t,r,n,i){if(!n)throw new FirestoreError(g,`Can't use a DocumentSnapshot that doesn't exist for ${r}().`);const s=[];for(const r of __PRIVATE_queryNormalizedOrderBy(e))if(r.field.isKeyField())s.push(__PRIVATE_refValue(t,n.key));else{const e=n.data.field(r.field);if(__PRIVATE_isServerTimestamp(e))throw new FirestoreError(m,'Invalid query. You are trying to start or end a query using a document for which the field "'+r.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){const e=r.field.canonicalString();throw new FirestoreError(m,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}s.push(e)}return new Bound(s,i)}(e._query,e.firestore._databaseId,t,r[0]._document,n);{const i=__PRIVATE_newUserDataReader(e.firestore);return function __PRIVATE_newQueryBoundFromFields(e,t,r,n,i,s){const o=e.explicitOrderBy;if(i.length>o.length)throw new FirestoreError(m,`Too many arguments provided to ${n}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const a=[];for(let s=0;s<i.length;s++){const u=i[s];if(o[s].field.isKeyField()){if("string"!=typeof u)throw new FirestoreError(m,`Invalid query. Expected a string for document ID in ${n}(), but got a ${typeof u}`);if(!__PRIVATE_isCollectionGroupQuery(e)&&-1!==u.indexOf("/"))throw new FirestoreError(m,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${n}() must be a plain document ID, but '${u}' contains a slash.`);const r=e.path.child(ResourcePath.fromString(u));if(!DocumentKey.isDocumentKey(r))throw new FirestoreError(m,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${n}() must result in a valid document path, but '${r}' is not because it contains an odd number of segments.`);const i=new DocumentKey(r);a.push(__PRIVATE_refValue(t,i))}else{const e=__PRIVATE_parseQueryValue(r,n,u);a.push(e)}}return new Bound(a,s)}(e._query,e.firestore._databaseId,i,t,r,n)}}function __PRIVATE_parseDocumentIdValue(e,t,r){if("string"==typeof(r=getModularInstance(r))){if(""===r)throw new FirestoreError(m,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!__PRIVATE_isCollectionGroupQuery(t)&&-1!==r.indexOf("/"))throw new FirestoreError(m,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${r}' contains a '/' character.`);const n=t.path.child(ResourcePath.fromString(r));if(!DocumentKey.isDocumentKey(n))throw new FirestoreError(m,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${n}' is not because it has an odd number of segments (${n.length}).`);return __PRIVATE_refValue(e,new DocumentKey(n))}if(r instanceof DocumentReference)return __PRIVATE_refValue(e,r._key);throw new FirestoreError(m,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(r)}.`)}function __PRIVATE_validateDisjunctiveFilterElements(e,t){if(!Array.isArray(e)||0===e.length)throw new FirestoreError(m,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function __PRIVATE_validateNewFieldFilter(e,t){const r=function __PRIVATE_findOpInsideFilters(e,t){for(const r of e)for(const e of r.getFlattenedFilters())if(t.indexOf(e.op)>=0)return e.op;return null}(e.filters,function __PRIVATE_conflictingOps(e){switch(e){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}(t.op));if(null!==r)throw r===t.op?new FirestoreError(m,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new FirestoreError(m,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}function __PRIVATE_validateQueryFilterConstraint(e,t){if(!(t instanceof QueryFieldFilterConstraint||t instanceof QueryCompositeFilterConstraint))throw new FirestoreError(m,`Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}function __PRIVATE_applyFirestoreDataConverter(e,t,r){let n;return n=e?r&&(r.merge||r.mergeFields)?e.toFirestore(t,r):e.toFirestore(t):t,n}class __PRIVATE_LiteUserDataWriter extends class AbstractUserDataWriter{convertValue(e,t="none"){switch(__PRIVATE_typeOrder(e)){case 0:return null;case 1:return e.booleanValue;case 2:return __PRIVATE_normalizeNumber(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(__PRIVATE_normalizeByteString(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 fail()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){const r={};return forEach(e,((e,n)=>{r[e]=this.convertValue(n,t)})),r}convertVectorValue(e){var t,r,n;const i=null===(n=null===(r=null===(t=e.fields)||void 0===t?void 0:t.value.arrayValue)||void 0===r?void 0:r.values)||void 0===n?void 0:n.map((e=>__PRIVATE_normalizeNumber(e.doubleValue)));return new VectorValue(i)}convertGeoPoint(e){return new GeoPoint(__PRIVATE_normalizeNumber(e.latitude),__PRIVATE_normalizeNumber(e.longitude))}convertArray(e,t){return(e.values||[]).map((e=>this.convertValue(e,t)))}convertServerTimestamp(e,t){switch(t){case"previous":const r=__PRIVATE_getPreviousValue(e);return null==r?null:this.convertValue(r,t);case"estimate":return this.convertTimestamp(__PRIVATE_getLocalWriteTime(e));default:return null}}convertTimestamp(e){const t=__PRIVATE_normalizeTimestamp(e);return new Timestamp(t.seconds,t.nanos)}convertDocumentKey(e,t){const r=ResourcePath.fromString(e);__PRIVATE_hardAssert(__PRIVATE_isValidResourceName(r));const n=new DatabaseId(r.get(1),r.get(3)),i=new DocumentKey(r.popFirst(5));return n.isEqual(t)||__PRIVATE_logError(`Document ${i} contains a document reference within a different database (${n.projectId}/${n.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}{constructor(e){super(),this.firestore=e}convertBytes(e){return new Bytes(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new DocumentReference(this.firestore,null,t)}}function getDoc(e){const t=__PRIVATE_getDatastore((e=__PRIVATE_cast(e,DocumentReference)).firestore),r=new __PRIVATE_LiteUserDataWriter(e.firestore);return __PRIVATE_invokeBatchGetDocumentsRpc(t,[e._key]).then((t=>{__PRIVATE_hardAssert(1===t.length);const n=t[0];return new DocumentSnapshot(e.firestore,r,e._key,n.isFoundDocument()?n:null,e.converter)}))}function getDocs(e){!function __PRIVATE_validateHasExplicitOrderByForLimitToLast(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new FirestoreError(P,"limitToLast() queries require specifying at least one orderBy() clause")}((e=__PRIVATE_cast(e,Query))._query);const t=__PRIVATE_getDatastore(e.firestore),r=new __PRIVATE_LiteUserDataWriter(e.firestore);return async function __PRIVATE_invokeRunQueryRpc(e,t){const r=__PRIVATE_debugCast(e),{q:n,parent:i}=__PRIVATE_toQueryTarget(r.serializer,__PRIVATE_queryToTarget(t));return(await r.g("RunQuery",r.serializer.databaseId,i,{structuredQuery:n.structuredQuery})).filter((e=>!!e.document)).map((e=>function __PRIVATE_fromDocument(e,t,r){const n=fromName(e,t.name),i=__PRIVATE_fromVersion(t.updateTime),s=t.createTime?__PRIVATE_fromVersion(t.createTime):SnapshotVersion.min(),o=new ObjectValue({mapValue:{fields:t.fields}}),a=MutableDocument.newFoundDocument(n,i,s,o);return r&&a.setHasCommittedMutations(),r?a.setHasCommittedMutations():a}(r.serializer,e.document,void 0)))}(t,e._query).then((t=>{const n=t.map((t=>new QueryDocumentSnapshot(e.firestore,r,t.key,t,e.converter)));return"L"===e._query.limitType&&n.reverse(),new QuerySnapshot(e,n)}))}function setDoc(e,t,r){const n=__PRIVATE_applyFirestoreDataConverter((e=__PRIVATE_cast(e,DocumentReference)).converter,t,r),i=__PRIVATE_parseSetData(__PRIVATE_newUserDataReader(e.firestore),"setDoc",e._key,n,null!==e.converter,r);return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(e.firestore),[i.toMutation(e._key,Precondition.none())])}function updateDoc(e,t,r,...n){const i=__PRIVATE_newUserDataReader((e=__PRIVATE_cast(e,DocumentReference)).firestore);let s;return s="string"==typeof(t=getModularInstance(t))||t instanceof FieldPath?__PRIVATE_parseUpdateVarargs(i,"updateDoc",e._key,t,r,n):__PRIVATE_parseUpdateData(i,"updateDoc",e._key,t),__PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(e.firestore),[s.toMutation(e._key,Precondition.exists(!0))])}function deleteDoc(e){return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore((e=__PRIVATE_cast(e,DocumentReference)).firestore),[new __PRIVATE_DeleteMutation(e._key,Precondition.none())])}function addDoc(e,t){const r=doc(e=__PRIVATE_cast(e,CollectionReference)),n=__PRIVATE_applyFirestoreDataConverter(e.converter,t),i=__PRIVATE_parseSetData(__PRIVATE_newUserDataReader(e.firestore),"addDoc",r._key,n,null!==r.converter,{});return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(e.firestore),[i.toMutation(r._key,Precondition.exists(!1))]).then((()=>r))}function getCount(e){return getAggregate(e,{count:count()})}function getAggregate(e,t){const r=__PRIVATE_cast(e.firestore,Firestore),n=__PRIVATE_getDatastore(r),i=function __PRIVATE_mapToArray(e,t){const r=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&r.push(t(e[n],n,e));return r}(t,((e,t)=>new __PRIVATE_AggregateImpl(t,e.aggregateType,e._internalFieldPath)));return async function __PRIVATE_invokeRunAggregationQueryRpc(e,t,r){var n;const i=__PRIVATE_debugCast(e),{request:s,Z:o,parent:a}=function __PRIVATE_toRunAggregationQueryRequest(e,t,r,n){const{q:i,parent:s}=__PRIVATE_toQueryTarget(e,t),o={},a=[];let u=0;return r.forEach((e=>{const t=n?e.alias:"aggregate_"+u++;o[t]=e.alias,"count"===e.aggregateType?a.push({alias:t,count:{}}):"avg"===e.aggregateType?a.push({alias:t,avg:{field:__PRIVATE_toFieldPathReference(e.fieldPath)}}):"sum"===e.aggregateType&&a.push({alias:t,sum:{field:__PRIVATE_toFieldPathReference(e.fieldPath)}})})),{request:{structuredAggregationQuery:{aggregations:a,structuredQuery:i.structuredQuery},parent:i.parent},Z:o,parent:s}}(i.serializer,function __PRIVATE_queryToAggregateTarget(e){const t=__PRIVATE_debugCast(e);return t.N||(t.N=__PRIVATE__queryToTarget(t,e.explicitOrderBy)),t.N}(t),r);i.connection.R||delete s.parent;const u=(await i.g("RunAggregationQuery",i.serializer.databaseId,a,s,1)).filter((e=>!!e.result));__PRIVATE_hardAssert(1===u.length);const l=null===(n=u[0].result)||void 0===n?void 0:n.aggregateFields;return Object.keys(l).reduce(((e,t)=>(e[o[t]]=l[t],e)),{})}(n,e._query,i).then((t=>function __PRIVATE_convertToAggregateQuerySnapshot(e,t,r){const n=new __PRIVATE_LiteUserDataWriter(e);return new AggregateQuerySnapshot(t,n,r)}(r,e,t)))}function sum(e){return new AggregateField("sum",__PRIVATE_fieldPathFromArgument$1("sum",e))}function average(e){return new AggregateField("avg",__PRIVATE_fieldPathFromArgument$1("average",e))}function count(){return new AggregateField("count")}function aggregateFieldEqual(e,t){var r,n;return e instanceof AggregateField&&t instanceof AggregateField&&e.aggregateType===t.aggregateType&&(null===(r=e._internalFieldPath)||void 0===r?void 0:r.canonicalString())===(null===(n=t._internalFieldPath)||void 0===n?void 0:n.canonicalString())}function aggregateQuerySnapshotEqual(e,t){return queryEqual(e.query,t.query)&&deepEqual(e.data(),t.data())}function deleteField(){return new __PRIVATE_DeleteFieldValueImpl("deleteField")}function serverTimestamp(){return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp")}function arrayUnion(...e){return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion",e)}function arrayRemove(...e){return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove",e)}function increment(e){return new __PRIVATE_NumericIncrementFieldValueImpl("increment",e)}function vector(e){return new VectorValue(e)}class WriteBatch{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=__PRIVATE_newUserDataReader(e)}set(e,t,r){this._verifyNotCommitted();const n=__PRIVATE_validateReference(e,this._firestore),i=__PRIVATE_applyFirestoreDataConverter(n.converter,t,r),s=__PRIVATE_parseSetData(this._dataReader,"WriteBatch.set",n._key,i,null!==n.converter,r);return this._mutations.push(s.toMutation(n._key,Precondition.none())),this}update(e,t,r,...n){this._verifyNotCommitted();const i=__PRIVATE_validateReference(e,this._firestore);let s;return s="string"==typeof(t=getModularInstance(t))||t instanceof FieldPath?__PRIVATE_parseUpdateVarargs(this._dataReader,"WriteBatch.update",i._key,t,r,n):__PRIVATE_parseUpdateData(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,Precondition.exists(!0))),this}delete(e){this._verifyNotCommitted();const t=__PRIVATE_validateReference(e,this._firestore);return this._mutations=this._mutations.concat(new __PRIVATE_DeleteMutation(t._key,Precondition.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new FirestoreError(y,"A write batch can no longer be used after commit() has been called.")}}function __PRIVATE_validateReference(e,t){if((e=getModularInstance(e)).firestore!==t)throw new FirestoreError(m,"Provided document reference is from a different Firestore instance.");return e}function writeBatch(e){const t=__PRIVATE_getDatastore(e=__PRIVATE_cast(e,Firestore));return new WriteBatch(e,(e=>__PRIVATE_invokeCommitRpc(t,e)))}class Transaction$1{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),this.mutations.length>0)throw this.lastTransactionError=new FirestoreError(m,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;const t=await __PRIVATE_invokeBatchGetDocumentsRpc(this.datastore,e);return t.forEach((e=>this.recordVersion(e))),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new __PRIVATE_DeleteMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;const e=this.readVersions;this.mutations.forEach((t=>{e.delete(t.key.toString())})),e.forEach(((e,t)=>{const r=DocumentKey.fromPath(t);this.mutations.push(new __PRIVATE_VerifyMutation(r,this.precondition(r)))})),await __PRIVATE_invokeCommitRpc(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw fail();t=SnapshotVersion.min()}const r=this.readVersions.get(e.key.toString());if(r){if(!t.isEqual(r))throw new FirestoreError(I,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){const t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(SnapshotVersion.min())?Precondition.exists(!1):Precondition.updateTime(t):Precondition.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&t){if(t.isEqual(SnapshotVersion.min()))throw new FirestoreError(m,"Can't update a document that doesn't exist.");return Precondition.updateTime(t)}return Precondition.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}const x={maxAttempts:5};class __PRIVATE_TransactionRunner{constructor(e,t,r,n,i){this.asyncQueue=e,this.datastore=t,this.options=r,this.updateFunction=n,this.deferred=i,this.ft=r.maxAttempts,this.Et=new __PRIVATE_ExponentialBackoff(this.asyncQueue,"transaction_retry")}At(){this.ft-=1,this.Tt()}Tt(){this.Et.K((async()=>{const e=new Transaction$1(this.datastore),t=this.Rt(e);t&&t.then((t=>{this.asyncQueue.enqueueAndForget((()=>e.commit().then((()=>{this.deferred.resolve(t)})).catch((e=>{this.Pt(e)}))))})).catch((e=>{this.Pt(e)}))}))}Rt(e){try{const t=this.updateFunction(e);return!__PRIVATE_isNullOrUndefined(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}Pt(e){this.ft>0&&this.Vt(e)?(this.ft-=1,this.asyncQueue.enqueueAndForget((()=>(this.Tt(),Promise.resolve())))):this.deferred.reject(e)}Vt(e){if("FirebaseError"===e.name){const t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!function __PRIVATE_isPermanentError(e){switch(e){default:return fail();case d:case f:case p:case A:case R:case v:case T:return!1;case m:case g:case"already-exists":case E:case y:case I:case V:case P:case"data-loss":return!0}}(t)}return!1}}function getDocument(){return"undefined"!=typeof document?document:null}class DelayedOperation{constructor(e,t,r,n,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=r,this.op=n,this.removalCallback=i,this.deferred=new __PRIVATE_Deferred,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,r,n,i){const s=Date.now()+r,o=new DelayedOperation(e,t,s,n,i);return o.start(r),o}start(e){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new FirestoreError(d,"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)}}class __PRIVATE_AsyncQueueImpl{constructor(e=Promise.resolve()){this.It=[],this.yt=!1,this.wt=[],this.gt=null,this.Ft=!1,this.vt=!1,this.Dt=[],this.Et=new __PRIVATE_ExponentialBackoff(this,"async_queue_retry"),this.bt=()=>{const e=getDocument();e&&__PRIVATE_logDebug("AsyncQueue","Visibility state changed to "+e.visibilityState),this.Et.H()},this.Ct=e;const t=getDocument();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.bt)}get isShuttingDown(){return this.yt}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.St(),this.Nt(e)}enterRestrictedMode(e){if(!this.yt){this.yt=!0,this.vt=e||!1;const t=getDocument();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.bt)}}enqueue(e){if(this.St(),this.yt)return new Promise((()=>{}));const t=new __PRIVATE_Deferred;return this.Nt((()=>this.yt&&this.vt?Promise.resolve():(e().then(t.resolve,t.reject),t.promise))).then((()=>t.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.It.push(e),this.Ot())))}async Ot(){if(0!==this.It.length){try{await this.It[0](),this.It.shift(),this.Et.reset()}catch(e){if(!function __PRIVATE_isIndexedDbTransactionError(e){return"IndexedDbTransactionError"===e.name}(e))throw e;__PRIVATE_logDebug("AsyncQueue","Operation failed with retryable error: "+e)}this.It.length>0&&this.Et.K((()=>this.Ot()))}}Nt(e){const t=this.Ct.then((()=>(this.Ft=!0,e().catch((e=>{this.gt=e,this.Ft=!1;const t=function __PRIVATE_getMessageOrStack(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e);throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ",t),e})).then((e=>(this.Ft=!1,e))))));return this.Ct=t,t}enqueueAfterDelay(e,t,r){this.St(),this.Dt.indexOf(e)>-1&&(t=0);const n=DelayedOperation.createAndSchedule(this,e,t,r,(e=>this.qt(e)));return this.wt.push(n),n}St(){this.gt&&fail()}verifyOperationInProgress(){}async Bt(){let e;do{e=this.Ct,await e}while(e!==this.Ct)}$t(e){for(const t of this.wt)if(t.timerId===e)return!0;return!1}Qt(e){return this.Bt().then((()=>{this.wt.sort(((e,t)=>e.targetTimeMs-t.targetTimeMs));for(const t of this.wt)if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.Bt()}))}Lt(e){this.Dt.push(e)}qt(e){const t=this.wt.indexOf(e);this.wt.splice(t,1)}}class Transaction{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=__PRIVATE_newUserDataReader(e)}get(e){const t=__PRIVATE_validateReference(e,this._firestore),r=new __PRIVATE_LiteUserDataWriter(this._firestore);return this._transaction.lookup([t._key]).then((e=>{if(!e||1!==e.length)return fail();const n=e[0];if(n.isFoundDocument())return new DocumentSnapshot(this._firestore,r,n.key,n,t.converter);if(n.isNoDocument())return new DocumentSnapshot(this._firestore,r,t._key,null,t.converter);throw fail()}))}set(e,t,r){const n=__PRIVATE_validateReference(e,this._firestore),i=__PRIVATE_applyFirestoreDataConverter(n.converter,t,r),s=__PRIVATE_parseSetData(this._dataReader,"Transaction.set",n._key,i,null!==n.converter,r);return this._transaction.set(n._key,s),this}update(e,t,r,...n){const i=__PRIVATE_validateReference(e,this._firestore);let s;return s="string"==typeof(t=getModularInstance(t))||t instanceof FieldPath?__PRIVATE_parseUpdateVarargs(this._dataReader,"Transaction.update",i._key,t,r,n):__PRIVATE_parseUpdateData(this._dataReader,"Transaction.update",i._key,t),this._transaction.update(i._key,s),this}delete(e){const t=__PRIVATE_validateReference(e,this._firestore);return this._transaction.delete(t._key),this}}function runTransaction(e,t,r){const n=__PRIVATE_getDatastore(e=__PRIVATE_cast(e,Firestore)),i=Object.assign(Object.assign({},x),r);!function __PRIVATE_validateTransactionOptions(e){if(e.maxAttempts<1)throw new FirestoreError(m,"Max attempts must be at least 1")}(i);const s=new __PRIVATE_Deferred;return new __PRIVATE_TransactionRunner(function __PRIVATE_newAsyncQueue(){return new __PRIVATE_AsyncQueueImpl}(),n,i,(r=>t(new Transaction(e,r))),s).At(),s.promise}!function __PRIVATE_registerFirestore(){!function __PRIVATE_setSDKVersion(e){_=e}(`${i}_lite`),e(new Component("firestore/lite",((e,{instanceIdentifier:t,options:r})=>{const n=e.getProvider("app").getImmediate(),i=new Firestore(new __PRIVATE_LiteAuthCredentialsProvider(e.getProvider("auth-internal")),new __PRIVATE_LiteAppCheckTokenProvider(e.getProvider("app-check-internal")),function __PRIVATE_databaseIdFromApp(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new FirestoreError(m,'"projectId" not provided in firebase.initializeApp.');return new DatabaseId(e.options.projectId,t)}(n,t),n);return r&&i._setSettings(r),i}),"PUBLIC").setMultipleInstances(!0)),t("firestore-lite","4.7.4",""),t("firestore-lite","4.7.4","esm2017")}();export{AggregateField,AggregateQuerySnapshot,Bytes,CollectionReference,DocumentReference,DocumentSnapshot,FieldPath,FieldValue,Firestore,FirestoreError,GeoPoint,Query,QueryCompositeFilterConstraint,QueryConstraint,QueryDocumentSnapshot,QueryEndAtConstraint,QueryFieldFilterConstraint,QueryLimitConstraint,QueryOrderByConstraint,QuerySnapshot,QueryStartAtConstraint,Timestamp,Transaction,VectorValue,WriteBatch,addDoc,aggregateFieldEqual,aggregateQuerySnapshotEqual,and,arrayRemove,arrayUnion,average,collection,collectionGroup,connectFirestoreEmulator,count,deleteDoc,deleteField,doc,documentId,endAt,endBefore,getAggregate,getCount,getDoc,getDocs,getFirestore,increment,initializeFirestore,limit,limitToLast,or,orderBy,query,queryEqual,refEqual,runTransaction,serverTimestamp,setDoc,setLogLevel,snapshotEqual,startAfter,startAt,sum,terminate,updateDoc,vector,where,writeBatch};
//# sourceMappingURL=firebase-firestore-lite.js.map