"use strict";function _interopDefault(t){return t&&"object"==typeof t&&"default"in t?t.default:t}Object.defineProperty(exports,"__esModule",{value:!0});var LogLevel,firebase=_interopDefault(require("@firebase/app")),tslib=require("tslib"),logger=require("@firebase/logger"),util=require("@firebase/util"),component=require("@firebase/component"),webchannelWrapper=require("@firebase/webchannel-wrapper"),SDK_VERSION=firebase.SDK_VERSION,__PRIVATE_logClient=new logger.Logger("@firebase/firestore");function __PRIVATE_getLogLevel(){return __PRIVATE_logClient.logLevel===logger.LogLevel.DEBUG?LogLevel.DEBUG:__PRIVATE_logClient.logLevel===logger.LogLevel.SILENT?LogLevel.SILENT:LogLevel.ERROR}function setLogLevel(t){switch(t){case LogLevel.DEBUG:__PRIVATE_logClient.logLevel=logger.LogLevel.DEBUG;break;case LogLevel.ERROR:__PRIVATE_logClient.logLevel=logger.LogLevel.ERROR;break;case LogLevel.SILENT:__PRIVATE_logClient.logLevel=logger.LogLevel.SILENT;break;default:__PRIVATE_logClient.error("Firestore ("+SDK_VERSION+"): Invalid value passed to `setLogLevel`")}}function debug(t,e){for(var n=[],r=2;re?1:0}function __PRIVATE_equals(t,e){return null!=t?!(!e||!t.isEqual(e)):t===e}function __PRIVATE_arrayEquals(t,e){if(t.length!==e.length)return!1;for(var n=0;nr)throw new FirestoreError(Code.INVALID_ARGUMENT,"Function "+t+"() requires between "+n+" and "+r+" arguments, but was called with "+__PRIVATE_formatPlural(e.length,"argument")+".")}function __PRIVATE_validateNamedArrayAtLeastNumberOfElements(t,e,n,r){if(!(e instanceof Array)||e.length20&&(t=t.substring(0,20)+"..."),JSON.stringify(t);if("number"==typeof t||"boolean"==typeof t)return""+t;if("object"==typeof t){if(t instanceof Array)return"an array";var e=__PRIVATE_tryGetCustomObjectType(t);return e?"a custom "+e+" object":"an object"}return"function"==typeof t?"a function":fail("Unknown wrong type: "+typeof t)}function __PRIVATE_tryGetCustomObjectType(t){if(t.constructor){var e=/function\s+([^\s(]+)\s*\(/.exec(t.constructor.toString());if(e&&e.length>1)return e[1]}return null}function __PRIVATE_validateDefined(t,e,n){if(void 0===n)throw new FirestoreError(Code.INVALID_ARGUMENT,"Function "+t+"() requires a valid "+__PRIVATE_ordinal(e)+" argument, but it was undefined.")}function __PRIVATE_validateOptionNames(t,e,n){forEach(e,(function(e,r){if(n.indexOf(e)<0)throw new FirestoreError(Code.INVALID_ARGUMENT,"Unknown option '"+e+"' passed to function "+t+"(). Available options: "+n.join(", "))}))}function __PRIVATE_invalidClassError(t,e,n,r){var i=__PRIVATE_valueDescription(r);return new FirestoreError(Code.INVALID_ARGUMENT,"Function "+t+"() requires its "+__PRIVATE_ordinal(n)+" argument to be a "+e+", but it was: "+i)}function __PRIVATE_validatePositiveNumber(t,e,n){if(n<=0)throw new FirestoreError(Code.INVALID_ARGUMENT,'Function "'+t+'()" requires its '+__PRIVATE_ordinal(e)+" argument to be a positive number, but it was: "+n+".")}function __PRIVATE_ordinal(t){switch(t){case 1:return"first";case 2:return"second";case 3:return"third";default:return t+"th"}}function __PRIVATE_formatPlural(t,e){return t+" "+e+(1===t?"":"s")}var GeoPoint=function(){function t(t,e){if(__PRIVATE_validateExactNumberOfArgs("GeoPoint",arguments,2),__PRIVATE_validateArgType("GeoPoint","number",1,t),__PRIVATE_validateArgType("GeoPoint","number",2,e),!isFinite(t)||t<-90||t>90)throw new FirestoreError(Code.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||e>180)throw new FirestoreError(Code.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this.U=t,this.k=e}return Object.defineProperty(t.prototype,"latitude",{get:function(){return this.U},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"longitude",{get:function(){return this.k},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(t){return this.U===t.U&&this.k===t.k},t.prototype.K=function(t){return __PRIVATE_primitiveComparator(this.U,t.U)||__PRIVATE_primitiveComparator(this.k,t.k)},t}(),Timestamp=function(){function t(t,e){if(this.seconds=t,this.nanoseconds=e,e<0)throw new FirestoreError(Code.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(e>=1e9)throw new FirestoreError(Code.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(t<-62135596800)throw new FirestoreError(Code.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t);if(t>=253402300800)throw new FirestoreError(Code.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t)}return t.now=function(){return t.fromMillis(Date.now())},t.fromDate=function(e){return t.fromMillis(e.getTime())},t.fromMillis=function(e){var n=Math.floor(e/1e3);return new t(n,1e6*(e-1e3*n))},t.prototype.toDate=function(){return new Date(this.toMillis())},t.prototype.toMillis=function(){return 1e3*this.seconds+this.nanoseconds/1e6},t.prototype.K=function(t){return this.seconds===t.seconds?__PRIVATE_primitiveComparator(this.nanoseconds,t.nanoseconds):__PRIVATE_primitiveComparator(this.seconds,t.seconds)},t.prototype.isEqual=function(t){return t.seconds===this.seconds&&t.nanoseconds===this.nanoseconds},t.prototype.toString=function(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"},t}(),__PRIVATE_SnapshotVersion=function(){function t(t){this.timestamp=t}return t.j=function(e){var n=Math.floor(e/1e6);return new t(new Timestamp(n,e%1e6*1e3))},t.q=function(e){return new t(e)},t.W=function(){return t.MIN},t.prototype._=function(t){return this.timestamp.K(t.timestamp)},t.prototype.isEqual=function(t){return this.timestamp.isEqual(t.timestamp)},t.prototype.$=function(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3},t.prototype.toString=function(){return"SnapshotVersion("+this.timestamp.toString()+")"},t.prototype.Y=function(){return this.timestamp},t.MIN=new t(new Timestamp(0,0)),t}(),__PRIVATE_DOCUMENT_KEY_NAME="__name__",__PRIVATE_BasePath=function(){function t(t,e,n){void 0===e?e=0:e>t.length&&fail("offset "+e+" out of range "+t.length),void 0===n?n=t.length-e:n>t.length-e&&fail("length "+n+" out of range "+(t.length-e)),this.segments=t,this.offset=e,this.H=n}return Object.defineProperty(t.prototype,"length",{get:function(){return this.H},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(e){return 0===t.X(this,e)},t.prototype.child=function(e){var n=this.segments.slice(this.offset,this.limit());return e instanceof t?e.forEach((function(t){n.push(t)})):n.push(e),this.J(n)},t.prototype.limit=function(){return this.offset+this.length},t.prototype.Z=function(t){return t=void 0===t?1:t,assert(this.length>=t,"Can't call popFirst() with less segments"),this.J(this.segments,this.offset+t,this.length-t)},t.prototype.tt=function(){return assert(!this.et(),"Can't call popLast() on empty path"),this.J(this.segments,this.offset,this.length-1)},t.prototype.nt=function(){return assert(!this.et(),"Can't call firstSegment() on empty path"),this.segments[this.offset]},t.prototype.rt=function(){return this.get(this.length-1)},t.prototype.get=function(t){return assert(ts)return 1}return t.lengthe.length?1:0},t}(),ResourcePath=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tslib.__extends(e,t),e.prototype.J=function(t,n,r){return new e(t,n,r)},e.prototype.ut=function(){return this.ot().join("/")},e.prototype.toString=function(){return this.ut()},e.at=function(t){if(t.indexOf("//")>=0)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid path ("+t+"). Paths must not contain // in them.");return new e(t.split("/").filter((function(t){return t.length>0})))},e._t=new e([]),e}(__PRIVATE_BasePath),__PRIVATE_identifierRegExp=/^[_a-zA-Z][_a-zA-Z0-9]*$/,FieldPath=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tslib.__extends(e,t),e.prototype.J=function(t,n,r){return new e(t,n,r)},e.ct=function(t){return __PRIVATE_identifierRegExp.test(t)},e.prototype.ut=function(){return this.ot().map((function(t){return t=t.replace("\\","\\\\").replace("`","\\`"),e.ct(t)||(t="`"+t+"`"),t})).join(".")},e.prototype.toString=function(){return this.ut()},e.prototype.ht=function(){return 1===this.length&&this.get(0)===__PRIVATE_DOCUMENT_KEY_NAME},e.ft=function(){return new e([__PRIVATE_DOCUMENT_KEY_NAME])},e.lt=function(t){for(var n=[],r="",i=0,s=function(){if(0===r.length)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'");n.push(r),r=""},o=!1;i=2&&this.path.get(this.path.length-2)===t},t.prototype.isEqual=function(t){return null!==t&&0===ResourcePath.X(this.path,t.path)},t.prototype.toString=function(){return this.path.toString()},t.X=function(t,e){return ResourcePath.X(t.path,e.path)},t.dt=function(t){return t.length%2==0},t.Et=function(e){return new t(new ResourcePath(e.slice()))},t.Pt=function(e){return new t(ResourcePath.at(e))},t.EMPTY=new t(new ResourcePath([])),t}(),__PRIVATE_SortedMap=function(){function t(t,e){this.X=t,this.root=e||__PRIVATE_LLRBNode.EMPTY}return t.prototype.At=function(e,n){return new t(this.X,this.root.At(e,n,this.X).Rt(null,null,__PRIVATE_LLRBNode.It,null,null))},t.prototype.remove=function(e){return new t(this.X,this.root.remove(e,this.X).Rt(null,null,__PRIVATE_LLRBNode.It,null,null))},t.prototype.get=function(t){for(var e=this.root;!e.et();){var n=this.X(t,e.key);if(0===n)return e.value;n<0?e=e.left:n>0&&(e=e.right)}return null},t.prototype.indexOf=function(t){for(var e=0,n=this.root;!n.et();){var r=this.X(t,n.key);if(0===r)return e+n.left.size;r<0?n=n.left:(e+=n.left.size+1,n=n.right)}return-1},t.prototype.et=function(){return this.root.et()},Object.defineProperty(t.prototype,"size",{get:function(){return this.root.size},enumerable:!0,configurable:!0}),t.prototype.Vt=function(){return this.root.Vt()},t.prototype.vt=function(){return this.root.vt()},t.prototype.pt=function(t){return this.root.pt(t)},t.prototype.forEach=function(t){this.pt((function(e,n){return t(e,n),!1}))},t.prototype.toString=function(){var t=[];return this.pt((function(e,n){return t.push(e+":"+n),!1})),"{"+t.join(", ")+"}"},t.prototype.bt=function(t){return this.root.bt(t)},t.prototype.gt=function(){return new __PRIVATE_SortedMapIterator(this.root,null,this.X,!1)},t.prototype.wt=function(t){return new __PRIVATE_SortedMapIterator(this.root,t,this.X,!1)},t.prototype.yt=function(){return new __PRIVATE_SortedMapIterator(this.root,null,this.X,!0)},t.prototype.St=function(t){return new __PRIVATE_SortedMapIterator(this.root,t,this.X,!0)},t}(),__PRIVATE_SortedMapIterator=function(){function t(t,e,n,r){this.Dt=r,this.Ct=[];for(var i=1;!t.et();)if(i=e?n(t.key,e):1,r&&(i*=-1),i<0)t=this.Dt?t.left:t.right;else{if(0===i){this.Ct.push(t);break}this.Ct.push(t),t=this.Dt?t.right:t.left}}return t.prototype.Ot=function(){assert(this.Ct.length>0,"getNext() called on iterator when hasNext() is false.");var t=this.Ct.pop(),e={key:t.key,value:t.value};if(this.Dt)for(t=t.left;!t.et();)this.Ct.push(t),t=t.right;else for(t=t.right;!t.et();)this.Ct.push(t),t=t.left;return e},t.prototype.Ft=function(){return this.Ct.length>0},t.prototype.Nt=function(){if(0===this.Ct.length)return null;var t=this.Ct[this.Ct.length-1];return{key:t.key,value:t.value}},t}(),__PRIVATE_LLRBNode=function(){function t(e,n,r,i,s){this.key=e,this.value=n,this.color=null!=r?r:t.RED,this.left=null!=i?i:t.EMPTY,this.right=null!=s?s:t.EMPTY,this.size=this.left.size+1+this.right.size}return t.prototype.Rt=function(e,n,r,i,s){return new t(null!=e?e:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=i?i:this.left,null!=s?s:this.right)},t.prototype.et=function(){return!1},t.prototype.pt=function(t){return this.left.pt(t)||t(this.key,this.value)||this.right.pt(t)},t.prototype.bt=function(t){return this.right.bt(t)||t(this.key,this.value)||this.left.bt(t)},t.prototype.min=function(){return this.left.et()?this:this.left.min()},t.prototype.Vt=function(){return this.min().key},t.prototype.vt=function(){return this.right.et()?this.key:this.right.vt()},t.prototype.At=function(t,e,n){var r=this,i=n(t,r.key);return(r=i<0?r.Rt(null,null,null,r.left.At(t,e,n),null):0===i?r.Rt(null,e,null,null,null):r.Rt(null,null,null,null,r.right.At(t,e,n))).Mt()},t.prototype.Lt=function(){if(this.left.et())return t.EMPTY;var e=this;return e.left.Gt()||e.left.left.Gt()||(e=e.Bt()),(e=e.Rt(null,null,null,e.left.Lt(),null)).Mt()},t.prototype.remove=function(e,n){var r,i=this;if(n(e,i.key)<0)i.left.et()||i.left.Gt()||i.left.left.Gt()||(i=i.Bt()),i=i.Rt(null,null,null,i.left.remove(e,n),null);else{if(i.left.Gt()&&(i=i.Ut()),i.right.et()||i.right.Gt()||i.right.left.Gt()||(i=i.kt()),0===n(e,i.key)){if(i.right.et())return t.EMPTY;r=i.right.min(),i=i.Rt(r.key,r.value,null,null,i.right.Lt())}i=i.Rt(null,null,null,null,i.right.remove(e,n))}return i.Mt()},t.prototype.Gt=function(){return this.color},t.prototype.Mt=function(){var t=this;return t.right.Gt()&&!t.left.Gt()&&(t=t.xt()),t.left.Gt()&&t.left.left.Gt()&&(t=t.Ut()),t.left.Gt()&&t.right.Gt()&&(t=t.Kt()),t},t.prototype.Bt=function(){var t=this.Kt();return t.right.left.Gt()&&(t=(t=(t=t.Rt(null,null,null,null,t.right.Ut())).xt()).Kt()),t},t.prototype.kt=function(){var t=this.Kt();return t.left.left.Gt()&&(t=(t=t.Ut()).Kt()),t},t.prototype.xt=function(){var e=this.Rt(null,null,t.RED,null,this.right.left);return this.right.Rt(null,null,this.color,e,null)},t.prototype.Ut=function(){var e=this.Rt(null,null,t.RED,this.left.right,null);return this.left.Rt(null,null,this.color,null,e)},t.prototype.Kt=function(){var t=this.left.Rt(null,null,!this.left.color,null,null),e=this.right.Rt(null,null,!this.right.color,null,null);return this.Rt(null,null,!this.color,t,e)},t.prototype.jt=function(){var t=this.qt();return Math.pow(2,t)<=this.size+1},t.prototype.qt=function(){if(this.Gt()&&this.left.Gt())throw fail("Red node has red child("+this.key+","+this.value+")");if(this.right.Gt())throw fail("Right child of ("+this.key+","+this.value+") is red");var t=this.left.qt();if(t!==this.right.qt())throw fail("Black depths differ");return t+(this.Gt()?0:1)},t.EMPTY=null,t.RED=!0,t.It=!1,t}(),__PRIVATE_LLRBEmptyNode=function(){function t(){this.size=0}return Object.defineProperty(t.prototype,"key",{get:function(){throw fail("LLRBEmptyNode has no key.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"value",{get:function(){throw fail("LLRBEmptyNode has no value.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"color",{get:function(){throw fail("LLRBEmptyNode has no color.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"left",{get:function(){throw fail("LLRBEmptyNode has no left child.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){throw fail("LLRBEmptyNode has no right child.")},enumerable:!0,configurable:!0}),t.prototype.Rt=function(t,e,n,r,i){return this},t.prototype.At=function(t,e,n){return new __PRIVATE_LLRBNode(t,e)},t.prototype.remove=function(t,e){return this},t.prototype.et=function(){return!0},t.prototype.pt=function(t){return!1},t.prototype.bt=function(t){return!1},t.prototype.Vt=function(){return null},t.prototype.vt=function(){return null},t.prototype.Gt=function(){return!1},t.prototype.jt=function(){return!0},t.prototype.qt=function(){return 0},t}();__PRIVATE_LLRBNode.EMPTY=new __PRIVATE_LLRBEmptyNode;var __PRIVATE_SortedSet=function(){function t(t){this.X=t,this.data=new __PRIVATE_SortedMap(this.X)}return t.Qt=function(e){var n=new t(e.X);return e.forEach((function(t){n=n.add(t)})),n},t.prototype.has=function(t){return null!==this.data.get(t)},t.prototype.first=function(){return this.data.Vt()},t.prototype.last=function(){return this.data.vt()},Object.defineProperty(t.prototype,"size",{get:function(){return this.data.size},enumerable:!0,configurable:!0}),t.prototype.indexOf=function(t){return this.data.indexOf(t)},t.prototype.forEach=function(t){this.data.pt((function(e,n){return t(e),!1}))},t.prototype.Wt=function(t,e){for(var n=this.data.wt(t[0]);n.Ft();){var r=n.Ot();if(this.X(r.key,t[1])>=0)return;e(r.key)}},t.prototype.$t=function(t,e){var n;for(n=void 0!==e?this.data.wt(e):this.data.gt();n.Ft();){if(!t(n.Ot().key))return}},t.prototype.Yt=function(t){var e=this.data.wt(t);return e.Ft()?e.Ot().key:null},t.prototype.gt=function(){return new __PRIVATE_SortedSetIterator(this.data.gt())},t.prototype.wt=function(t){return new __PRIVATE_SortedSetIterator(this.data.wt(t))},t.prototype.add=function(t){return this.Rt(this.data.remove(t).At(t,!0))},t.prototype.delete=function(t){return this.has(t)?this.Rt(this.data.remove(t)):this},t.prototype.et=function(){return this.data.et()},t.prototype.Ht=function(t){var e=this;return t.forEach((function(t){e=e.add(t)})),e},t.prototype.isEqual=function(e){if(!(e instanceof t))return!1;if(this.size!==e.size)return!1;for(var n=this.data.gt(),r=e.data.gt();n.Ft();){var i=n.Ot().key,s=r.Ot().key;if(0!==this.X(i,s))return!1}return!0},t.prototype.ot=function(){var t=[];return this.forEach((function(e){t.push(e)})),t},t.prototype.toString=function(){var t=[];return this.forEach((function(e){return t.push(e)})),"SortedSet("+t.toString()+")"},t.prototype.Rt=function(e){var n=new t(this.X);return n.data=e,n},t}(),__PRIVATE_SortedSetIterator=function(){function t(t){this.Xt=t}return t.prototype.Ot=function(){return this.Xt.Ot().key},t.prototype.Ft=function(){return this.Xt.Ft()},t}(),__PRIVATE_ServerTimestampTransform=function(){function t(){}return t.prototype.zt=function(t,e){return new __PRIVATE_ServerTimestampValue(e,t)},t.prototype.Jt=function(t,e){return e},t.prototype.Zt=function(t){return null},t.prototype.isEqual=function(e){return e instanceof t},t.instance=new t,t}(),__PRIVATE_ArrayUnionTransformOperation=function(){function t(t){this.elements=t}return t.prototype.zt=function(t,e){return this.apply(t)},t.prototype.Jt=function(t,e){return this.apply(t)},t.prototype.apply=function(t){for(var e=__PRIVATE_coercedFieldValuesArray(t),n=function(t){e.find((function(e){return e.isEqual(t)}))||e.push(t)},r=0,i=this.elements;re?1:t===e?0:isNaN(t)?isNaN(e)?0:-1:1}function __PRIVATE_numericEquals(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}var __PRIVATE_IntegerValue=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tslib.__extends(e,t),e.prototype.isEqual=function(t){return t instanceof e&&__PRIVATE_numericEquals(this.ee,t.ee)},e}(__PRIVATE_NumberValue),__PRIVATE_DoubleValue=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tslib.__extends(e,t),e.prototype.isEqual=function(t){return t instanceof e&&__PRIVATE_numericEquals(this.ee,t.ee)},e.je=new e(NaN),e.POSITIVE_INFINITY=new e(1/0),e.NEGATIVE_INFINITY=new e(-1/0),e}(__PRIVATE_NumberValue),__PRIVATE_StringValue=function(t){function e(e){var n=t.call(this)||this;return n.ee=e,n.Be=__PRIVATE_TypeOrder.we,n}return tslib.__extends(e,t),e.prototype.value=function(t){return this.ee},e.prototype.isEqual=function(t){return t instanceof e&&this.ee===t.ee},e.prototype._=function(t){return t instanceof e?__PRIVATE_primitiveComparator(this.ee,t.ee):this.Ge(t)},e.prototype.Ue=function(){return 2*this.ee.length},e}(FieldValue),__PRIVATE_TimestampValue=function(t){function e(e){var n=t.call(this)||this;return n.ee=e,n.Be=__PRIVATE_TypeOrder.ge,n}return tslib.__extends(e,t),e.prototype.value=function(t){return!t||t.timestampsInSnapshots?this.ee:this.ee.toDate()},e.prototype.isEqual=function(t){return t instanceof e&&this.ee.isEqual(t.ee)},e.prototype._=function(t){return t instanceof e?this.ee.K(t.ee):t instanceof __PRIVATE_ServerTimestampValue?-1:this.Ge(t)},e.prototype.Ue=function(){return 16},e}(FieldValue),__PRIVATE_ServerTimestampValue=function(t){function e(e,n){var r=t.call(this)||this;return r.qe=e,r.previousValue=n,r.Be=__PRIVATE_TypeOrder.ge,r}return tslib.__extends(e,t),e.prototype.value=function(t){return t&&t.Me===__PRIVATE_ServerTimestampBehavior.Fe?new __PRIVATE_TimestampValue(this.qe).value(t):t&&t.Me===__PRIVATE_ServerTimestampBehavior.Ne&&this.previousValue?this.previousValue.value(t):null},e.prototype.isEqual=function(t){return t instanceof e&&this.qe.isEqual(t.qe)},e.prototype._=function(t){return t instanceof e?this.qe.K(t.qe):t instanceof __PRIVATE_TimestampValue?1:this.Ge(t)},e.prototype.toString=function(){return""},e.prototype.Ue=function(){return 16+(this.previousValue?this.previousValue.Ue():0)},e}(FieldValue),__PRIVATE_BlobValue=function(t){function e(e){var n=t.call(this)||this;return n.ee=e,n.Be=__PRIVATE_TypeOrder.ye,n}return tslib.__extends(e,t),e.prototype.value=function(t){return this.ee},e.prototype.isEqual=function(t){return t instanceof e&&this.ee.isEqual(t.ee)},e.prototype._=function(t){return t instanceof e?this.ee.K(t.ee):this.Ge(t)},e.prototype.Ue=function(){return this.ee.Qe()},e}(FieldValue),__PRIVATE_RefValue=function(t){function e(e,n){var r=t.call(this)||this;return r.o=e,r.key=n,r.Be=__PRIVATE_TypeOrder.Se,r}return tslib.__extends(e,t),e.prototype.value=function(t){return this.key},e.prototype.isEqual=function(t){return t instanceof e&&(this.key.isEqual(t.key)&&this.o.isEqual(t.o))},e.prototype._=function(t){if(t instanceof e){var n=this.o._(t.o);return 0!==n?n:__PRIVATE_DocumentKey.X(this.key,t.key)}return this.Ge(t)},e.prototype.Ue=function(){return this.o.projectId.length+this.o.database.length+this.key.toString().length},e}(FieldValue),__PRIVATE_GeoPointValue=function(t){function e(e){var n=t.call(this)||this;return n.ee=e,n.Be=__PRIVATE_TypeOrder.De,n}return tslib.__extends(e,t),e.prototype.value=function(t){return this.ee},e.prototype.isEqual=function(t){return t instanceof e&&this.ee.isEqual(t.ee)},e.prototype._=function(t){return t instanceof e?this.ee.K(t.ee):this.Ge(t)},e.prototype.Ue=function(){return 16},e}(FieldValue),__PRIVATE_ObjectValue=function(t){function e(e){var n=t.call(this)||this;return n.ee=e,n.Be=__PRIVATE_TypeOrder.Ce,n}return tslib.__extends(e,t),e.prototype.value=function(t){var e={};return this.ee.pt((function(n,r){e[n]=r.value(t)})),e},e.prototype.forEach=function(t){this.ee.pt(t)},e.prototype.isEqual=function(t){if(t instanceof e){for(var n=this.ee.gt(),r=t.ee.gt();n.Ft()&&r.Ft();){var i=n.Ot(),s=r.Ot();if(i.key!==s.key||!i.value.isEqual(s.value))return!1}return!n.Ft()&&!r.Ft()}return!1},e.prototype._=function(t){if(t instanceof e){for(var n=this.ee.gt(),r=t.ee.gt();n.Ft()&&r.Ft();){var i=n.Ot(),s=r.Ot(),o=__PRIVATE_primitiveComparator(i.key,s.key)||i.value._(s.value);if(o)return o}return __PRIVATE_primitiveComparator(n.Ft(),r.Ft())}return this.Ge(t)},e.prototype.set=function(t,n){if(assert(!t.et(),"Cannot set field for empty path on ObjectValue"),1===t.length)return this.We(t.nt(),n);var r=this.child(t.nt());r instanceof e||(r=e.EMPTY);var i=r.set(t.Z(),n);return this.We(t.nt(),i)},e.prototype.delete=function(t){if(assert(!t.et(),"Cannot delete field for empty path on ObjectValue"),1===t.length)return new e(this.ee.remove(t.nt()));var n=this.child(t.nt());if(n instanceof e){var r=n.delete(t.Z());return new e(this.ee.At(t.nt(),r))}return this},e.prototype.contains=function(t){return null!==this.field(t)},e.prototype.field=function(t){assert(!t.et(),"Can't get field of empty path");var n=this;return t.forEach((function(t){n=n instanceof e?n.ee.get(t):null})),n},e.prototype.Ee=function(){var t=new __PRIVATE_SortedSet(FieldPath.X);return this.ee.forEach((function(n,r){var i=new FieldPath([n]);if(r instanceof e){var s=r.Ee().fields;s.et()?t=t.add(i):s.forEach((function(e){t=t.add(i.child(e))}))}else t=t.add(i)})),__PRIVATE_FieldMask.ne(t)},e.prototype.Ue=function(){var t=0;return this.ee.pt((function(e,n){t+=e.length+n.Ue()})),t},e.prototype.toString=function(){return this.ee.toString()},e.prototype.child=function(t){return this.ee.get(t)||void 0},e.prototype.We=function(t,n){return new e(this.ee.At(t,n))},e.EMPTY=new e(new __PRIVATE_SortedMap(__PRIVATE_primitiveComparator)),e}(FieldValue),ArrayValue=function(t){function e(e){var n=t.call(this)||this;return n.ee=e,n.Be=__PRIVATE_TypeOrder.ArrayValue,n}return tslib.__extends(e,t),e.prototype.value=function(t){return this.ee.map((function(e){return e.value(t)}))},e.prototype.contains=function(t){for(var e=0,n=this.ee;e=MIN_SAFE_INTEGER}var __PRIVATE_LimitType,Target=function(){function t(t,e,n,r,i,s,o){void 0===e&&(e=null),void 0===n&&(n=[]),void 0===r&&(r=[]),void 0===i&&(i=null),void 0===s&&(s=null),void 0===o&&(o=null),this.path=t,this.collectionGroup=e,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=o,this.Je=null}return t.prototype.canonicalId=function(){if(null===this.Je){var t=this.path.ut();null!==this.collectionGroup&&(t+="|cg:"+this.collectionGroup),t+="|f:";for(var e=0,n=this.filters;e0&&(t+=", orderBy: ["+this.orderBy.join(", ")+"]"),this.startAt&&(t+=", startAt: "+this.startAt.canonicalId()),this.endAt&&(t+=", endAt: "+this.endAt.canonicalId()),"Target("+t+")"},t.prototype.isEqual=function(t){if(this.limit!==t.limit)return!1;if(this.orderBy.length!==t.orderBy.length)return!1;for(var e=0;e0?this.nn[this.nn.length-1].dir:__PRIVATE_Direction.ASCENDING;this.in.push(o===__PRIVATE_Direction.ASCENDING?__PRIVATE_KEY_ORDERING_ASC:__PRIVATE_KEY_ORDERING_DESC)}}}return this.in},enumerable:!0,configurable:!0}),t.prototype.cn=function(e){assert(null==this.an()||!(e instanceof FieldFilter)||!e.hn()||e.field.isEqual(this.an()),"Query must only have one inequality field."),assert(!this.Ze(),"No filtering allowed for document query");var n=this.filters.concat([e]);return new t(this.path,this.collectionGroup,this.nn.slice(),n,this.limit,this.rn,this.startAt,this.endAt)},t.prototype.fn=function(e){assert(!this.startAt&&!this.endAt,"Bounds must be set after orderBy");var n=this.nn.concat([e]);return new t(this.path,this.collectionGroup,n,this.filters.slice(),this.limit,this.rn,this.startAt,this.endAt)},t.prototype.ln=function(e){return new t(this.path,this.collectionGroup,this.nn.slice(),this.filters.slice(),e,__PRIVATE_LimitType.tn,this.startAt,this.endAt)},t.prototype.dn=function(e){return new t(this.path,this.collectionGroup,this.nn.slice(),this.filters.slice(),e,__PRIVATE_LimitType.en,this.startAt,this.endAt)},t.prototype.Tn=function(e){return new t(this.path,this.collectionGroup,this.nn.slice(),this.filters.slice(),this.limit,this.rn,e,this.endAt)},t.prototype.En=function(e){return new t(this.path,this.collectionGroup,this.nn.slice(),this.filters.slice(),this.limit,this.rn,this.startAt,e)},t.prototype.Pn=function(e){return new t(e,null,this.nn.slice(),this.filters.slice(),this.limit,this.rn,this.startAt,this.endAt)},t.prototype.An=function(){return 0===this.filters.length&&null===this.limit&&null==this.startAt&&null==this.endAt&&(0===this.nn.length||1===this.nn.length&&this.nn[0].field.ht())},t.prototype.canonicalId=function(){return this.Rn().canonicalId()+"|lt:"+this.rn},t.prototype.toString=function(){return"Query(target="+this.Rn().toString()+"; limitType="+this.rn+")"},t.prototype.isEqual=function(t){return this.Rn().isEqual(t.Rn())&&this.rn===t.rn},t.prototype.In=function(t,e){for(var n=!1,r=0,i=this.orderBy;r0?this.nn[0].field:null},t.prototype.an=function(){for(var t=0,e=this.filters;t=0)return r.op}return null},t.prototype.Ze=function(){return this.Rn().Ze()},t.prototype.yn=function(){return null!==this.collectionGroup},t.prototype.Rn=function(){if(!this.sn)if(this.rn===__PRIVATE_LimitType.tn)this.sn=new Target(this.path,this.collectionGroup,this.orderBy,this.filters,this.limit,this.startAt,this.endAt);else{for(var t=[],e=0,n=this.orderBy;e=":return t.GREATER_THAN_OR_EQUAL;case">":return t.GREATER_THAN;case"array-contains":return t.ARRAY_CONTAINS;case"in":return t.IN;case"array-contains-any":return t.ARRAY_CONTAINS_ANY;default:return fail("Unknown FieldFilter operator: "+e)}},t.prototype.toString=function(){return this.name},t.prototype.isEqual=function(t){return this.name===t.name},t.LESS_THAN=new t("<"),t.LESS_THAN_OR_EQUAL=new t("<="),t.EQUAL=new t("=="),t.GREATER_THAN=new t(">"),t.GREATER_THAN_OR_EQUAL=new t(">="),t.ARRAY_CONTAINS=new t("array-contains"),t.IN=new t("in"),t.ARRAY_CONTAINS_ANY=new t("array-contains-any"),t}(),FieldFilter=function(t){function e(e,n,r){var i=t.call(this)||this;return i.field=e,i.op=n,i.value=r,i}return tslib.__extends(e,t),e.create=function(t,n,r){if(t.ht())return n===__PRIVATE_Operator.IN?(assert(r instanceof ArrayValue,"Comparing on key with IN, but filter value not an ArrayValue"),assert(r.ee.every((function(t){return t instanceof __PRIVATE_RefValue})),"Comparing on key with IN, but an array value was not a RefValue"),new __PRIVATE_KeyFieldInFilter(t,r)):(assert(r instanceof __PRIVATE_RefValue,"Comparing on key, but filter value not a RefValue"),assert(n!==__PRIVATE_Operator.ARRAY_CONTAINS&&n!==__PRIVATE_Operator.ARRAY_CONTAINS_ANY,"'"+n.toString()+"' queries don't make sense on document keys."),new __PRIVATE_KeyFieldFilter(t,n,r));if(r.isEqual(__PRIVATE_NullValue.ke)){if(n!==__PRIVATE_Operator.EQUAL)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid query. Null supports only equality comparisons.");return new e(t,n,r)}if(r.isEqual(__PRIVATE_DoubleValue.je)){if(n!==__PRIVATE_Operator.EQUAL)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid query. NaN supports only equality comparisons.");return new e(t,n,r)}return n===__PRIVATE_Operator.ARRAY_CONTAINS?new __PRIVATE_ArrayContainsFilter(t,r):n===__PRIVATE_Operator.IN?(assert(r instanceof ArrayValue,"IN filter has invalid value: "+r.toString()),new __PRIVATE_InFilter(t,r)):n===__PRIVATE_Operator.ARRAY_CONTAINS_ANY?(assert(r instanceof ArrayValue,"ARRAY_CONTAINS_ANY filter has invalid value: "+r.toString()),new __PRIVATE_ArrayContainsAnyFilter(t,r)):new e(t,n,r)},e.prototype.matches=function(t){var e=t.field(this.field);return null!==e&&this.value.Be===e.Be&&this.Dn(e._(this.value))},e.prototype.Dn=function(t){switch(this.op){case __PRIVATE_Operator.LESS_THAN:return t<0;case __PRIVATE_Operator.LESS_THAN_OR_EQUAL:return t<=0;case __PRIVATE_Operator.EQUAL:return 0===t;case __PRIVATE_Operator.GREATER_THAN:return t>0;case __PRIVATE_Operator.GREATER_THAN_OR_EQUAL:return t>=0;default:return fail("Unknown FieldFilter operator: "+this.op)}},e.prototype.hn=function(){return[__PRIVATE_Operator.LESS_THAN,__PRIVATE_Operator.LESS_THAN_OR_EQUAL,__PRIVATE_Operator.GREATER_THAN,__PRIVATE_Operator.GREATER_THAN_OR_EQUAL].indexOf(this.op)>=0},e.prototype.canonicalId=function(){return this.field.ut()+this.op.toString()+this.value.toString()},e.prototype.isEqual=function(t){return t instanceof e&&(this.op.isEqual(t.op)&&this.field.isEqual(t.field)&&this.value.isEqual(t.value))},e.prototype.toString=function(){return this.field.ut()+" "+this.op+" "+this.value.value()},e}(Filter),__PRIVATE_KeyFieldFilter=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tslib.__extends(e,t),e.prototype.matches=function(t){var e=this.value,n=__PRIVATE_DocumentKey.X(t.key,e.key);return this.Dn(n)},e}(FieldFilter),__PRIVATE_KeyFieldInFilter=function(t){function e(e,n){var r=t.call(this,e,__PRIVATE_Operator.IN,n)||this;return r.value=n,r}return tslib.__extends(e,t),e.prototype.matches=function(t){return this.value.ee.some((function(e){return t.key.isEqual(e.key)}))},e}(FieldFilter),__PRIVATE_ArrayContainsFilter=function(t){function e(e,n){return t.call(this,e,__PRIVATE_Operator.ARRAY_CONTAINS,n)||this}return tslib.__extends(e,t),e.prototype.matches=function(t){var e=t.field(this.field);return e instanceof ArrayValue&&e.contains(this.value)},e}(FieldFilter),__PRIVATE_InFilter=function(t){function e(e,n){var r=t.call(this,e,__PRIVATE_Operator.IN,n)||this;return r.value=n,r}return tslib.__extends(e,t),e.prototype.matches=function(t){var e=this.value,n=t.field(this.field);return null!==n&&e.contains(n)},e}(FieldFilter),__PRIVATE_ArrayContainsAnyFilter=function(t){function e(e,n){var r=t.call(this,e,__PRIVATE_Operator.ARRAY_CONTAINS_ANY,n)||this;return r.value=n,r}return tslib.__extends(e,t),e.prototype.matches=function(t){var e=this,n=t.field(this.field);return n instanceof ArrayValue&&n.ee.some((function(t){return e.value.contains(t)}))},e}(FieldFilter),__PRIVATE_Direction=function(){function t(t){this.name=t}return t.prototype.toString=function(){return this.name},t.ASCENDING=new t("asc"),t.DESCENDING=new t("desc"),t}(),__PRIVATE_Bound=function(){function t(t,e){this.position=t,this.before=e}return t.prototype.canonicalId=function(){for(var t=this.before?"b:":"a:",e=0,n=this.position;e=0?e:Code.UNKNOWN}!function(t){t[t.OK=0]="OK",t[t.CANCELLED=1]="CANCELLED",t[t.UNKNOWN=2]="UNKNOWN",t[t.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",t[t.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",t[t.NOT_FOUND=5]="NOT_FOUND",t[t.ALREADY_EXISTS=6]="ALREADY_EXISTS",t[t.PERMISSION_DENIED=7]="PERMISSION_DENIED",t[t.UNAUTHENTICATED=16]="UNAUTHENTICATED",t[t.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",t[t.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",t[t.ABORTED=10]="ABORTED",t[t.OUT_OF_RANGE=11]="OUT_OF_RANGE",t[t.UNIMPLEMENTED=12]="UNIMPLEMENTED",t[t.INTERNAL=13]="INTERNAL",t[t.UNAVAILABLE=14]="UNAVAILABLE",t[t.DATA_LOSS=15]="DATA_LOSS"}(__PRIVATE_RpcCode||(__PRIVATE_RpcCode={}));var __PRIVATE_EMPTY_MAYBE_DOCUMENT_MAP=new __PRIVATE_SortedMap(__PRIVATE_DocumentKey.X);function __PRIVATE_maybeDocumentMap(){return __PRIVATE_EMPTY_MAYBE_DOCUMENT_MAP}function __PRIVATE_nullableMaybeDocumentMap(){return __PRIVATE_maybeDocumentMap()}var __PRIVATE_EMPTY_DOCUMENT_MAP=new __PRIVATE_SortedMap(__PRIVATE_DocumentKey.X);function __PRIVATE_documentMap(){return __PRIVATE_EMPTY_DOCUMENT_MAP}var __PRIVATE_EMPTY_DOCUMENT_VERSION_MAP=new __PRIVATE_SortedMap(__PRIVATE_DocumentKey.X);function __PRIVATE_documentVersionMap(){return __PRIVATE_EMPTY_DOCUMENT_VERSION_MAP}var __PRIVATE_EMPTY_DOCUMENT_KEY_SET=new __PRIVATE_SortedSet(__PRIVATE_DocumentKey.X);function __PRIVATE_documentKeySet(){for(var t=[],e=0;e0&&(this.vr=!0,this.Vr=t)},t.prototype.wr=function(){var t=__PRIVATE_documentKeySet(),e=__PRIVATE_documentKeySet(),n=__PRIVATE_documentKeySet();return this.Ir.forEach((function(r,i){switch(i){case __PRIVATE_ChangeType.jn:t=t.add(r);break;case __PRIVATE_ChangeType.Qn:e=e.add(r);break;case __PRIVATE_ChangeType.qn:n=n.add(r);break;default:fail("Encountered invalid change type: "+i)}})),new TargetChange(this.Vr,this.mr,t,e,n)},t.prototype.yr=function(){this.vr=!1,this.Ir=__PRIVATE_snapshotChangesMap()},t.prototype.Sr=function(t,e){this.vr=!0,this.Ir=this.Ir.At(t,e)},t.prototype.Dr=function(t){this.vr=!0,this.Ir=this.Ir.remove(t)},t.prototype.Cr=function(){this.Rr+=1},t.prototype.Or=function(){this.Rr-=1},t.prototype.Fr=function(){this.vr=!0,this.mr=!0},t}(),__PRIVATE_LOG_TAG="WatchChangeAggregator",__PRIVATE_WatchChangeAggregator=function(){function t(t){this.Nr=t,this.Mr={},this.Lr=__PRIVATE_maybeDocumentMap(),this.Gr=__PRIVATE_documentTargetMap(),this.Br=new __PRIVATE_SortedSet(__PRIVATE_primitiveComparator)}return t.prototype.Ur=function(t){for(var e=0,n=t.lr;e0?t.targetIds.forEach(e):__PRIVATE_forEachNumber(this.Mr,e)},t.prototype.$r=function(t){var e=t.targetId,n=t.Tr.count,r=this.Yr(e);if(r){var i=r.target;if(i.Ze())if(0===n){var s=new __PRIVATE_DocumentKey(i.path);this.xr(e,s,new __PRIVATE_NoDocument(s,__PRIVATE_SnapshotVersion.W()))}else assert(1===n,"Single document existence filter with count: "+n);else this.Hr(e)!==n&&(this.Wr(e),this.Br=this.Br.add(e))}},t.prototype.Xr=function(t){var e=this,n={};__PRIVATE_forEachNumber(this.Mr,(function(r,i){var s=e.Yr(r);if(s){if(i.ar&&s.target.Ze()){var o=new __PRIVATE_DocumentKey(s.target.path);null!==e.Lr.get(o)||e.zr(r,o)||e.xr(r,o,new __PRIVATE_NoDocument(o,t))}i.br&&(n[r]=i.wr(),i.yr())}}));var r=__PRIVATE_documentKeySet();this.Gr.forEach((function(t,n){var i=!0;n.$t((function(t){var n=e.Yr(t);return!n||n.Mn===__PRIVATE_TargetPurpose.Nn||(i=!1,!1)})),i&&(r=r.add(t))}));var i=new __PRIVATE_RemoteEvent(t,n,this.Br,this.Lr,r);return this.Lr=__PRIVATE_maybeDocumentMap(),this.Gr=__PRIVATE_documentTargetMap(),this.Br=new __PRIVATE_SortedSet(__PRIVATE_primitiveComparator),i},t.prototype.kr=function(t,e){if(this.Qr(t)){var n=this.zr(t,e.key)?__PRIVATE_ChangeType.Qn:__PRIVATE_ChangeType.jn;this.qr(t).Sr(e.key,n),this.Lr=this.Lr.At(e.key,e),this.Gr=this.Gr.At(e.key,this.Jr(e.key).add(t))}},t.prototype.xr=function(t,e,n){if(this.Qr(t)){var r=this.qr(t);this.zr(t,e)?r.Sr(e,__PRIVATE_ChangeType.qn):r.Dr(e),this.Gr=this.Gr.At(e,this.Jr(e).delete(t)),n&&(this.Lr=this.Lr.At(e,n))}},t.prototype.removeTarget=function(t){delete this.Mr[t]},t.prototype.Hr=function(t){var e=this.qr(t).wr();return this.Nr.Zr(t).size+e._r.size-e.hr.size},t.prototype.Cr=function(t){this.qr(t).Cr()},t.prototype.qr=function(t){return this.Mr[t]||(this.Mr[t]=new __PRIVATE_TargetState),this.Mr[t]},t.prototype.Jr=function(t){var e=this.Gr.get(t);return e||(e=new __PRIVATE_SortedSet(__PRIVATE_primitiveComparator),this.Gr=this.Gr.At(t,e)),e},t.prototype.Qr=function(t){var e=null!==this.Yr(t);return e||debug(__PRIVATE_LOG_TAG,"Detected inactive target",t),e},t.prototype.Yr=function(t){var e=this.Mr[t];return e&&e.pr?null:this.Nr.ti(t)},t.prototype.Wr=function(t){var e=this;assert(!this.Mr[t].pr,"Should only reset active targets"),this.Mr[t]=new __PRIVATE_TargetState,this.Nr.Zr(t).forEach((function(n){e.xr(t,n,null)}))},t.prototype.zr=function(t,e){return this.Nr.Zr(t).has(e)},t}();function __PRIVATE_documentTargetMap(){return new __PRIVATE_SortedMap(__PRIVATE_DocumentKey.X)}function __PRIVATE_snapshotChangesMap(){return new __PRIVATE_SortedMap(__PRIVATE_DocumentKey.X)}var __PRIVATE_DIRECTIONS=function(){var t={};return t[__PRIVATE_Direction.ASCENDING.name]="ASCENDING",t[__PRIVATE_Direction.DESCENDING.name]="DESCENDING",t}(),__PRIVATE_OPERATORS=function(){var t={};return t[__PRIVATE_Operator.LESS_THAN.name]="LESS_THAN",t[__PRIVATE_Operator.LESS_THAN_OR_EQUAL.name]="LESS_THAN_OR_EQUAL",t[__PRIVATE_Operator.GREATER_THAN.name]="GREATER_THAN",t[__PRIVATE_Operator.GREATER_THAN_OR_EQUAL.name]="GREATER_THAN_OR_EQUAL",t[__PRIVATE_Operator.EQUAL.name]="EQUAL",t[__PRIVATE_Operator.ARRAY_CONTAINS.name]="ARRAY_CONTAINS",t[__PRIVATE_Operator.IN.name]="IN",t[__PRIVATE_Operator.ARRAY_CONTAINS_ANY.name]="ARRAY_CONTAINS_ANY",t}(),__PRIVATE_ISO_REG_EXP=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function __PRIVATE_assertPresent(t,e){assert(!__PRIVATE_isNullOrUndefined(t),e+" is missing")}function __PRIVATE_parseInt64(t){return"number"==typeof t?t:"string"==typeof t?Number(t):fail("can't parse "+t)}var __PRIVATE_JsonProtoSerializer=function(){function t(t,e){this.o=t,this.options=e}return t.prototype.ei=function(){return this.options.ni?"":new Uint8Array(0)},t.prototype.ri=function(t){return t},t.prototype.ii=function(t){var e=void 0===t.code?Code.UNKNOWN:__PRIVATE_mapCodeFromRpcCode(t.code);return new FirestoreError(e,t.message||"")},t.prototype.si=function(t){return this.options.ni||__PRIVATE_isNullOrUndefined(t)?t:{value:t}},t.prototype.oi=function(t){var e;return __PRIVATE_isNullOrUndefined(e="object"==typeof t?t.value:t)?null:e},t.prototype.Y=function(t){return this.options.ni?new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")+"."+("000000000"+t.nanoseconds).slice(-9)+"Z":{seconds:""+t.seconds,nanos:t.nanoseconds}},t.prototype.q=function(t){if("string"==typeof t)return this.ui(t);assert(!!t,"Cannot deserialize null or undefined timestamp.");var e=__PRIVATE_parseInt64(t.seconds||"0"),n=t.nanos||0;return new Timestamp(e,n)},t.prototype.ui=function(t){var e=0,n=__PRIVATE_ISO_REG_EXP.exec(t);if(assert(!!n,"invalid timestamp: "+t),n[1]){var r=n[1];r=(r+"000000000").substr(0,9),e=Number(r)}var i=new Date(t),s=Math.floor(i.getTime()/1e3);return new Timestamp(s,e)},t.prototype.ai=function(t){return this.options.ni?t.toBase64():this.ri(t.toUint8Array())},t.prototype._i=function(t){return"string"==typeof t?(assert(this.options.ni,"Expected bytes to be passed in as Uint8Array, but got a string instead."),Blob.fromBase64String(t)):(assert(!this.options.ni,"Expected bytes to be passed in as Uint8Array, but got a string instead."),Blob.fromUint8Array(t))},t.prototype.toVersion=function(t){return this.Y(t.Y())},t.prototype.fromVersion=function(t){return assert(!!t,"Trying to deserialize version that isn't set"),__PRIVATE_SnapshotVersion.q(this.q(t))},t.prototype.ci=function(t,e){return this.hi(t).child("documents").child(e).ut()},t.prototype.fi=function(t){var e=ResourcePath.at(t);return assert(this.li(e),"Tried to deserialize invalid key "+e.toString()),e},t.prototype.di=function(t){return this.ci(this.o,t.path)},t.prototype.Ti=function(t){var e=this.fi(t);return assert(e.get(1)===this.o.projectId,"Tried to deserialize key from different project: "+e.get(1)+" vs "+this.o.projectId),assert(!e.get(3)&&!this.o.database||e.get(3)===this.o.database,"Tried to deserialize key from different database: "+e.get(3)+" vs "+this.o.database),new __PRIVATE_DocumentKey(this.Ei(e))},t.prototype.Pi=function(t){return this.ci(this.o,t)},t.prototype.Ai=function(t){var e=this.fi(t);return 4===e.length?ResourcePath._t:this.Ei(e)},Object.defineProperty(t.prototype,"Ri",{get:function(){return new ResourcePath(["projects",this.o.projectId,"databases",this.o.database]).ut()},enumerable:!0,configurable:!0}),t.prototype.hi=function(t){return new ResourcePath(["projects",t.projectId,"databases",t.database])},t.prototype.Ei=function(t){return assert(t.length>4&&"documents"===t.get(4),"tried to deserialize invalid key "+t.toString()),t.Z(5)},t.prototype.li=function(t){return t.length>=4&&"projects"===t.get(0)&&"databases"===t.get(2)},t.prototype.Ii=function(t){if(t instanceof __PRIVATE_NullValue)return{nullValue:"NULL_VALUE"};if(t instanceof __PRIVATE_BooleanValue)return{booleanValue:t.value()};if(t instanceof __PRIVATE_IntegerValue)return{integerValue:""+t.value()};if(t instanceof __PRIVATE_DoubleValue){var e=t.value();if(this.options.ni){if(isNaN(e))return{doubleValue:"NaN"};if(e===1/0)return{doubleValue:"Infinity"};if(e===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:t.value()}}return t instanceof __PRIVATE_StringValue?{stringValue:t.value()}:t instanceof __PRIVATE_ObjectValue?{mapValue:this.Vi(t)}:t instanceof ArrayValue?{arrayValue:this.mi(t)}:t instanceof __PRIVATE_TimestampValue?{timestampValue:this.Y(t.ee)}:t instanceof __PRIVATE_GeoPointValue?{geoPointValue:{latitude:t.value().latitude,longitude:t.value().longitude}}:t instanceof __PRIVATE_BlobValue?{bytesValue:this.ai(t.value())}:t instanceof __PRIVATE_RefValue?{referenceValue:this.ci(t.o,t.key.path)}:fail("Unknown FieldValue "+JSON.stringify(t))},t.prototype.vi=function(t){var e=this;if("nullValue"in t)return __PRIVATE_NullValue.ke;if("booleanValue"in t)return __PRIVATE_BooleanValue.of(t.booleanValue);if("integerValue"in t)return new __PRIVATE_IntegerValue(__PRIVATE_parseInt64(t.integerValue));if("doubleValue"in t){if(this.options.ni){if("NaN"===t.doubleValue)return __PRIVATE_DoubleValue.je;if("Infinity"===t.doubleValue)return __PRIVATE_DoubleValue.POSITIVE_INFINITY;if("-Infinity"===t.doubleValue)return __PRIVATE_DoubleValue.NEGATIVE_INFINITY}return new __PRIVATE_DoubleValue(t.doubleValue)}if("stringValue"in t)return new __PRIVATE_StringValue(t.stringValue);if("mapValue"in t)return this.pi(t.mapValue.fields||{});if("arrayValue"in t){__PRIVATE_assertPresent(t.arrayValue,"arrayValue");var n=t.arrayValue.values||[];return new ArrayValue(n.map((function(t){return e.vi(t)})))}if("timestampValue"in t)return __PRIVATE_assertPresent(t.timestampValue,"timestampValue"),new __PRIVATE_TimestampValue(this.q(t.timestampValue));if("geoPointValue"in t){__PRIVATE_assertPresent(t.geoPointValue,"geoPointValue");var r=t.geoPointValue.latitude||0,i=t.geoPointValue.longitude||0;return new __PRIVATE_GeoPointValue(new GeoPoint(r,i))}if("bytesValue"in t){__PRIVATE_assertPresent(t.bytesValue,"bytesValue");var s=this._i(t.bytesValue);return new __PRIVATE_BlobValue(s)}if("referenceValue"in t){__PRIVATE_assertPresent(t.referenceValue,"referenceValue");var o=this.fi(t.referenceValue),u=new __PRIVATE_DatabaseId(o.get(1),o.get(3)),a=new __PRIVATE_DocumentKey(this.Ei(o));return new __PRIVATE_RefValue(u,a)}return fail("Unknown Value proto "+JSON.stringify(t))},t.prototype.bi=function(t,e){return{name:this.di(t),fields:this.gi(e)}},t.prototype.wi=function(t){return assert(!t.de,"Can't serialize documents with mutations."),{name:this.di(t.key),fields:this.gi(t.data()),updateTime:this.Y(t.version.Y())}},t.prototype.yi=function(t,e){var n=this,r=this.Ti(t.name),i=this.fromVersion(t.updateTime);return new Document(r,i,{hasCommittedMutations:!!e},void 0,t,(function(t){return n.vi(t)}))},t.prototype.gi=function(t){var e=this,n={};return t.forEach((function(t,r){n[t]=e.Ii(r)})),n},t.prototype.pi=function(t){var e=this,n=t,r=__PRIVATE_ObjectValue.EMPTY;return forEach(n,(function(t,n){r=r.set(new FieldPath([t]),e.vi(n))})),r},t.prototype.Vi=function(t){return{fields:this.gi(t)}},t.prototype.mi=function(t){var e=this,n=[];return t.forEach((function(t){n.push(e.Ii(t))})),{values:n}},t.prototype.Si=function(t){var e=this;assert(!!t.found,"Tried to deserialize a found document from a missing document."),__PRIVATE_assertPresent(t.found.name,"doc.found.name"),__PRIVATE_assertPresent(t.found.updateTime,"doc.found.updateTime");var n=this.Ti(t.found.name),r=this.fromVersion(t.found.updateTime);return new Document(n,r,{},void 0,t.found,(function(t){return e.vi(t)}))},t.prototype.Di=function(t){assert(!!t.missing,"Tried to deserialize a missing document from a found document."),assert(!!t.readTime,"Tried to deserialize a missing document without a read time.");var e=this.Ti(t.missing),n=this.fromVersion(t.readTime);return new __PRIVATE_NoDocument(e,n)},t.prototype.Ci=function(t){return"found"in t?this.Si(t):"missing"in t?this.Di(t):fail("invalid batch get response: "+JSON.stringify(t))},t.prototype.Oi=function(t){switch(t){case __PRIVATE_WatchTargetChangeState.jn:return"ADD";case __PRIVATE_WatchTargetChangeState.Pr:return"CURRENT";case __PRIVATE_WatchTargetChangeState.Er:return"NO_CHANGE";case __PRIVATE_WatchTargetChangeState.qn:return"REMOVE";case __PRIVATE_WatchTargetChangeState.Ar:return"RESET";default:return fail("Unknown WatchTargetChangeState: "+t)}},t.prototype.Fi=function(t){if(t instanceof __PRIVATE_ExistenceFilterChange)return{filter:{count:t.Tr.count,targetId:t.targetId}};if(t instanceof __PRIVATE_DocumentWatchChange){if(t.dr instanceof Document){var e=t.dr;return{documentChange:{document:{name:this.di(e.key),fields:this.gi(e.data()),updateTime:this.toVersion(e.version)},targetIds:t.lr,removedTargetIds:t.removedTargetIds}}}if(t.dr instanceof __PRIVATE_NoDocument){e=t.dr;return{documentDelete:{document:this.di(e.key),readTime:this.toVersion(e.version),removedTargetIds:t.removedTargetIds}}}if(null===t.dr)return{documentRemove:{document:this.di(t.key),removedTargetIds:t.removedTargetIds}}}if(t instanceof __PRIVATE_WatchTargetChange){var n=void 0;return t.cause&&(n={code:__PRIVATE_mapRpcCodeFromCode(t.cause.code),message:t.cause.message}),{targetChange:{targetChangeType:this.Oi(t.state),targetIds:t.targetIds,resumeToken:this.ri(t.resumeToken),cause:n}}}return fail("Unrecognized watch change: "+JSON.stringify(t))},t.prototype.Ni=function(t){var e,n=this;if("targetChange"in t){__PRIVATE_assertPresent(t.targetChange,"targetChange");var r=this.Mi(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],s=t.targetChange.resumeToken||this.ei(),o=t.targetChange.cause,u=o&&this.ii(o);e=new __PRIVATE_WatchTargetChange(r,i,s,u||null)}else if("documentChange"in t){__PRIVATE_assertPresent(t.documentChange,"documentChange");var a=t.documentChange;__PRIVATE_assertPresent(a.document,"documentChange.name"),__PRIVATE_assertPresent(a.document.name,"documentChange.document.name"),__PRIVATE_assertPresent(a.document.updateTime,"documentChange.document.updateTime");var _=this.Ti(a.document.name),c=this.fromVersion(a.document.updateTime),h=new Document(_,c,{},void 0,a.document,(function(t){return n.vi(t)})),f=a.targetIds||[],l=a.removedTargetIds||[];e=new __PRIVATE_DocumentWatchChange(f,l,h.key,h)}else if("documentDelete"in t){__PRIVATE_assertPresent(t.documentDelete,"documentDelete");var d=t.documentDelete;__PRIVATE_assertPresent(d.document,"documentDelete.document");_=this.Ti(d.document),c=d.readTime?this.fromVersion(d.readTime):__PRIVATE_SnapshotVersion.W(),h=new __PRIVATE_NoDocument(_,c),l=d.removedTargetIds||[];e=new __PRIVATE_DocumentWatchChange([],l,h.key,h)}else if("documentRemove"in t){__PRIVATE_assertPresent(t.documentRemove,"documentRemove");var T=t.documentRemove;__PRIVATE_assertPresent(T.document,"documentRemove");_=this.Ti(T.document),l=T.removedTargetIds||[];e=new __PRIVATE_DocumentWatchChange([],l,_,null)}else{if(!("filter"in t))return fail("Unknown change type "+JSON.stringify(t));__PRIVATE_assertPresent(t.filter,"filter");var E=t.filter;__PRIVATE_assertPresent(E.targetId,"filter.targetId");var P=E.count||0,A=new ExistenceFilter(P),R=E.targetId;e=new __PRIVATE_ExistenceFilterChange(R,A)}return e},t.prototype.Mi=function(t){return"NO_CHANGE"===t?__PRIVATE_WatchTargetChangeState.Er:"ADD"===t?__PRIVATE_WatchTargetChangeState.jn:"REMOVE"===t?__PRIVATE_WatchTargetChangeState.qn:"CURRENT"===t?__PRIVATE_WatchTargetChangeState.Pr:"RESET"===t?__PRIVATE_WatchTargetChangeState.Ar:fail("Got unexpected TargetChange.state: "+t)},t.prototype.Li=function(t){if(!("targetChange"in t))return __PRIVATE_SnapshotVersion.MIN;var e=t.targetChange;return e.targetIds&&e.targetIds.length?__PRIVATE_SnapshotVersion.MIN:e.readTime?this.fromVersion(e.readTime):__PRIVATE_SnapshotVersion.MIN},t.prototype.Gi=function(t){var e,n=this;if(t instanceof __PRIVATE_SetMutation)e={update:this.bi(t.key,t.value)};else if(t instanceof __PRIVATE_DeleteMutation)e={delete:this.di(t.key)};else if(t instanceof __PRIVATE_PatchMutation)e={update:this.bi(t.key,t.data),updateMask:this.Bi(t.Ee)};else if(t instanceof __PRIVATE_TransformMutation)e={transform:{document:this.di(t.key),fieldTransforms:t.fieldTransforms.map((function(t){return n.Ui(t)}))}};else{if(!(t instanceof __PRIVATE_VerifyMutation))return fail("Unknown mutation type "+t.type);e={verify:this.di(t.key)}}return t.le._e||(e.currentDocument=this.ki(t.le)),e},t.prototype.xi=function(t){var e=this,n=t.currentDocument?this.Ki(t.currentDocument):Precondition.NONE;if(t.update){__PRIVATE_assertPresent(t.update.name,"name");var r=this.Ti(t.update.name),i=this.pi(t.update.fields||{});if(t.updateMask){var s=this.ji(t.updateMask);return new __PRIVATE_PatchMutation(r,i,s,n)}return new __PRIVATE_SetMutation(r,i,n)}if(t.delete){r=this.Ti(t.delete);return new __PRIVATE_DeleteMutation(r,n)}if(t.transform){r=this.Ti(t.transform.document);var o=t.transform.fieldTransforms.map((function(t){return e.qi(t)}));return assert(!0===n.exists,'Transforms only support precondition "exists == true"'),new __PRIVATE_TransformMutation(r,o)}if(t.verify){r=this.Ti(t.verify);return new __PRIVATE_VerifyMutation(r,n)}return fail("unknown mutation proto: "+JSON.stringify(t))},t.prototype.ki=function(t){return assert(!t._e,"Can't serialize an empty precondition"),void 0!==t.updateTime?{updateTime:this.toVersion(t.updateTime)}:void 0!==t.exists?{exists:t.exists}:fail("Unknown precondition")},t.prototype.Ki=function(t){return void 0!==t.updateTime?Precondition.updateTime(this.fromVersion(t.updateTime)):void 0!==t.exists?Precondition.exists(t.exists):Precondition.NONE},t.prototype.Qi=function(t,e){var n=this,r=t.updateTime?this.fromVersion(t.updateTime):this.fromVersion(e);r.isEqual(__PRIVATE_SnapshotVersion.MIN)&&(r=this.fromVersion(e));var i=null;return t.transformResults&&t.transformResults.length>0&&(i=t.transformResults.map((function(t){return n.vi(t)}))),new __PRIVATE_MutationResult(r,i)},t.prototype.Wi=function(t,e){var n=this;return t&&t.length>0?(assert(void 0!==e,"Received a write result without a commit time"),t.map((function(t){return n.Qi(t,e)}))):[]},t.prototype.Ui=function(t){var e=this,n=t.transform;if(n instanceof __PRIVATE_ServerTimestampTransform)return{fieldPath:t.field.ut(),setToServerValue:"REQUEST_TIME"};if(n instanceof __PRIVATE_ArrayUnionTransformOperation)return{fieldPath:t.field.ut(),appendMissingElements:{values:n.elements.map((function(t){return e.Ii(t)}))}};if(n instanceof __PRIVATE_ArrayRemoveTransformOperation)return{fieldPath:t.field.ut(),removeAllFromArray:{values:n.elements.map((function(t){return e.Ii(t)}))}};if(n instanceof __PRIVATE_NumericIncrementTransformOperation)return{fieldPath:t.field.ut(),increment:this.Ii(n.te)};throw fail("Unknown transform: "+t.transform)},t.prototype.qi=function(t){var e=this,n=null;if("setToServerValue"in t)assert("REQUEST_TIME"===t.setToServerValue,"Unknown server value transform proto: "+JSON.stringify(t)),n=__PRIVATE_ServerTimestampTransform.instance;else if("appendMissingElements"in t){var r=t.appendMissingElements.values||[];n=new __PRIVATE_ArrayUnionTransformOperation(r.map((function(t){return e.vi(t)})))}else if("removeAllFromArray"in t){r=t.removeAllFromArray.values||[];n=new __PRIVATE_ArrayRemoveTransformOperation(r.map((function(t){return e.vi(t)})))}else if("increment"in t){var i=this.vi(t.increment);assert(i instanceof __PRIVATE_NumberValue,"NUMERIC_ADD transform requires a NumberValue"),n=new __PRIVATE_NumericIncrementTransformOperation(i)}else fail("Unknown transform proto: "+JSON.stringify(t));var s=FieldPath.lt(t.fieldPath);return new FieldTransform(s,n)},t.prototype.$i=function(t){return{documents:[this.Pi(t.path)]}},t.prototype.Yi=function(t){var e=t.documents.length;assert(1===e,"DocumentsTarget contained other than 1 document: "+e);var n=t.documents[0];return Query.un(this.Ai(n)).Rn()},t.prototype.Hi=function(t){var e={structuredQuery:{}},n=t.path;null!==t.collectionGroup?(assert(n.length%2==0,"Collection Group queries should be within a document path or root."),e.parent=this.Pi(n),e.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(assert(n.length%2!=0,"Document queries with filters are not supported."),e.parent=this.Pi(n.tt()),e.structuredQuery.from=[{collectionId:n.rt()}]);var r=this.Xi(t.filters);r&&(e.structuredQuery.where=r);var i=this.zi(t.orderBy);i&&(e.structuredQuery.orderBy=i);var s=this.si(t.limit);return null!==s&&(e.structuredQuery.limit=s),t.startAt&&(e.structuredQuery.startAt=this.Ji(t.startAt)),t.endAt&&(e.structuredQuery.endAt=this.Ji(t.endAt)),e},t.prototype.Zi=function(t){var e=this.Ai(t.parent),n=t.structuredQuery,r=n.from?n.from.length:0,i=null;if(r>0){assert(1===r,"StructuredQuery.from with more than one collection is not supported.");var s=n.from[0];s.allDescendants?i=s.collectionId:e=e.child(s.collectionId)}var o=[];n.where&&(o=this.ts(n.where));var u=[];n.orderBy&&(u=this.es(n.orderBy));var a=null;n.limit&&(a=this.oi(n.limit));var _=null;n.startAt&&(_=this.ns(n.startAt));var c=null;return n.endAt&&(c=this.ns(n.endAt)),new Query(e,i,u,o,a,__PRIVATE_LimitType.tn,_,c).Rn()},t.prototype.rs=function(t){var e=this.ss(t.Mn);return null==e?null:{"goog-listen-tags":e}},t.prototype.ss=function(t){switch(t){case __PRIVATE_TargetPurpose.On:return null;case __PRIVATE_TargetPurpose.Fn:return"existence-filter-mismatch";case __PRIVATE_TargetPurpose.Nn:return"limbo-document";default:return fail("Unrecognized query purpose: "+t)}},t.prototype.Rn=function(t){var e,n=t.target;return(e=n.Ze()?{documents:this.$i(n)}:{query:this.Hi(n)}).targetId=t.targetId,t.resumeToken.length>0&&(e.resumeToken=this.ri(t.resumeToken)),e},t.prototype.Xi=function(t){var e=this;if(0!==t.length){var n=t.map((function(t){return t instanceof FieldFilter?e.os(t):fail("Unrecognized filter: "+JSON.stringify(t))}));return 1===n.length?n[0]:{compositeFilter:{op:"AND",filters:n}}}},t.prototype.ts=function(t){var e=this;return t?void 0!==t.unaryFilter?[this.us(t)]:void 0!==t.fieldFilter?[this.as(t)]:void 0!==t.compositeFilter?t.compositeFilter.filters.map((function(t){return e.ts(t)})).reduce((function(t,e){return t.concat(e)})):fail("Unknown filter: "+JSON.stringify(t)):[]},t.prototype.zi=function(t){var e=this;if(0!==t.length)return t.map((function(t){return e._s(t)}))},t.prototype.es=function(t){var e=this;return t.map((function(t){return e.cs(t)}))},t.prototype.Ji=function(t){var e=this;return{before:t.before,values:t.position.map((function(t){return e.Ii(t)}))}},t.prototype.ns=function(t){var e=this,n=!!t.before,r=t.values.map((function(t){return e.vi(t)}));return new __PRIVATE_Bound(r,n)},t.prototype.hs=function(t){return __PRIVATE_DIRECTIONS[t.name]},t.prototype.fs=function(t){switch(t){case"ASCENDING":return __PRIVATE_Direction.ASCENDING;case"DESCENDING":return __PRIVATE_Direction.DESCENDING;default:return}},t.prototype.ls=function(t){return __PRIVATE_OPERATORS[t.name]},t.prototype.ds=function(t){switch(t){case"EQUAL":return __PRIVATE_Operator.EQUAL;case"GREATER_THAN":return __PRIVATE_Operator.GREATER_THAN;case"GREATER_THAN_OR_EQUAL":return __PRIVATE_Operator.GREATER_THAN_OR_EQUAL;case"LESS_THAN":return __PRIVATE_Operator.LESS_THAN;case"LESS_THAN_OR_EQUAL":return __PRIVATE_Operator.LESS_THAN_OR_EQUAL;case"ARRAY_CONTAINS":return __PRIVATE_Operator.ARRAY_CONTAINS;case"IN":return __PRIVATE_Operator.IN;case"ARRAY_CONTAINS_ANY":return __PRIVATE_Operator.ARRAY_CONTAINS_ANY;case"OPERATOR_UNSPECIFIED":return fail("Unspecified operator");default:return fail("Unknown operator")}},t.prototype.Ts=function(t){return{fieldPath:t.ut()}},t.prototype.Es=function(t){return FieldPath.lt(t.fieldPath)},t.prototype._s=function(t){return{field:this.Ts(t.field),direction:this.hs(t.dir)}},t.prototype.cs=function(t){return new __PRIVATE_OrderBy(this.Es(t.field),this.fs(t.direction))},t.prototype.as=function(t){return FieldFilter.create(this.Es(t.fieldFilter.field),this.ds(t.fieldFilter.op),this.vi(t.fieldFilter.value))},t.prototype.os=function(t){if(t.op===__PRIVATE_Operator.EQUAL){if(t.value.isEqual(__PRIVATE_DoubleValue.je))return{unaryFilter:{field:this.Ts(t.field),op:"IS_NAN"}};if(t.value.isEqual(__PRIVATE_NullValue.ke))return{unaryFilter:{field:this.Ts(t.field),op:"IS_NULL"}}}return{fieldFilter:{field:this.Ts(t.field),op:this.ls(t.op),value:this.Ii(t.value)}}},t.prototype.us=function(t){switch(t.unaryFilter.op){case"IS_NAN":var e=this.Es(t.unaryFilter.field);return FieldFilter.create(e,__PRIVATE_Operator.EQUAL,__PRIVATE_DoubleValue.je);case"IS_NULL":var n=this.Es(t.unaryFilter.field);return FieldFilter.create(n,__PRIVATE_Operator.EQUAL,__PRIVATE_NullValue.ke);case"OPERATOR_UNSPECIFIED":return fail("Unspecified filter");default:return fail("Unknown filter")}},t.prototype.Bi=function(t){var e=[];return t.fields.forEach((function(t){return e.push(t.ut())})),{fieldPaths:e}},t.prototype.ji=function(t){var e=(t.fieldPaths||[]).map((function(t){return FieldPath.lt(t)}));return __PRIVATE_FieldMask.re(e)},t}(),__PRIVATE_PlatformSupport=function(){function t(){}return t.Ps=function(e){t.platform&&fail("Platform already defined"),t.platform=e},t.t=function(){return t.platform||fail("Platform not set"),t.platform},t}();function __PRIVATE_emptyByteString(){return __PRIVATE_PlatformSupport.t().ei}function __PRIVATE_makeConstructorPrivate(t,e){function n(){var t="This constructor is private.";throw e&&(t+=" ",t+=e),new FirestoreError(Code.INVALID_ARGUMENT,t)}for(var r in n.prototype=t.prototype,t)t.hasOwnProperty(r)&&(n[r]=t[r]);return n}function __PRIVATE_assertUint8ArrayAvailable(){if("undefined"==typeof Uint8Array)throw new FirestoreError(Code.UNIMPLEMENTED,"Uint8Arrays are not available in this environment.")}function __PRIVATE_assertBase64Available(){if(!__PRIVATE_PlatformSupport.t().As)throw new FirestoreError(Code.UNIMPLEMENTED,"Blobs are unavailable in Firestore in this environment.")}var __PRIVATE_TimerId,Blob=function(){function t(t){__PRIVATE_assertBase64Available(),this.Rs=t}return t.fromBase64String=function(e){__PRIVATE_validateExactNumberOfArgs("Blob.fromBase64String",arguments,1),__PRIVATE_validateArgType("Blob.fromBase64String","string",1,e),__PRIVATE_assertBase64Available();try{var n=__PRIVATE_PlatformSupport.t().atob(e);return new t(n)}catch(t){throw new FirestoreError(Code.INVALID_ARGUMENT,"Failed to construct Blob from Base64 string: "+t)}},t.fromUint8Array=function(e){if(__PRIVATE_validateExactNumberOfArgs("Blob.fromUint8Array",arguments,1),__PRIVATE_assertUint8ArrayAvailable(),!(e instanceof Uint8Array))throw __PRIVATE_invalidClassError("Blob.fromUint8Array","Uint8Array",1,e);var n=Array.prototype.map.call(e,(function(t){return String.fromCharCode(t)})).join("");return new t(n)},t.prototype.toBase64=function(){return __PRIVATE_validateExactNumberOfArgs("Blob.toBase64",arguments,0),__PRIVATE_assertBase64Available(),__PRIVATE_PlatformSupport.t().btoa(this.Rs)},t.prototype.toUint8Array=function(){__PRIVATE_validateExactNumberOfArgs("Blob.toUint8Array",arguments,0),__PRIVATE_assertUint8ArrayAvailable();for(var t=new Uint8Array(this.Rs.length),e=0;e0,"Cannot create an empty mutation batch")}return t.prototype.Jt=function(t,e,n){e&&assert(e.key.isEqual(t),"applyToRemoteDocument: key "+t+" should match maybeDoc key\n "+e.key);var r=n.ms;assert(r.length===this.mutations.length,"Mismatch between mutations length\n ("+this.mutations.length+") and mutation results length\n ("+r.length+").");for(var i=0;i=0,"Attempted to schedule an operation with a negative delay of "+e),this.iu.indexOf(t)>-1&&(e=0);var i=__PRIVATE_DelayedOperation.Yo(this,t,e,n,(function(t){return r.fu(t)}));return this.eu.push(i),i},t.prototype.uu=function(){this.nu&&fail("AsyncQueue is already failed: "+(this.nu.stack||this.nu.message))},t.prototype.lu=function(){assert(this.ru,"verifyOpInProgress() called when no op in progress on this queue.")},t.prototype.du=function(){return this._u((function(){return Promise.resolve()}))},t.prototype.Tu=function(t){for(var e=0,n=this.eu;e=0,"Delayed operation not found."),this.eu.splice(e,1)},t}();function __PRIVATE_bufferEntryComparator(t,e){var n=t[0],r=t[1],i=e[0],s=e[1],o=__PRIVATE_primitiveComparator(n,i);return 0===o?__PRIVATE_primitiveComparator(r,s):o}var __PRIVATE_RollingSequenceNumberBuffer=function(){function t(t){this.Au=t,this.buffer=new __PRIVATE_SortedSet(__PRIVATE_bufferEntryComparator),this.Ru=0}return t.prototype.Iu=function(){return++this.Ru},t.prototype.Vu=function(t){var e=[t,this.Iu()];if(this.buffer.size_.ku.yu?(debug("LruGarbageCollector","Capping sequence numbers to collect down to the maximum of "+_.ku.yu+" from "+e),r=_.ku.yu):r=e,s=Date.now(),_.$u(t,r)})).next((function(r){return n=r,o=Date.now(),_.Hu(t,n,e)})).next((function(e){return i=e,u=Date.now(),_.Xu(t,n)})).next((function(t){(a=Date.now(),__PRIVATE_getLogLevel()<=LogLevel.DEBUG)&&debug("LruGarbageCollector","LRU Garbage Collection\n\tCounted targets in "+(s-c)+"ms\n\tDetermined least recently used "+r+" in "+(o-s)+"ms\n\tRemoved "+i+" targets in "+(u-o)+"ms\n\tRemoved "+t+" documents in "+(a-u)+"ms\nTotal Duration: "+(a-c)+"ms");return PersistencePromise.resolve({mu:!0,vu:r,pu:i,bu:t})}))},t}(),__PRIVATE_LOG_TAG$1="LocalStore",__PRIVATE_LocalStore=function(){function t(t,e,n){this.persistence=t,this.ta=e,this.ea=new __PRIVATE_ReferenceSet,this.na=new __PRIVATE_SortedMap(__PRIVATE_primitiveComparator),this.ra=new __PRIVATE_ObjectMap((function(t){return t.canonicalId()})),this.ia=__PRIVATE_SnapshotVersion.MIN,assert(t.Ku,"LocalStore was passed an unstarted persistence implementation"),this.persistence.oa.sa(this.ea),this._o=t.ua(n),this.aa=t._a(),this.ca=t.ha(),this.fa=new __PRIVATE_LocalDocumentsView(this.aa,this._o,this.persistence.la()),this.ta.da(this.fa)}return t.prototype.start=function(){return this.Ta()},t.prototype.Ea=function(t){return tslib.__awaiter(this,void 0,void 0,(function(){var e,n,r,i=this;return tslib.__generator(this,(function(s){switch(s.label){case 0:return e=this._o,n=this.fa,[4,this.persistence.runTransaction("Handle user change","readonly-idempotent",(function(r){var s;return i._o.Pa(r).next((function(o){return s=o,e=i.persistence.ua(t),n=new __PRIVATE_LocalDocumentsView(i.aa,e,i.persistence.la()),e.Pa(r)})).next((function(t){for(var e=[],i=[],o=__PRIVATE_documentKeySet(),u=0,a=s;u0){var c=a.Bn(_,r).Gn(s.ka);i=i.At(e,c),t.xa(a,c,o)&&u.push(n.ca.Ka(s,c))}}}));var a=__PRIVATE_maybeDocumentMap(),_=__PRIVATE_documentKeySet();if(e.ir.forEach((function(t,e){_=_.add(t)})),u.push(o.getEntries(s,_).next((function(t){e.ir.forEach((function(i,_){var c=t.get(i);_ instanceof __PRIVATE_NoDocument&&_.version.isEqual(__PRIVATE_SnapshotVersion.MIN)?(o.to(i,r),a=a.At(i,_)):null==c||_.version._(c.version)>0||0===_.version._(c.version)&&c.hasPendingWrites?(assert(!__PRIVATE_SnapshotVersion.MIN.isEqual(r),"Cannot add a document when the remote version is zero"),o.Js(_,r),a=a.At(i,_)):debug(__PRIVATE_LOG_TAG$1,"Ignoring outdated watch update for ",i,". Current version:",c.version," Watch version:",_.version),e.sr.has(i)&&u.push(n.persistence.oa.ja(s,i))}))}))),!r.isEqual(__PRIVATE_SnapshotVersion.MIN)){var c=n.ca.La(s).next((function(t){return assert(r._(t)>=0,"Watch stream reverted to previous snapshot?? "+r+" < "+t),n.ca.qa(s,s.ka,r)}));u.push(c)}return PersistencePromise.$s(u).next((function(){return o.apply(s)})).next((function(){return n.fa.Eo(s,a)}))})).then((function(t){return n.na=i,t}))},t.xa=function(t,e,n){return assert(e.resumeToken.length>0,"Attempted to persist target data with no resume token"),0===t.resumeToken.length||(e.Ln.$()-t.Ln.$()>=this.Qa||n._r.size+n.cr.size+n.hr.size>0)},t.prototype.Wa=function(t){for(var e=this,n=0,r=t;n=0)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not contain '~', '*', '/', '[', or ']'");try{return new(FieldPath$1.bind.apply(FieldPath$1,tslib.__spreadArrays([void 0],t.split("."))))}catch(e){throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'")}}var __PRIVATE_UserDataSource,__PRIVATE_FieldValueImpl=function(){function t(t){this.T_=t}return t.delete=function(){return __PRIVATE_validateNoArgs("FieldValue.delete",arguments),__PRIVATE_DeleteFieldValueImpl.instance},t.serverTimestamp=function(){return __PRIVATE_validateNoArgs("FieldValue.serverTimestamp",arguments),__PRIVATE_ServerTimestampFieldValueImpl.instance},t.arrayUnion=function(){for(var t=[],e=0;e() instead."),__PRIVATE_RESERVED_FIELD_REGEX=/^__.*__$/,__PRIVATE_ParsedSetData=function(){function t(t,e,n){this.data=t,this.Ee=e,this.fieldTransforms=n}return t.prototype.A_=function(t,e){var n=[];return null!==this.Ee?n.push(new __PRIVATE_PatchMutation(t,this.data,this.Ee,e)):n.push(new __PRIVATE_SetMutation(t,this.data,e)),this.fieldTransforms.length>0&&n.push(new __PRIVATE_TransformMutation(t,this.fieldTransforms)),n},t}(),__PRIVATE_ParsedUpdateData=function(){function t(t,e,n){this.data=t,this.Ee=e,this.fieldTransforms=n}return t.prototype.A_=function(t,e){var n=[new __PRIVATE_PatchMutation(t,this.data,this.Ee,e)];return this.fieldTransforms.length>0&&n.push(new __PRIVATE_TransformMutation(t,this.fieldTransforms)),n},t}();function __PRIVATE_isWrite(t){switch(t){case __PRIVATE_UserDataSource.Set:case __PRIVATE_UserDataSource.R_:case __PRIVATE_UserDataSource.I_:return!0;case __PRIVATE_UserDataSource.V_:case __PRIVATE_UserDataSource.m_:return!1;default:throw fail("Unexpected case for UserDataSource: "+t)}}!function(t){t[t.Set=0]="Set",t[t.I_=1]="__PRIVATE_Update",t[t.R_=2]="__PRIVATE_MergeSet",t[t.V_=3]="__PRIVATE_Argument",t[t.m_=4]="__PRIVATE_ArrayArgument"}(__PRIVATE_UserDataSource||(__PRIVATE_UserDataSource={}));var __PRIVATE_ParseContext=function(){function t(t,e,n,r,i,s){this.v_=t,this.methodName=e,this.path=n,this.p_=r,void 0===i&&this.b_(),this.p_=void 0!==r&&r,this.fieldTransforms=i||[],this.Ee=s||[]}return t.prototype.g_=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.v_,this.methodName,n,!1,this.fieldTransforms,this.Ee);return r.w_(e),r},t.prototype.y_=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.v_,this.methodName,n,!1,this.fieldTransforms,this.Ee);return r.b_(),r},t.prototype.S_=function(e){return new t(this.v_,this.methodName,null,!0,this.fieldTransforms,this.Ee)},t.prototype.D_=function(t){var e=null===this.path||this.path.et()?"":" (found in field "+this.path.toString()+")";return new FirestoreError(Code.INVALID_ARGUMENT,"Function "+this.methodName+"() called with invalid data. "+t+e)},t.prototype.contains=function(t){return void 0!==this.Ee.find((function(e){return t.it(e)}))||void 0!==this.fieldTransforms.find((function(e){return t.it(e.field)}))},t.prototype.b_=function(){if(null!==this.path)for(var t=0;t0&&e.Ee.push(e.path):forEach(t,(function(t,i){var s=n.F_(i,e.g_(t));null!=s&&(r=r.At(t,s))})),new __PRIVATE_ObjectValue(r)},t.prototype.x_=function(t,e){for(var n=[],r=0,i=0,s=t;i0,"FieldValue.delete() at the top level should have already been handled."),e.D_("FieldValue.delete() can only appear at the top level of your update data")):e.D_("FieldValue.delete() cannot be used with set() unless you pass {merge:true}");e.Ee.push(e.path)}else if(t instanceof __PRIVATE_ServerTimestampFieldValueImpl)e.fieldTransforms.push(new FieldTransform(e.path,__PRIVATE_ServerTimestampTransform.instance));else if(t instanceof __PRIVATE_ArrayUnionFieldValueImpl){var n=this.j_(t.T_,t.E_),r=new __PRIVATE_ArrayUnionTransformOperation(n);e.fieldTransforms.push(new FieldTransform(e.path,r))}else if(t instanceof __PRIVATE_ArrayRemoveFieldValueImpl){n=this.j_(t.T_,t.E_);var i=new __PRIVATE_ArrayRemoveTransformOperation(n);e.fieldTransforms.push(new FieldTransform(e.path,i))}else if(t instanceof __PRIVATE_NumericIncrementFieldValueImpl){var s=this.B_("FieldValue.increment",t.P_),o=new __PRIVATE_NumericIncrementTransformOperation(s);e.fieldTransforms.push(new FieldTransform(e.path,o))}else fail("Unknown FieldValue type: "+t)},t.prototype.K_=function(t,e){if(null===t)return __PRIVATE_NullValue.ke;if("number"==typeof t)return isSafeInteger(t)?new __PRIVATE_IntegerValue(t):new __PRIVATE_DoubleValue(t);if("boolean"==typeof t)return __PRIVATE_BooleanValue.of(t);if("string"==typeof t)return new __PRIVATE_StringValue(t);if(t instanceof Date)return new __PRIVATE_TimestampValue(Timestamp.fromDate(t));if(t instanceof Timestamp)return new __PRIVATE_TimestampValue(new Timestamp(t.seconds,1e3*Math.floor(t.nanoseconds/1e3)));if(t instanceof GeoPoint)return new __PRIVATE_GeoPointValue(t);if(t instanceof Blob)return new __PRIVATE_BlobValue(t);if(t instanceof __PRIVATE_DocumentKeyReference)return new __PRIVATE_RefValue(t.o,t.key);throw e.D_("Unsupported field value: "+__PRIVATE_valueDescription(t))},t.prototype.j_=function(t,e){var n=this;return e.map((function(e,r){var i=new __PRIVATE_ParseContext(__PRIVATE_UserDataSource.V_,t,FieldPath._t);return n.F_(e,i.S_(r))}))},t}();function __PRIVATE_looksLikeJsonObject(t){return!("object"!=typeof t||null===t||t instanceof Array||t instanceof Date||t instanceof Timestamp||t instanceof GeoPoint||t instanceof Blob||t instanceof __PRIVATE_DocumentKeyReference||t instanceof __PRIVATE_FieldValueImpl)}function __PRIVATE_validatePlainObject(t,e,n){if(!__PRIVATE_looksLikeJsonObject(n)||!__PRIVATE_isPlainObject(n)){var r=__PRIVATE_valueDescription(n);throw"an object"===r?e.D_(t+" a custom object"):e.D_(t+" "+r)}}function __PRIVATE_fieldPathFromArgument(t,e){if(e instanceof FieldPath$1)return e.l_;if("string"==typeof e)return __PRIVATE_fieldPathFromDotSeparatedString(t,e);throw new FirestoreError(Code.INVALID_ARGUMENT,"Function "+t+"() called with invalid data. Field path arguments must be of type string or FieldPath.")}function __PRIVATE_fieldPathFromDotSeparatedString(t,e){try{return __PRIVATE_fromDotSeparatedString(e).l_}catch(e){var n=__PRIVATE_errorMessage(e);throw new FirestoreError(Code.INVALID_ARGUMENT,"Function "+t+"() called with invalid data. "+n)}}function __PRIVATE_errorMessage(t){return t instanceof Error?t.message:t.toString()}var __PRIVATE_PersistentStreamState,__PRIVATE_LOG_TAG$2="ExponentialBackoff",__PRIVATE_DEFAULT_BACKOFF_INITIAL_DELAY_MS=1e3,__PRIVATE_DEFAULT_BACKOFF_FACTOR=1.5,__PRIVATE_DEFAULT_BACKOFF_MAX_DELAY_MS=6e4,__PRIVATE_ExponentialBackoff=function(){function t(t,e,n,r,i){void 0===n&&(n=__PRIVATE_DEFAULT_BACKOFF_INITIAL_DELAY_MS),void 0===r&&(r=__PRIVATE_DEFAULT_BACKOFF_FACTOR),void 0===i&&(i=__PRIVATE_DEFAULT_BACKOFF_MAX_DELAY_MS),this.q_=t,this.qo=e,this.Q_=n,this.W_=r,this.Y_=i,this.H_=0,this.X_=null,this.z_=Date.now(),this.reset()}return t.prototype.reset=function(){this.H_=0},t.prototype.J_=function(){this.H_=this.Y_},t.prototype.Z_=function(t){var e=this;this.cancel();var n=Math.floor(this.H_+this.tc()),r=Math.max(0,Date.now()-this.z_),i=Math.max(0,n-r);this.H_>0&&debug(__PRIVATE_LOG_TAG$2,"Backing off for "+i+" ms (base delay: "+this.H_+" ms, delay with jitter: "+n+" ms, last attempt: "+r+" ms ago)"),this.X_=this.q_.hu(this.qo,i,(function(){return e.z_=Date.now(),t()})),this.H_*=this.W_,this.H_this.Y_&&(this.H_=this.Y_)},t.prototype.cancel=function(){null!==this.X_&&(this.X_.cancel(),this.X_=null)},t.prototype.tc=function(){return(Math.random()-.5)*this.H_},t}(),__PRIVATE_LOG_TAG$3="PersistentStream";!function(t){t[t.ec=0]="__PRIVATE_Initial",t[t.nc=1]="__PRIVATE_Starting",t[t.rc=2]="__PRIVATE_Open",t[t.Error=3]="Error",t[t.ic=4]="__PRIVATE_Backoff"}(__PRIVATE_PersistentStreamState||(__PRIVATE_PersistentStreamState={}));var __PRIVATE_IDLE_TIMEOUT_MS=6e4,__PRIVATE_PersistentStream=function(){function t(t,e,n,r,i,s){this.q_=t,this.sc=n,this.oc=r,this.uc=i,this.listener=s,this.state=__PRIVATE_PersistentStreamState.ec,this.ac=0,this._c=null,this.stream=null,this.cc=new __PRIVATE_ExponentialBackoff(t,e)}return t.prototype.hc=function(){return this.state===__PRIVATE_PersistentStreamState.nc||this.state===__PRIVATE_PersistentStreamState.rc||this.state===__PRIVATE_PersistentStreamState.ic},t.prototype.fc=function(){return this.state===__PRIVATE_PersistentStreamState.rc},t.prototype.start=function(){this.state!==__PRIVATE_PersistentStreamState.Error?(assert(this.state===__PRIVATE_PersistentStreamState.ec,"Already started"),this.auth()):this.lc()},t.prototype.stop=function(){return tslib.__awaiter(this,void 0,void 0,(function(){return tslib.__generator(this,(function(t){switch(t.label){case 0:return this.hc()?[4,this.close(__PRIVATE_PersistentStreamState.ec)]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))},t.prototype.dc=function(){assert(!this.hc(),"Can only inhibit backoff in a stopped state"),this.state=__PRIVATE_PersistentStreamState.ec,this.cc.reset()},t.prototype.Tc=function(){var t=this;this.fc()&&null===this._c&&(this._c=this.q_.hu(this.sc,__PRIVATE_IDLE_TIMEOUT_MS,(function(){return t.Ec()})))},t.prototype.Pc=function(t){this.Ac(),this.stream.send(t)},t.prototype.Ec=function(){return tslib.__awaiter(this,void 0,void 0,(function(){return tslib.__generator(this,(function(t){return this.fc()?[2,this.close(__PRIVATE_PersistentStreamState.ec)]:[2]}))}))},t.prototype.Ac=function(){this._c&&(this._c.cancel(),this._c=null)},t.prototype.close=function(t,e){return tslib.__awaiter(this,void 0,void 0,(function(){return tslib.__generator(this,(function(n){switch(n.label){case 0:return assert(this.hc(),"Only started streams should be closed."),assert(t===__PRIVATE_PersistentStreamState.Error||__PRIVATE_isNullOrUndefined(e),"Can't provide an error when not in an error state."),this.Ac(),this.cc.cancel(),this.ac++,t!==__PRIVATE_PersistentStreamState.Error?this.cc.reset():e&&e.code===Code.RESOURCE_EXHAUSTED?(error(e.toString()),error("Using maximum backoff delay to prevent overloading the backend."),this.cc.J_()):e&&e.code===Code.UNAUTHENTICATED&&this.uc.g(),null!==this.stream&&(this.Rc(),this.stream.close(),this.stream=null),this.state=t,[4,this.listener.Ic(e)];case 1:return n.sent(),[2]}}))}))},t.prototype.Rc=function(){},t.prototype.auth=function(){var t=this;assert(this.state===__PRIVATE_PersistentStreamState.ec,"Must be in initial state to auth"),this.state=__PRIVATE_PersistentStreamState.nc;var e=this.Vc(this.ac),n=this.ac;this.uc.getToken().then((function(e){t.ac===n&&t.mc(e)}),(function(n){e((function(){var e=new FirestoreError(Code.UNKNOWN,"Fetching auth token failed: "+n.message);return t.vc(e)}))}))},t.prototype.mc=function(t){var e=this;assert(this.state===__PRIVATE_PersistentStreamState.nc,"Trying to start stream in a non-starting state");var n=this.Vc(this.ac);this.stream=this.pc(t),this.stream.bc((function(){n((function(){return assert(e.state===__PRIVATE_PersistentStreamState.nc,"Expected stream to be in state Starting, but was "+e.state),e.state=__PRIVATE_PersistentStreamState.rc,e.listener.bc()}))})),this.stream.Ic((function(t){n((function(){return e.vc(t)}))})),this.stream.onMessage((function(t){n((function(){return e.onMessage(t)}))}))},t.prototype.lc=function(){var t=this;assert(this.state===__PRIVATE_PersistentStreamState.Error,"Should only perform backoff when in Error state"),this.state=__PRIVATE_PersistentStreamState.ic,this.cc.Z_((function(){return tslib.__awaiter(t,void 0,void 0,(function(){return tslib.__generator(this,(function(t){return assert(this.state===__PRIVATE_PersistentStreamState.ic,"Backoff elapsed but state is now: "+this.state),this.state=__PRIVATE_PersistentStreamState.ec,this.start(),assert(this.hc(),"PersistentStream should have started"),[2]}))}))}))},t.prototype.vc=function(t){return assert(this.hc(),"Can't handle server close on non-started stream"),debug(__PRIVATE_LOG_TAG$3,"close with error: "+t),this.stream=null,this.close(__PRIVATE_PersistentStreamState.Error,t)},t.prototype.Vc=function(t){var e=this;return function(n){e.q_.Jo((function(){return e.ac===t?n():(debug(__PRIVATE_LOG_TAG$3,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())}))}},t}(),__PRIVATE_PersistentListenStream=function(t){function e(e,n,r,i,s){var o=t.call(this,e,__PRIVATE_TimerId.Lo,__PRIVATE_TimerId.Mo,n,r,s)||this;return o.serializer=i,o}return tslib.__extends(e,t),e.prototype.pc=function(t){return this.oc.gc("Listen",t)},e.prototype.onMessage=function(t){this.cc.reset();var e=this.serializer.Ni(t),n=this.serializer.Li(t);return this.listener.wc(e,n)},e.prototype.yc=function(t){var e={};e.database=this.serializer.Ri,e.addTarget=this.serializer.Rn(t);var n=this.serializer.rs(t);n&&(e.labels=n),this.Pc(e)},e.prototype.Sc=function(t){var e={};e.database=this.serializer.Ri,e.removeTarget=t,this.Pc(e)},e}(__PRIVATE_PersistentStream),__PRIVATE_PersistentWriteStream=function(t){function e(e,n,r,i,s){var o=t.call(this,e,__PRIVATE_TimerId.Bo,__PRIVATE_TimerId.Go,n,r,s)||this;return o.serializer=i,o.Dc=!1,o.lastStreamToken=__PRIVATE_emptyByteString(),o}return tslib.__extends(e,t),Object.defineProperty(e.prototype,"Cc",{get:function(){return this.Dc},enumerable:!0,configurable:!0}),e.prototype.start=function(){this.Dc=!1,t.prototype.start.call(this)},e.prototype.Rc=function(){this.Dc&&this.Oc([])},e.prototype.pc=function(t){return this.oc.gc("Write",t)},e.prototype.onMessage=function(t){if(assert(!!t.streamToken,"Got a write response without a stream token"),this.lastStreamToken=t.streamToken,this.Dc){this.cc.reset();var e=this.serializer.Wi(t.writeResults,t.commitTime),n=this.serializer.fromVersion(t.commitTime);return this.listener.Fc(n,e)}return assert(!t.writeResults||0===t.writeResults.length,"Got mutation results for handshake"),this.Dc=!0,this.listener.Nc()},e.prototype.Mc=function(){assert(this.fc(),"Writing handshake requires an opened stream"),assert(!this.Dc,"Handshake already completed");var t={};t.database=this.serializer.Ri,this.Pc(t)},e.prototype.Oc=function(t){var e=this;assert(this.fc(),"Writing mutations requires an opened stream"),assert(this.Dc,"Handshake must be complete before writing mutations"),assert(this.lastStreamToken.length>0,"Trying to write mutation without a token");var n={streamToken:this.lastStreamToken,writes:t.map((function(t){return e.serializer.Gi(t)}))};this.Pc(n)},e}(__PRIVATE_PersistentStream),__PRIVATE_Datastore=function(){function t(t,e,n,r){this.q_=t,this.oc=e,this.credentials=n,this.serializer=r}return t.prototype.Lc=function(t){return new __PRIVATE_PersistentWriteStream(this.q_,this.oc,this.credentials,this.serializer,t)},t.prototype.Gc=function(t){return new __PRIVATE_PersistentListenStream(this.q_,this.oc,this.credentials,this.serializer,t)},t.prototype.commit=function(t){var e=this,n={database:this.serializer.Ri,writes:t.map((function(t){return e.serializer.Gi(t)}))};return this.Bc("Commit",n).then((function(t){return e.serializer.Wi(t.writeResults,t.commitTime)}))},t.prototype.Uc=function(t){var e=this,n={database:this.serializer.Ri,documents:t.map((function(t){return e.serializer.di(t)}))};return this.kc("BatchGetDocuments",n).then((function(n){var r=__PRIVATE_maybeDocumentMap();n.forEach((function(t){var n=e.serializer.Ci(t);r=r.At(n.key,n)}));var i=[];return t.forEach((function(t){var e=r.get(t);assert(!!e,"Missing entity in write response for "+t),i.push(e)})),i}))},t.prototype.Bc=function(t,e){var n=this;return this.credentials.getToken().then((function(r){return n.oc.Bc(t,e,r)})).catch((function(t){throw t.code===Code.UNAUTHENTICATED&&n.credentials.g(),t}))},t.prototype.kc=function(t,e){var n=this;return this.credentials.getToken().then((function(r){return n.oc.kc(t,e,r)})).catch((function(t){throw t.code===Code.UNAUTHENTICATED&&n.credentials.g(),t}))},t}(),Transaction=function(){function t(t){this.xc=t,this.Kc=__PRIVATE_documentVersionMap(),this.mutations=[],this.jc=!1,this.qc=null,this.Qc=new Set}return t.prototype.Uc=function(t){return tslib.__awaiter(this,void 0,void 0,(function(){var e,n=this;return tslib.__generator(this,(function(r){switch(r.label){case 0:if(this.Wc(),this.mutations.length>0)throw new FirestoreError(Code.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");return[4,this.xc.Uc(t)];case 1:return(e=r.sent()).forEach((function(t){t instanceof __PRIVATE_NoDocument||t instanceof Document?n.$c(t):fail("Document in a transaction was a "+t.constructor.name)})),[2,e]}}))}))},t.prototype.set=function(t,e){this.write(e.A_(t,this.le(t))),this.Qc.add(t)},t.prototype.update=function(t,e){try{this.write(e.A_(t,this.Yc(t)))}catch(t){this.qc=t}this.Qc.add(t)},t.prototype.delete=function(t){this.write([new __PRIVATE_DeleteMutation(t,this.le(t))]),this.Qc.add(t)},t.prototype.commit=function(){return tslib.__awaiter(this,void 0,void 0,(function(){var t,e=this;return tslib.__generator(this,(function(n){switch(n.label){case 0:if(this.Wc(),this.qc)throw this.qc;return t=this.Kc,this.mutations.forEach((function(e){t=t.remove(e.key)})),t.forEach((function(t,n){e.mutations.push(new __PRIVATE_VerifyMutation(t,e.le(t)))})),[4,this.xc.commit(this.mutations)];case 1:return n.sent(),this.jc=!0,[2]}}))}))},t.prototype.$c=function(t){var e;if(t instanceof Document)e=t.version;else{if(!(t instanceof __PRIVATE_NoDocument))throw fail("Document in a transaction was a "+t.constructor.name);e=__PRIVATE_SnapshotVersion.W()}var n=this.Kc.get(t.key);if(null!==n){if(!e.isEqual(n))throw new FirestoreError(Code.ABORTED,"Document version changed between two reads.")}else this.Kc=this.Kc.At(t.key,e)},t.prototype.le=function(t){var e=this.Kc.get(t);return!this.Qc.has(t)&&e?Precondition.updateTime(e):Precondition.NONE},t.prototype.Yc=function(t){var e=this.Kc.get(t);if(!this.Qc.has(t)&&e){if(e.isEqual(__PRIVATE_SnapshotVersion.W()))throw new FirestoreError(Code.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Precondition.updateTime(e)}return Precondition.exists(!0)},t.prototype.write=function(t){this.Wc(),this.mutations=this.mutations.concat(t)},t.prototype.Wc=function(){assert(!this.jc,"A transaction object cannot be used after its update callback has been invoked.")},t}(),__PRIVATE_LOG_TAG$4="OnlineStateTracker",__PRIVATE_MAX_WATCH_STREAM_FAILURES=1,__PRIVATE_ONLINE_STATE_TIMEOUT_MS=1e4,__PRIVATE_OnlineStateTracker=function(){function t(t,e){this.jo=t,this.Hc=e,this.state=__PRIVATE_OnlineState.h,this.Xc=0,this.zc=null,this.Jc=!0}return t.prototype.Zc=function(){var t=this;0===this.Xc&&(this.th(__PRIVATE_OnlineState.h),assert(null===this.zc,"onlineStateTimer shouldn't be started yet"),this.zc=this.jo.hu(__PRIVATE_TimerId.Uo,__PRIVATE_ONLINE_STATE_TIMEOUT_MS,(function(){return t.zc=null,assert(t.state===__PRIVATE_OnlineState.h,"Timer should be canceled if we transitioned to a different state."),t.eh("Backend didn't respond within "+__PRIVATE_ONLINE_STATE_TIMEOUT_MS/1e3+" seconds."),t.th(__PRIVATE_OnlineState.T),Promise.resolve()})))},t.prototype.nh=function(t){this.state===__PRIVATE_OnlineState.l?(this.th(__PRIVATE_OnlineState.h),assert(0===this.Xc,"watchStreamFailures must be 0"),assert(null===this.zc,"onlineStateTimer must be null")):(this.Xc++,this.Xc>=__PRIVATE_MAX_WATCH_STREAM_FAILURES&&(this.rh(),this.eh("Connection failed "+__PRIVATE_MAX_WATCH_STREAM_FAILURES+" times. Most recent error: "+t.toString()),this.th(__PRIVATE_OnlineState.T)))},t.prototype.set=function(t){this.rh(),this.Xc=0,t===__PRIVATE_OnlineState.l&&(this.Jc=!1),this.th(t)},t.prototype.th=function(t){t!==this.state&&(this.state=t,this.Hc(t))},t.prototype.eh=function(t){var e="Could not reach Cloud Firestore backend. "+t+"\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.";this.Jc?(error(e),this.Jc=!1):debug(__PRIVATE_LOG_TAG$4,e)},t.prototype.rh=function(){null!==this.zc&&(this.zc.cancel(),this.zc=null)},t}(),__PRIVATE_LOG_TAG$5="RemoteStore",__PRIVATE_MAX_PENDING_WRITES=10,__PRIVATE_RemoteStore=function(){function t(t,e,n,r,i){var s=this;this.Gu=t,this.xc=e,this.ih=[],this.sh={},this.oh=null,this.networkEnabled=!1,this.isPrimary=!1,this.uh=i,this.uh.ah((function(t){n.Jo((function(){return tslib.__awaiter(s,void 0,void 0,(function(){return tslib.__generator(this,(function(t){switch(t.label){case 0:return this._h()?(debug(__PRIVATE_LOG_TAG$5,"Restarting streams for network reachability change."),[4,this.hh()]):[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))}))})),this.fh=new __PRIVATE_OnlineStateTracker(n,r),this.lh=this.xc.Gc({bc:this.dh.bind(this),Ic:this.Th.bind(this),wc:this.Eh.bind(this)}),this.Ph=this.xc.Lc({bc:this.Ah.bind(this),Ic:this.Rh.bind(this),Nc:this.Ih.bind(this),Fc:this.Fc.bind(this)})}return t.prototype.start=function(){return this.enableNetwork()},t.prototype.enableNetwork=function(){return tslib.__awaiter(this,void 0,void 0,(function(){var t;return tslib.__generator(this,(function(e){switch(e.label){case 0:return this.networkEnabled=!0,this._h()?(t=this.Ph,[4,this.Gu.Na()]):[3,3];case 1:return t.lastStreamToken=e.sent(),this.Vh()?this.mh():this.fh.set(__PRIVATE_OnlineState.h),[4,this.vh()];case 2:e.sent(),e.label=3;case 3:return[2]}}))}))},t.prototype.disableNetwork=function(){return tslib.__awaiter(this,void 0,void 0,(function(){return tslib.__generator(this,(function(t){switch(t.label){case 0:return this.networkEnabled=!1,[4,this.ph()];case 1:return t.sent(),this.fh.set(__PRIVATE_OnlineState.T),[2]}}))}))},t.prototype.ph=function(){return tslib.__awaiter(this,void 0,void 0,(function(){return tslib.__generator(this,(function(t){switch(t.label){case 0:return[4,this.Ph.stop()];case 1:return t.sent(),[4,this.lh.stop()];case 2:return t.sent(),this.ih.length>0&&(debug(__PRIVATE_LOG_TAG$5,"Stopping write stream with "+this.ih.length+" pending writes"),this.ih=[]),this.bh(),[2]}}))}))},t.prototype.gh=function(){return tslib.__awaiter(this,void 0,void 0,(function(){return tslib.__generator(this,(function(t){switch(t.label){case 0:return debug(__PRIVATE_LOG_TAG$5,"RemoteStore shutting down."),this.networkEnabled=!1,[4,this.ph()];case 1:return t.sent(),this.uh.gh(),this.fh.set(__PRIVATE_OnlineState.h),[2]}}))}))},t.prototype.listen=function(t){contains(this.sh,t.targetId)||(this.sh[t.targetId]=t,this.Vh()?this.mh():this.lh.fc()&&this.wh(t))},t.prototype.yh=function(t){assert(contains(this.sh,t),"unlisten called on target no currently watched: "+t),delete this.sh[t],this.lh.fc()&&this.Sh(t),__PRIVATE_isEmpty(this.sh)&&(this.lh.fc()?this.lh.Tc():this._h()&&this.fh.set(__PRIVATE_OnlineState.h))},t.prototype.ti=function(t){return this.sh[t]||null},t.prototype.Zr=function(t){return this.Dh.Zr(t)},t.prototype.wh=function(t){this.oh.Cr(t.targetId),this.lh.yc(t)},t.prototype.Sh=function(t){this.oh.Cr(t),this.lh.Sc(t)},t.prototype.mh=function(){assert(this.Vh(),"startWatchStream() called when shouldStartWatchStream() is false."),this.oh=new __PRIVATE_WatchChangeAggregator(this),this.lh.start(),this.fh.Zc()},t.prototype.Vh=function(){return this._h()&&!this.lh.hc()&&!__PRIVATE_isEmpty(this.sh)},t.prototype._h=function(){return this.isPrimary&&this.networkEnabled},t.prototype.bh=function(){this.oh=null},t.prototype.dh=function(){return tslib.__awaiter(this,void 0,void 0,(function(){var t=this;return tslib.__generator(this,(function(e){return __PRIVATE_forEachNumber(this.sh,(function(e,n){t.wh(n)})),[2]}))}))},t.prototype.Th=function(t){return tslib.__awaiter(this,void 0,void 0,(function(){return tslib.__generator(this,(function(e){return void 0===t&&assert(!this.Vh(),"Watch stream was stopped gracefully while still needed."),this.bh(),this.Vh()?(this.fh.nh(t),this.mh()):this.fh.set(__PRIVATE_OnlineState.h),[2]}))}))},t.prototype.Eh=function(t,e){return tslib.__awaiter(this,void 0,void 0,(function(){var n;return tslib.__generator(this,(function(r){switch(r.label){case 0:return this.fh.set(__PRIVATE_OnlineState.l),t instanceof __PRIVATE_WatchTargetChange&&t.state===__PRIVATE_WatchTargetChangeState.qn&&t.cause?[2,this.Ch(t)]:(t instanceof __PRIVATE_DocumentWatchChange?this.oh.Ur(t):t instanceof __PRIVATE_ExistenceFilterChange?this.oh.$r(t):(assert(t instanceof __PRIVATE_WatchTargetChange,"Expected watchChange to be an instance of WatchTargetChange"),this.oh.Kr(t)),e.isEqual(__PRIVATE_SnapshotVersion.MIN)?[3,3]:[4,this.Gu.La()]);case 1:return n=r.sent(),e._(n)>=0?[4,this.Oh(e)]:[3,3];case 2:r.sent(),r.label=3;case 3:return[2]}}))}))},t.prototype.Oh=function(t){var e=this;assert(!t.isEqual(__PRIVATE_SnapshotVersion.MIN),"Can't raise event for unknown SnapshotVersion");var n=this.oh.Xr(t);return __PRIVATE_forEachNumber(n.nr,(function(n,r){if(r.resumeToken.length>0){var i=e.sh[n];i&&(e.sh[n]=i.Bn(r.resumeToken,t))}})),n.rr.forEach((function(t){var n=e.sh[t];if(n){e.sh[t]=n.Bn(__PRIVATE_emptyByteString(),n.Ln),e.Sh(t);var r=new __PRIVATE_TargetData(n.target,t,__PRIVATE_TargetPurpose.Fn,n.sequenceNumber);e.wh(r)}})),this.Dh.Ga(n)},t.prototype.Ch=function(t){var e=this;assert(!!t.cause,"Handling target error without a cause");var n=t.cause,r=Promise.resolve();return t.targetIds.forEach((function(t){r=r.then((function(){return tslib.__awaiter(e,void 0,void 0,(function(){return tslib.__generator(this,(function(e){return contains(this.sh,t)?(delete this.sh[t],this.oh.removeTarget(t),[2,this.Dh.Fh(t,n)]):[2]}))}))}))})),r},t.prototype.vh=function(){return tslib.__awaiter(this,void 0,void 0,(function(){var t,e;return tslib.__generator(this,(function(n){switch(n.label){case 0:return this.Nh()?(t=this.ih.length>0?this.ih[this.ih.length-1].batchId:__PRIVATE_BATCHID_UNKNOWN,[4,this.Gu.$a(t)]):[3,4];case 1:return null!==(e=n.sent())?[3,2]:(0===this.ih.length&&this.Ph.Tc(),[3,4]);case 2:return this.Mh(e),[4,this.vh()];case 3:n.sent(),n.label=4;case 4:return this.Lh()&&this.Gh(),[2]}}))}))},t.prototype.Nh=function(){return this._h()&&this.ih.length<__PRIVATE_MAX_PENDING_WRITES},t.prototype.Bh=function(){return this.ih.length},t.prototype.Mh=function(t){assert(this.Nh(),"addToWritePipeline called when pipeline is full"),this.ih.push(t),this.Ph.fc()&&this.Ph.Cc&&this.Ph.Oc(t.mutations)},t.prototype.Lh=function(){return this._h()&&!this.Ph.hc()&&this.ih.length>0},t.prototype.Gh=function(){assert(this.Lh(),"startWriteStream() called when shouldStartWriteStream() is false."),this.Ph.start()},t.prototype.Ah=function(){return tslib.__awaiter(this,void 0,void 0,(function(){return tslib.__generator(this,(function(t){return this.Ph.Mc(),[2]}))}))},t.prototype.Ih=function(){var t=this;return this.Gu.Ma(this.Ph.lastStreamToken).then((function(){for(var e=0,n=t.ih;e0,"Got result for empty write pipeline");var r=this.ih.shift(),i=__PRIVATE_MutationBatchResult.from(r,t,e,this.Ph.lastStreamToken);return this.Dh.Uh(i).then((function(){return n.vh()}))},t.prototype.Rh=function(t){return tslib.__awaiter(this,void 0,void 0,(function(){var e=this;return tslib.__generator(this,(function(n){return void 0===t&&assert(!this.Lh(),"Write stream was stopped gracefully while still needed."),t&&this.ih.length>0?(void 0,[2,(this.Ph.Cc?this.kh(t):this.xh(t)).then((function(){e.Lh()&&e.Gh()}))]):[2]}))}))},t.prototype.xh=function(t){return tslib.__awaiter(this,void 0,void 0,(function(){return tslib.__generator(this,(function(e){return __PRIVATE_isPermanentError(t.code)?(debug(__PRIVATE_LOG_TAG$5,"RemoteStore error before completed handshake; resetting stream token: ",this.Ph.lastStreamToken),this.Ph.lastStreamToken=__PRIVATE_emptyByteString(),[2,this.Gu.Ma(__PRIVATE_emptyByteString()).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss)]):[2]}))}))},t.prototype.kh=function(t){return tslib.__awaiter(this,void 0,void 0,(function(){var e,n=this;return tslib.__generator(this,(function(r){return __PRIVATE_isPermanentWriteError(t.code)?(e=this.ih.shift(),this.Ph.dc(),[2,this.Dh.Kh(e.batchId,t).then((function(){return n.vh()}))]):[2]}))}))},t.prototype.jh=function(){return new Transaction(this.xc)},t.prototype.hh=function(){return tslib.__awaiter(this,void 0,void 0,(function(){return tslib.__generator(this,(function(t){switch(t.label){case 0:return this.networkEnabled=!1,[4,this.ph()];case 1:return t.sent(),this.fh.set(__PRIVATE_OnlineState.h),[4,this.enableNetwork()];case 2:return t.sent(),[2]}}))}))},t.prototype.qh=function(){return tslib.__awaiter(this,void 0,void 0,(function(){return tslib.__generator(this,(function(t){switch(t.label){case 0:return this._h()?(debug(__PRIVATE_LOG_TAG$5,"RemoteStore restarting streams for new credential"),[4,this.hh()]):[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))},t.prototype.Qh=function(t){return tslib.__awaiter(this,void 0,void 0,(function(){return tslib.__generator(this,(function(e){switch(e.label){case 0:return this.isPrimary=t,t&&this.networkEnabled?[4,this.enableNetwork()]:[3,2];case 1:return e.sent(),[3,4];case 2:return t?[3,4]:[4,this.ph()];case 3:e.sent(),this.fh.set(__PRIVATE_OnlineState.h),e.label=4;case 4:return[2]}}))}))},t}(),CLIENT_STATE_KEY_PREFIX="firestore_clients";function createWebStorageClientStateKey(t,e){return assert(-1===e.indexOf("_"),"Client key cannot contain '_', but was '"+e+"'"),CLIENT_STATE_KEY_PREFIX+"_"+t+"_"+e}var MUTATION_BATCH_KEY_PREFIX="firestore_mutations";function createWebStorageMutationBatchKey(t,e,n){var r=MUTATION_BATCH_KEY_PREFIX+"_"+t+"_"+n;return e.R()&&(r+="_"+e.uid),r}var QUERY_TARGET_KEY_PREFIX="firestore_targets";function createWebStorageQueryTargetMetadataKey(t,e){return QUERY_TARGET_KEY_PREFIX+"_"+t+"_"+e}var ONLINE_STATE_KEY_PREFIX="firestore_online_state";function createWebStorageOnlineStateKey(t){return ONLINE_STATE_KEY_PREFIX+"_"+t}var SEQUENCE_NUMBER_KEY_PREFIX="firestore_sequence_number";function createWebStorageSequenceNumberKey(t){return SEQUENCE_NUMBER_KEY_PREFIX+"_"+t}var __PRIVATE_LOG_TAG$6="SharedClientState",__PRIVATE_MutationMetadata=function(){function t(t,e,n,r){this.user=t,this.batchId=e,this.state=n,this.error=r,assert(void 0!==r==("rejected"===n),"MutationMetadata must contain an error iff state is 'rejected'")}return t.Wh=function(e,n,r){var i=JSON.parse(r),s="object"==typeof i&&-1!==["pending","acknowledged","rejected"].indexOf(i.state)&&(void 0===i.error||"object"==typeof i.error),o=void 0;return s&&i.error&&(s="string"==typeof i.error.message&&"string"==typeof i.error.code)&&(o=new FirestoreError(i.error.code,i.error.message)),s?new t(e,n,i.state,o):(error(__PRIVATE_LOG_TAG$6,"Failed to parse mutation state for ID '"+n+"': "+r),null)},t.prototype.$h=function(){var t={state:this.state,updateTimeMs:Date.now()};return this.error&&(t.error={code:this.error.code,message:this.error.message}),JSON.stringify(t)},t}(),__PRIVATE_QueryTargetMetadata=function(){function t(t,e,n){this.targetId=t,this.state=e,this.error=n,assert(void 0!==n==("rejected"===e),"QueryTargetMetadata must contain an error iff state is 'rejected'")}return t.Wh=function(e,n){var r=JSON.parse(n),i="object"==typeof r&&-1!==["not-current","current","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error),s=void 0;return i&&r.error&&(i="string"==typeof r.error.message&&"string"==typeof r.error.code)&&(s=new FirestoreError(r.error.code,r.error.message)),i?new t(e,r.state,s):(error(__PRIVATE_LOG_TAG$6,"Failed to parse target state for ID '"+e+"': "+n),null)},t.prototype.$h=function(){var t={state:this.state,updateTimeMs:Date.now()};return this.error&&(t.error={code:this.error.code,message:this.error.message}),JSON.stringify(t)},t}(),__PRIVATE_RemoteClientState=function(){function t(t,e){this.clientId=t,this.activeTargetIds=e}return t.Wh=function(e,n){for(var r=JSON.parse(n),i="object"==typeof r&&r.activeTargetIds instanceof Array,s=__PRIVATE_targetIdSet(),o=0;i&&o0&&this.dl(t)?(this._l-=1,this.jo.Jo((function(){return e.hl(),Promise.resolve()}))):this.$o.reject(t)},t.prototype.dl=function(t){if("FirebaseError"===t.name){var e=t.code;return"aborted"===e||"failed-precondition"===e||!__PRIVATE_isPermanentError(e)}return!1},t}(),__PRIVATE_LOG_TAG$7="SyncEngine",__PRIVATE_QueryView=function(t,e,n){this.query=t,this.targetId=e,this.view=n},__PRIVATE_LimboResolution=function(t){this.key=t,this.Tl=!1},__PRIVATE_SyncEngine=function(){function t(t,e,n,r){this.Gu=t,this.al=e,this.El=n,this.currentUser=r,this.Pl=null,this.Al=new __PRIVATE_ObjectMap((function(t){return t.canonicalId()})),this.Rl={},this.Il=new __PRIVATE_SortedMap(__PRIVATE_DocumentKey.X),this.Vl={},this.ml=new __PRIVATE_ReferenceSet,this.vl={},this.pl=new Map,this.bl=__PRIVATE_TargetIdGenerator.Qf(),this.isPrimary=void 0,this.onlineState=__PRIVATE_OnlineState.h}return Object.defineProperty(t.prototype,"gl",{get:function(){return!0===this.isPrimary},enumerable:!0,configurable:!0}),t.prototype.subscribe=function(t){assert(null!==t,"SyncEngine listener cannot be null"),assert(null===this.Pl,"SyncEngine already has a subscriber."),this.Pl=t},t.prototype.listen=function(t){return tslib.__awaiter(this,void 0,void 0,(function(){var e,n,r,i,s;return tslib.__generator(this,(function(o){switch(o.label){case 0:return this.wl("listen()"),(r=this.Al.get(t))?(e=r.targetId,this.El.Af(e),n=r.view.ul(),[3,4]):[3,1];case 1:return[4,this.Gu.Xa(t.Rn())];case 2:return i=o.sent(),s=this.El.Af(i.targetId),e=i.targetId,[4,this.yl(t,e,"current"===s)];case 3:n=o.sent(),this.isPrimary&&this.al.listen(i),o.label=4;case 4:return this.Pl.wc([n]),[2,e]}}))}))},t.prototype.yl=function(t,e,n){return tslib.__awaiter(this,void 0,void 0,(function(){var r,i,s,o,u,a;return tslib.__generator(this,(function(_){switch(_.label){case 0:return[4,this.Gu.e_(t,!0)];case 1:return r=_.sent(),i=new __PRIVATE_View(t,r.r_),s=i.zf(r.documents),o=TargetChange.ur(e,n&&this.onlineState!==__PRIVATE_OnlineState.T),assert(0===(u=i.io(s,!0===this.isPrimary,o)).rl.length,"View returned limbo docs before target ack from the server."),assert(!!u.snapshot,"applyChanges for new view should always return a snapshot"),a=new __PRIVATE_QueryView(t,e,i),this.Al.set(t,a),this.Rl[e]||(this.Rl[e]=[]),this.Rl[e].push(t),[2,u.snapshot]}}))}))},t.prototype.Sl=function(t){return tslib.__awaiter(this,void 0,void 0,(function(){var e,n;return tslib.__generator(this,(function(r){switch(r.label){case 0:return[4,this.Gu.e_(t.query,!0)];case 1:return e=r.sent(),n=t.view.ol(e),this.isPrimary&&this.Dl(t.targetId,n.rl),[2,n]}}))}))},t.prototype.yh=function(t){return tslib.__awaiter(this,void 0,void 0,(function(){var e,n,r=this;return tslib.__generator(this,(function(i){switch(i.label){case 0:return this.wl("unlisten()"),assert(!!(e=this.Al.get(t)),"Trying to unlisten on query not found:"+t),(n=this.Rl[e.targetId]).length>1?(this.Rl[e.targetId]=n.filter((function(e){return!e.isEqual(t)})),this.Al.delete(t),[2]):this.isPrimary?(this.El.If(e.targetId),this.El.lf(e.targetId)?[3,2]:[4,this.Gu.t_(e.targetId,!1).then((function(){r.El.mf(e.targetId),r.al.yh(e.targetId),r.Cl(e.targetId)})).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss)]):[3,3];case 1:i.sent(),i.label=2;case 2:return[3,5];case 3:return this.Cl(e.targetId),[4,this.Gu.t_(e.targetId,!0)];case 4:i.sent(),i.label=5;case 5:return[2]}}))}))},t.prototype.write=function(t,e){return tslib.__awaiter(this,void 0,void 0,(function(){var n;return tslib.__generator(this,(function(r){switch(r.label){case 0:return this.wl("write()"),[4,this.Gu.Va(t)];case 1:return n=r.sent(),this.El.df(n.batchId),this.Ol(n.batchId,e),[4,this.Fl(n.Hs)];case 2:return r.sent(),[4,this.al.vh()];case 3:return r.sent(),[2]}}))}))},t.prototype.runTransaction=function(t,e,n){new __PRIVATE_TransactionRunner(t,this.al,e,n).cl()},t.prototype.Ga=function(t){return tslib.__awaiter(this,void 0,void 0,(function(){var e,n=this;return tslib.__generator(this,(function(r){switch(r.label){case 0:this.wl("applyRemoteEvent()"),r.label=1;case 1:return r.trys.push([1,4,,6]),[4,this.Gu.Ga(t)];case 2:return e=r.sent(),forEach(t.nr,(function(t,e){var r=n.Vl[Number(t)];r&&(assert(e._r.size+e.cr.size+e.hr.size<=1,"Limbo resolution for single document contains multiple changes."),e._r.size>0?r.Tl=!0:e.cr.size>0?assert(r.Tl,"Received change for limbo target document without add."):e.hr.size>0&&(assert(r.Tl,"Received remove for limbo target document without add."),r.Tl=!1))})),[4,this.Fl(e,t)];case 3:return r.sent(),[3,6];case 4:return[4,__PRIVATE_ignoreIfPrimaryLeaseLoss(r.sent())];case 5:return r.sent(),[3,6];case 6:return[2]}}))}))},t.prototype.il=function(t,e){if(this.isPrimary&&e===__PRIVATE_OnlineStateSource.P||!this.isPrimary&&e===__PRIVATE_OnlineStateSource.A){this.wl("applyOnlineStateChange()");var n=[];this.Al.forEach((function(e,r){var i=r.view.il(t);assert(0===i.rl.length,"OnlineState should not affect limbo documents."),i.snapshot&&n.push(i.snapshot)})),this.Pl.Nl(t),this.Pl.wc(n),this.onlineState=t,this.isPrimary&&this.El.bf(t)}},t.prototype.Fh=function(t,e){return tslib.__awaiter(this,void 0,void 0,(function(){var n,r,i,s,o,u=this;return tslib.__generator(this,(function(a){switch(a.label){case 0:return this.wl("rejectListens()"),this.El.vf(t,"rejected",e),n=this.Vl[t],(r=n&&n.key)?(this.Il=this.Il.remove(r),delete this.Vl[t],i=(i=new __PRIVATE_SortedMap(__PRIVATE_DocumentKey.X)).At(r,new __PRIVATE_NoDocument(r,__PRIVATE_SnapshotVersion.W())),s=__PRIVATE_documentKeySet().add(r),o=new __PRIVATE_RemoteEvent(__PRIVATE_SnapshotVersion.MIN,{},new __PRIVATE_SortedSet(__PRIVATE_primitiveComparator),i,s),[2,this.Ga(o)]):[3,1];case 1:return[4,this.Gu.t_(t,!1).then((function(){return u.Cl(t,e)})).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss)];case 2:a.sent(),a.label=3;case 3:return[2]}}))}))},t.prototype.Nf=function(t,e,n){return tslib.__awaiter(this,void 0,void 0,(function(){var r;return tslib.__generator(this,(function(i){switch(i.label){case 0:return this.wl("applyBatchState()"),[4,this.Gu.va(t)];case 1:return null===(r=i.sent())?(debug(__PRIVATE_LOG_TAG$7,"Cannot apply mutation batch with id: "+t),[2]):"pending"!==e?[3,3]:[4,this.al.vh()];case 2:return i.sent(),[3,4];case 3:"acknowledged"===e||"rejected"===e?(this.Ml(t,n||null),this.Gu.o_(t)):fail("Unknown batchState: "+e),i.label=4;case 4:return[4,this.Fl(r)];case 5:return i.sent(),[2]}}))}))},t.prototype.Uh=function(t){return tslib.__awaiter(this,void 0,void 0,(function(){var e,n;return tslib.__generator(this,(function(r){switch(r.label){case 0:this.wl("applySuccessfulWrite()"),e=t.batch.batchId,this.Ml(e,null),this.Ll(e),r.label=1;case 1:return r.trys.push([1,4,,6]),[4,this.Gu.ba(t)];case 2:return n=r.sent(),this.El.Ef(e,"acknowledged"),[4,this.Fl(n)];case 3:return r.sent(),[3,6];case 4:return[4,__PRIVATE_ignoreIfPrimaryLeaseLoss(r.sent())];case 5:return r.sent(),[3,6];case 6:return[2]}}))}))},t.prototype.Kh=function(t,e){return tslib.__awaiter(this,void 0,void 0,(function(){var n;return tslib.__generator(this,(function(r){switch(r.label){case 0:this.wl("rejectFailedWrite()"),this.Ml(t,e),this.Ll(t),r.label=1;case 1:return r.trys.push([1,4,,6]),[4,this.Gu.Da(t)];case 2:return n=r.sent(),this.El.Ef(t,"rejected",e),[4,this.Fl(n)];case 3:return r.sent(),[3,6];case 4:return[4,__PRIVATE_ignoreIfPrimaryLeaseLoss(r.sent())];case 5:return r.sent(),[3,6];case 6:return[2]}}))}))},t.prototype.Gl=function(t){return tslib.__awaiter(this,void 0,void 0,(function(){var e,n;return tslib.__generator(this,(function(r){switch(r.label){case 0:return this.al._h()||debug(__PRIVATE_LOG_TAG$7,"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled."),[4,this.Gu.Fa()];case 1:return(e=r.sent())===__PRIVATE_BATCHID_UNKNOWN?(t.resolve(),[2]):((n=this.pl.get(e)||[]).push(t),this.pl.set(e,n),[2])}}))}))},t.prototype.Ll=function(t){(this.pl.get(t)||[]).forEach((function(t){t.resolve()})),this.pl.delete(t)},t.prototype.Bl=function(t){this.pl.forEach((function(e){e.forEach((function(e){e.reject(new FirestoreError(Code.CANCELLED,t))}))})),this.pl.clear()},t.prototype.Ol=function(t,e){var n=this.vl[this.currentUser.I()];n||(n=new __PRIVATE_SortedMap(__PRIVATE_primitiveComparator)),n=n.At(t,e),this.vl[this.currentUser.I()]=n},t.prototype.Ml=function(t,e){var n=this.vl[this.currentUser.I()];if(n){var r=n.get(t);r&&(assert(t===n.Vt(),"Mutation callbacks processed out-of-order?"),e?r.reject(e):r.resolve(),n=n.remove(t)),this.vl[this.currentUser.I()]=n}},t.prototype.Cl=function(t,e){var n=this;void 0===e&&(e=null),this.El.If(t),assert(this.Rl[t]&&0!==this.Rl[t].length,"There are no queries mapped to target id "+t);for(var r=0,i=this.Rl[t];r=0&&(r.$l.splice(i,1),n=0===r.$l.length),n?(this.Yl.delete(e),[2,this.Dh.yh(e)]):[2]}))}))},t.prototype.wc=function(t){for(var e=!1,n=0,r=t;n0||t.Zn,"We got a new snapshot with no changes?"),!this.options.includeMetadataChanges){for(var e=[],n=0,r=t.docChanges;n0)return!0;var e=this.nd&&this.nd.hasPendingWrites!==t.hasPendingWrites;return!(!t.Zn&&!e)&&!0===this.options.includeMetadataChanges},t.prototype.od=function(t){assert(!this.ed,"Trying to raise initial events for second time"),t=__PRIVATE_ViewSnapshot.er(t.query,t.docs,t.Jn,t.fromCache),this.ed=!0,this.td.next(t)},t}(),__PRIVATE_escapeChar="",__PRIVATE_encodedSeparatorChar="",__PRIVATE_encodedNul="",__PRIVATE_encodedEscape="";function encode(t){for(var e="",n=0;n0&&(e=__PRIVATE_encodeSeparator(e)),e=__PRIVATE_encodeSegment(t.get(n),e);return __PRIVATE_encodeSeparator(e)}function __PRIVATE_encodeSegment(t,e){for(var n=e,r=t.length,i=0;i=2,"Invalid path "+t),2===e)return assert(t.charAt(0)===__PRIVATE_escapeChar&&t.charAt(1)===__PRIVATE_encodedSeparatorChar,"Non-empty path "+t+" had length 2"),ResourcePath._t;for(var n=e-2,r=[],i="",s=0;sn)&&fail('Invalid encoded resource path: "'+t+'"'),t.charAt(o+1)){case __PRIVATE_encodedSeparatorChar:var u=t.substring(s,o),a=void 0;0===i.length?a=u:(a=i+=u,i=""),r.push(a);break;case __PRIVATE_encodedNul:i+=t.substring(s,o),i+="\0";break;case __PRIVATE_encodedEscape:i+=t.substring(s,o+1);break;default:fail('Invalid encoded resource path: "'+t+'"')}s=o+2}return new ResourcePath(r)}var __PRIVATE_LOG_TAG$8="SimpleDb",__PRIVATE_TRANSACTION_RETRY_COUNT=3,__PRIVATE_SimpleDb=function(){function t(e){this.db=e,12.2===t.ad(util.getUA())&&error("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}return t._d=function(e,n,r){return assert(t.ef(),"IndexedDB not supported in current environment."),debug(__PRIVATE_LOG_TAG$8,"Opening database:",e),new PersistencePromise((function(i,s){var o=window.indexedDB.open(e,n);o.onsuccess=function(e){var n=e.target.result;i(new t(n))},o.onblocked=function(){s(new FirestoreError(Code.FAILED_PRECONDITION,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},o.onerror=function(t){var e=t.target.error;"VersionError"===e.name?s(new FirestoreError(Code.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):s(e)},o.onupgradeneeded=function(t){debug(__PRIVATE_LOG_TAG$8,'Database "'+e+'" requires upgrade from version:',t.oldVersion);var n=t.target.result;r.createOrUpgrade(n,o.transaction,t.oldVersion,SCHEMA_VERSION).next((function(){debug(__PRIVATE_LOG_TAG$8,"Database upgrade to version "+SCHEMA_VERSION+" complete")}))}})).Qs()},t.delete=function(t){return debug(__PRIVATE_LOG_TAG$8,"Removing database:",t),__PRIVATE_wrapRequest(window.indexedDB.deleteDatabase(t)).Qs()},t.ef=function(){if("undefined"==typeof window||null==window.indexedDB)return!1;if(t.hd())return!0;if(void 0===window.navigator)return!1;var e=util.getUA(),n=t.ad(e),r=00||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0||r||s)},t.hd=function(){var t;return"undefined"!=typeof __PRIVATE_process&&"YES"===(null===(t=__PRIVATE_process.__PRIVATE_env)||void 0===t?void 0:t.ld)},t.dd=function(t,e){return t.store(e)},t.ad=function(t){var e=t.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=e?e[1].split("_").slice(0,2).join("."):"-1";return Number(n)},t.fd=function(t){var e=t.match(/Android ([\d.]+)/i),n=e?e[1].split(".").slice(0,2).join("."):"-1";return Number(n)},t.prototype.Td=function(t){this.db.onversionchange=function(e){return t(e)}},t.prototype.runTransaction=function(t,e,n){return tslib.__awaiter(this,void 0,void 0,(function(){var r,i,s,o,u,a;return tslib.__generator(this,(function(_){switch(_.label){case 0:r=t.startsWith("readonly"),i=t.endsWith("idempotent"),s=0,o=function(){var t,o,a,_;return tslib.__generator(this,(function(c){switch(c.label){case 0:++s,t=__PRIVATE_SimpleDbTransaction.open(u.db,r?"readonly":"readwrite",e),c.label=1;case 1:return c.trys.push([1,3,,4]),(o=n(t).catch((function(e){return t.abort(e),PersistencePromise.reject(e)})).Qs()).catch((function(){})),[4,t.Ed];case 2:return c.sent(),[2,{value:o}];case 3:return a=c.sent(),_=i&&"FirebaseError"!==a.name&&s<__PRIVATE_TRANSACTION_RETRY_COUNT,debug(__PRIVATE_LOG_TAG$8,"Transaction failed with error: %s. Retrying: %s.",a.message,_),_?[3,4]:[2,{value:Promise.reject(a)}];case 4:return[2]}}))},u=this,_.label=1;case 1:return[5,o()];case 2:return"object"==typeof(a=_.sent())?[2,a.value]:[3,1];case 3:return[2]}}))}))},t.prototype.close=function(){this.db.close()},t}(),__PRIVATE_IterationController=function(){function t(t){this.Pd=t,this.Ad=!1,this.Rd=null}return Object.defineProperty(t.prototype,"xs",{get:function(){return this.Ad},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"Id",{get:function(){return this.Rd},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cursor",{set:function(t){this.Pd=t},enumerable:!0,configurable:!0}),t.prototype.done=function(){this.Ad=!0},t.prototype.Vd=function(t){this.Rd=t},t.prototype.delete=function(){return __PRIVATE_wrapRequest(this.Pd.delete())},t}(),__PRIVATE_SimpleDbTransaction=function(){function t(t){var e=this;this.transaction=t,this.aborted=!1,this.md=new __PRIVATE_Deferred,this.transaction.oncomplete=function(){e.md.resolve()},this.transaction.onabort=function(){t.error?e.md.reject(t.error):e.md.resolve()},this.transaction.onerror=function(t){var n=__PRIVATE_checkForAndReportiOSError(t.target.error);e.md.reject(n)}}return t.open=function(e,n,r){return new t(e.transaction(r,n))},Object.defineProperty(t.prototype,"Ed",{get:function(){return this.md.promise},enumerable:!0,configurable:!0}),t.prototype.abort=function(t){t&&this.md.reject(t),this.aborted||(debug(__PRIVATE_LOG_TAG$8,"Aborting transaction:",t?t.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())},t.prototype.store=function(t){var e=this.transaction.objectStore(t);return assert(!!e,"Object store not part of transaction: "+t),new __PRIVATE_SimpleDbStore(e)},t}(),__PRIVATE_SimpleDbStore=function(){function t(t){this.store=t}return t.prototype.put=function(t,e){var n;return void 0!==e?(debug(__PRIVATE_LOG_TAG$8,"PUT",this.store.name,t,e),n=this.store.put(e,t)):(debug(__PRIVATE_LOG_TAG$8,"PUT",this.store.name,"",t),n=this.store.put(t)),__PRIVATE_wrapRequest(n)},t.prototype.add=function(t){return debug(__PRIVATE_LOG_TAG$8,"ADD",this.store.name,t,t),__PRIVATE_wrapRequest(this.store.add(t))},t.prototype.get=function(t){var e=this;return __PRIVATE_wrapRequest(this.store.get(t)).next((function(n){return void 0===n&&(n=null),debug(__PRIVATE_LOG_TAG$8,"GET",e.store.name,t,n),n}))},t.prototype.delete=function(t){return debug(__PRIVATE_LOG_TAG$8,"DELETE",this.store.name,t),__PRIVATE_wrapRequest(this.store.delete(t))},t.prototype.count=function(){return debug(__PRIVATE_LOG_TAG$8,"COUNT",this.store.name),__PRIVATE_wrapRequest(this.store.count())},t.prototype.vd=function(t,e){var n=this.cursor(this.options(t,e)),r=[];return this.pd(n,(function(t,e){r.push(e)})).next((function(){return r}))},t.prototype.bd=function(t,e){debug(__PRIVATE_LOG_TAG$8,"DELETE ALL",this.store.name);var n=this.options(t,e);n.gd=!1;var r=this.cursor(n);return this.pd(r,(function(t,e,n){return n.delete()}))},t.prototype.wd=function(t,e){var n;e?n=t:(n={},e=t);var r=this.cursor(n);return this.pd(r,e)},t.prototype.yd=function(t){var e=this.cursor({});return new PersistencePromise((function(n,r){e.onerror=function(t){var e=__PRIVATE_checkForAndReportiOSError(t.target.error);r(e)},e.onsuccess=function(e){var r=e.target.result;r?t(r.primaryKey,r.value).next((function(t){t?r.continue():n()})):n()}}))},t.prototype.pd=function(t,e){var n=[];return new PersistencePromise((function(r,i){t.onerror=function(t){i(t.target.error)},t.onsuccess=function(t){var i=t.target.result;if(i){var s=new __PRIVATE_IterationController(i),o=e(i.primaryKey,i.value,s);if(o instanceof PersistencePromise){var u=o.catch((function(t){return s.done(),PersistencePromise.reject(t)}));n.push(u)}s.xs?r():null===s.Id?i.continue():i.continue(s.Id)}else r()}})).next((function(){return PersistencePromise.$s(n)}))},t.prototype.options=function(t,e){var n=void 0;return void 0!==t&&("string"==typeof t?n=t:(assert(void 0===e,"3rd argument must not be defined if 2nd is a range."),e=t)),{index:n,range:e}},t.prototype.cursor=function(t){var e="next";if(t.reverse&&(e="prev"),t.index){var n=this.store.index(t.index);return t.gd?n.openKeyCursor(t.range,e):n.openCursor(t.range,e)}return this.store.openCursor(t.range,e)},t}();function __PRIVATE_wrapRequest(t){return new PersistencePromise((function(e,n){t.onsuccess=function(t){var n=t.target.result;e(n)},t.onerror=function(t){var e=__PRIVATE_checkForAndReportiOSError(t.target.error);n(e)}}))}var __PRIVATE_reportedIOSError=!1;function __PRIVATE_checkForAndReportiOSError(t){var e=__PRIVATE_SimpleDb.ad(util.getUA());if(e>=12.2&&e<13){var n="An internal error was encountered in the Indexed Database server";if(t.message.indexOf(n)>=0){var r=new FirestoreError("internal","IOS_INDEXEDDB_BUG1: IndexedDb has thrown '"+n+"'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.");return __PRIVATE_reportedIOSError||(__PRIVATE_reportedIOSError=!0,setTimeout((function(){throw r}),0)),r}}return t}var __PRIVATE_IndexedDbMutationQueue=function(){function t(t,e,n,r){this.userId=t,this.serializer=e,this.co=n,this.oa=r,this.Sd={}}return t.Dd=function(e,n,r,i){return assert(""!==e.uid,"UserID must not be an empty string."),new t(e.R()?e.uid:"",n,r,i)},t.prototype.Cd=function(t){var e=!0,n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return __PRIVATE_mutationsStore(t).wd({index:DbMutationBatch.userMutationsIndex,range:n},(function(t,n,r){e=!1,r.done()})).next((function(){return e}))},t.prototype.ba=function(t,e,n){return this.Od(t).next((function(e){return e.lastStreamToken=__PRIVATE_convertStreamToken(n),__PRIVATE_mutationQueuesStore(t).put(e)}))},t.prototype.Na=function(t){return this.Od(t).next((function(t){return t.lastStreamToken}))},t.prototype.Ma=function(t,e){return this.Od(t).next((function(n){return n.lastStreamToken=__PRIVATE_convertStreamToken(e),__PRIVATE_mutationQueuesStore(t).put(n)}))},t.prototype.ma=function(t,e,n,r){var i=this,s=__PRIVATE_documentMutationsStore(t),o=__PRIVATE_mutationsStore(t);return o.add({}).next((function(u){assert("number"==typeof u,"Auto-generated key is not a number");for(var a=new __PRIVATE_MutationBatch(u,e,n,r),_=i.serializer.Fd(i.userId,a),c=[],h=new __PRIVATE_SortedSet((function(t,e){return __PRIVATE_primitiveComparator(t.ut(),e.ut())})),f=0,l=r;f=r,"Should have found mutation after "+r),s=n.serializer.Md(e)),i.done()})).next((function(){return s}))},t.prototype.Fa=function(t){var e=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]),n=__PRIVATE_BATCHID_UNKNOWN;return __PRIVATE_mutationsStore(t).wd({index:DbMutationBatch.userMutationsIndex,range:e,reverse:!0},(function(t,e,r){n=e.batchId,r.done()})).next((function(){return n}))},t.prototype.Pa=function(t){var e=this,n=IDBKeyRange.bound([this.userId,__PRIVATE_BATCHID_UNKNOWN],[this.userId,Number.POSITIVE_INFINITY]);return __PRIVATE_mutationsStore(t).vd(DbMutationBatch.userMutationsIndex,n).next((function(t){return t.map((function(t){return e.serializer.Md(t)}))}))},t.prototype.fo=function(t,e){var n=this,r=DbDocumentMutation.prefixForPath(this.userId,e.path),i=IDBKeyRange.lowerBound(r),s=[];return __PRIVATE_documentMutationsStore(t).wd({range:i},(function(r,i,o){var u=r[0],a=r[1],_=r[2],c=decode(a);if(u===n.userId&&e.path.isEqual(c))return __PRIVATE_mutationsStore(t).get(_).next((function(t){if(!t)throw fail("Dangling document-mutation reference found: "+r+" which points to "+_);assert(t.userId===n.userId,"Unexpected user '"+t.userId+"' for mutation batch "+_),s.push(n.serializer.Md(t))}));o.done()})).next((function(){return s}))},t.prototype.Po=function(t,e){var n=this,r=new __PRIVATE_SortedSet(__PRIVATE_primitiveComparator),i=[];return e.forEach((function(e){var s=DbDocumentMutation.prefixForPath(n.userId,e.path),o=IDBKeyRange.lowerBound(s),u=__PRIVATE_documentMutationsStore(t).wd({range:o},(function(t,i,s){var o=t[0],u=t[1],a=t[2],_=decode(u);o===n.userId&&e.path.isEqual(_)?r=r.add(a):s.done()}));i.push(u)})),PersistencePromise.$s(i).next((function(){return n.Ld(t,r)}))},t.prototype.vo=function(t,e){var n=this;assert(!e.Ze(),"Document queries shouldn't go down this path"),assert(!e.yn(),"CollectionGroup queries should be handled in LocalDocumentsView");var r=e.path,i=r.length+1,s=DbDocumentMutation.prefixForPath(this.userId,r),o=IDBKeyRange.lowerBound(s),u=new __PRIVATE_SortedSet(__PRIVATE_primitiveComparator);return __PRIVATE_documentMutationsStore(t).wd({range:o},(function(t,e,s){var o=t[0],a=t[1],_=t[2],c=decode(a);o===n.userId&&r.it(c)?c.length===i&&(u=u.add(_)):s.done()})).next((function(){return n.Ld(t,u)}))},t.prototype.Ld=function(t,e){var n=this,r=[],i=[];return e.forEach((function(e){i.push(__PRIVATE_mutationsStore(t).get(e).next((function(t){if(null===t)throw fail("Dangling document-mutation reference found, which points to "+e);assert(t.userId===n.userId,"Unexpected user '"+t.userId+"' for mutation batch "+e),r.push(n.serializer.Md(t))})))})),PersistencePromise.$s(i).next((function(){return r}))},t.prototype.Oa=function(t,e){var n=this;return __PRIVATE_removeMutationBatch(t.Gd,this.userId,e).next((function(r){return t.oo((function(){n.u_(e.batchId)})),PersistencePromise.forEach(r,(function(e){return n.oa.Bd(t,e)}))}))},t.prototype.u_=function(t){delete this.Sd[t]},t.prototype.Sa=function(t){var e=this;return this.Cd(t).next((function(n){if(!n)return PersistencePromise.resolve();var r=IDBKeyRange.lowerBound(DbDocumentMutation.prefixForUser(e.userId)),i=[];return __PRIVATE_documentMutationsStore(t).wd({range:r},(function(t,n,r){if(t[0]===e.userId){var s=decode(t[1]);i.push(s)}else r.done()})).next((function(){assert(0===i.length,"Document leak -- detected dangling mutation references when queue is empty. Dangling keys: "+i.map((function(t){return t.ut()})))}))}))},t.prototype.Gs=function(t,e){return __PRIVATE_mutationQueueContainsKey(t,this.userId,e)},t.prototype.Od=function(t){var e=this;return __PRIVATE_mutationQueuesStore(t).get(this.userId).next((function(t){return t||new DbMutationQueue(e.userId,__PRIVATE_BATCHID_UNKNOWN,"")}))},t}();function __PRIVATE_mutationQueueContainsKey(t,e,n){var r=DbDocumentMutation.prefixForPath(e,n.path),i=r[1],s=IDBKeyRange.lowerBound(r),o=!1;return __PRIVATE_documentMutationsStore(t).wd({range:s,gd:!0},(function(t,n,r){var s=t[0],u=t[1];t[2];s===e&&u===i&&(o=!0),r.done()})).next((function(){return o}))}function __PRIVATE_mutationQueuesContainKey(t,e){var n=!1;return __PRIVATE_mutationQueuesStore(t).yd((function(r){return __PRIVATE_mutationQueueContainsKey(t,r,e).next((function(t){return t&&(n=!0),PersistencePromise.resolve(!t)}))})).next((function(){return n}))}function __PRIVATE_removeMutationBatch(t,e,n){var r=t.store(DbMutationBatch.store),i=t.store(DbDocumentMutation.store),s=[],o=IDBKeyRange.only(n.batchId),u=0,a=r.wd({range:o},(function(t,e,n){return u++,n.delete()}));s.push(a.next((function(){assert(1===u,"Dangling document-mutation reference found: Missing batch "+n.batchId)})));for(var _=[],c=0,h=n.mutations;ci.highestListenSequenceNumber&&(i.highestListenSequenceNumber=e),r.xd(t,i)}))},t.prototype.Za=function(t,e){var n=this;return this.jd(t,e).next((function(){return n.kd(t).next((function(r){return r.targetCount+=1,n.qd(e,r),n.xd(t,r)}))}))},t.prototype.Ka=function(t,e){return this.jd(t,e)},t.prototype.Qd=function(t,e){var n=this;return this.Wd(t,e.targetId).next((function(){return __PRIVATE_targetsStore(t).delete(e.targetId)})).next((function(){return n.kd(t)})).next((function(e){return assert(e.targetCount>0,"Removing from an empty target cache"),e.targetCount-=1,n.xd(t,e)}))},t.prototype.Hu=function(t,e,n){var r=this,i=0,s=[];return __PRIVATE_targetsStore(t).wd((function(o,u){var a=r.serializer.$d(u);a.sequenceNumber<=e&&null===n.get(a.targetId)&&(i++,s.push(r.Qd(t,a)))})).next((function(){return PersistencePromise.$s(s)})).next((function(){return i}))},t.prototype.jr=function(t,e){var n=this;return __PRIVATE_targetsStore(t).wd((function(t,r){var i=n.serializer.$d(r);e(i)}))},t.prototype.kd=function(t){return __PRIVATE_retrieveMetadata(t.Gd)},t.prototype.xd=function(t,e){return __PRIVATE_globalTargetStore(t).put(DbTargetGlobal.key,e)},t.prototype.jd=function(t,e){return __PRIVATE_targetsStore(t).put(this.serializer.Yd(e))},t.prototype.qd=function(t,e){var n=!1;return t.targetId>e.highestTargetId&&(e.highestTargetId=t.targetId,n=!0),t.sequenceNumber>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=t.sequenceNumber,n=!0),n},t.prototype.Hd=function(t){return this.kd(t).next((function(t){return t.targetCount}))},t.prototype.za=function(t,e){var n=this,r=e.canonicalId(),i=IDBKeyRange.bound([r,Number.NEGATIVE_INFINITY],[r,Number.POSITIVE_INFINITY]),s=null;return __PRIVATE_targetsStore(t).wd({range:i,index:DbTarget.queryTargetsIndexName},(function(t,r,i){var o=n.serializer.$d(r);e.isEqual(o.target)&&(s=o,i.done())})).next((function(){return s}))},t.prototype.Ua=function(t,e,n){var r=this,i=[],s=__PRIVATE_documentTargetStore(t);return e.forEach((function(e){var o=encode(e.path);i.push(s.put(new DbTargetDocument(n,o))),i.push(r.oa.Ss(t,e))})),PersistencePromise.$s(i)},t.prototype.Ba=function(t,e,n){var r=this,i=__PRIVATE_documentTargetStore(t);return PersistencePromise.forEach(e,(function(e){var s=encode(e.path);return PersistencePromise.$s([i.delete([n,s]),r.oa.Cs(t,e)])}))},t.prototype.Wd=function(t,e){var n=__PRIVATE_documentTargetStore(t),r=IDBKeyRange.bound([e],[e+1],!1,!0);return n.delete(r)},t.prototype.n_=function(t,e){var n=IDBKeyRange.bound([e],[e+1],!1,!0),r=__PRIVATE_documentTargetStore(t),i=__PRIVATE_documentKeySet();return r.wd({range:n,gd:!0},(function(t,e,n){var r=decode(t[1]),s=new __PRIVATE_DocumentKey(r);i=i.add(s)})).next((function(){return i}))},t.prototype.Gs=function(t,e){var n=encode(e.path),r=IDBKeyRange.bound([n],[__PRIVATE_immediateSuccessor(n)],!1,!0),i=0;return __PRIVATE_documentTargetStore(t).wd({index:DbTargetDocument.documentTargetsIndex,gd:!0,range:r},(function(t,e,n){var r=t[0];t[1];0!==r&&(i++,n.done())})).next((function(){return i>0}))},t.prototype.ti=function(t,e){var n=this;return __PRIVATE_targetsStore(t).get(e).next((function(t){return t?n.serializer.$d(t):null}))},t}();function __PRIVATE_targetsStore(t){return __PRIVATE_IndexedDbPersistence.dd(t,DbTarget.store)}function __PRIVATE_globalTargetStore(t){return __PRIVATE_IndexedDbPersistence.dd(t,DbTargetGlobal.store)}function __PRIVATE_retrieveMetadata(t){return __PRIVATE_SimpleDb.dd(t,DbTargetGlobal.store).get(DbTargetGlobal.key).next((function(t){return assert(null!==t,"Missing metadata row."),t}))}function __PRIVATE_getHighestListenSequenceNumber(t){return __PRIVATE_retrieveMetadata(t).next((function(t){return t.highestListenSequenceNumber}))}function __PRIVATE_documentTargetStore(t){return __PRIVATE_IndexedDbPersistence.dd(t,DbTargetDocument.store)}var __PRIVATE_IndexedDbRemoteDocumentCache=function(){function t(t,e){this.serializer=t,this.co=e}return t.prototype.Js=function(t,e,n){return __PRIVATE_remoteDocumentsStore(t).put(__PRIVATE_dbKey(e),n)},t.prototype.to=function(t,e){var n=__PRIVATE_remoteDocumentsStore(t),r=__PRIVATE_dbKey(e);return n.delete(r)},t.prototype.updateMetadata=function(t,e){var n=this;return this.getMetadata(t).next((function(r){return r.byteSize+=e,n.Xd(t,r)}))},t.prototype.eo=function(t,e){var n=this;return __PRIVATE_remoteDocumentsStore(t).get(__PRIVATE_dbKey(e)).next((function(t){return n.zd(t)}))},t.prototype.Jd=function(t,e){var n=this;return __PRIVATE_remoteDocumentsStore(t).get(__PRIVATE_dbKey(e)).next((function(t){var e=n.zd(t);return e?{Zd:e,size:__PRIVATE_dbDocumentSize(t)}:null}))},t.prototype.getEntries=function(t,e){var n=this,r=__PRIVATE_nullableMaybeDocumentMap();return this.tT(t,e,(function(t,e){var i=n.zd(e);r=r.At(t,i)})).next((function(){return r}))},t.prototype.eT=function(t,e){var n=this,r=__PRIVATE_nullableMaybeDocumentMap(),i=new __PRIVATE_SortedMap(__PRIVATE_DocumentKey.X);return this.tT(t,e,(function(t,e){var s=n.zd(e);s?(r=r.At(t,s),i=i.At(t,__PRIVATE_dbDocumentSize(e))):(r=r.At(t,null),i=i.At(t,0))})).next((function(){return{nT:r,rT:i}}))},t.prototype.tT=function(t,e,n){if(e.et())return PersistencePromise.resolve();var r=IDBKeyRange.bound(e.first().path.ot(),e.last().path.ot()),i=e.gt(),s=i.Ot();return __PRIVATE_remoteDocumentsStore(t).wd({range:r},(function(t,e,r){for(var o=__PRIVATE_DocumentKey.Et(t);s&&__PRIVATE_DocumentKey.X(s,o)<0;)n(s,null),s=i.Ot();s&&s.isEqual(o)&&(n(s,e),s=i.Ft()?i.Ot():null),s?r.Vd(s.path.ot()):r.done()})).next((function(){for(;s;)n(s,null),s=i.Ft()?i.Ot():null}))},t.prototype.Ao=function(t,e,n){var r=this;assert(!e.yn(),"CollectionGroup queries should be handled in LocalDocumentsView");var i=__PRIVATE_documentMap(),s=e.path.length+1,o={};if(n.isEqual(__PRIVATE_SnapshotVersion.MIN)){var u=e.path.ot();o.range=IDBKeyRange.lowerBound(u)}else{var a=e.path.ot(),_=this.serializer.iT(n);o.range=IDBKeyRange.lowerBound([a,_],!0),o.index=DbRemoteDocument.collectionReadTimeIndex}return __PRIVATE_remoteDocumentsStore(t).wd(o,(function(t,n,o){if(t.length===s){var u=r.serializer.sT(n);e.path.it(u.key.path)?u instanceof Document&&e.matches(u)&&(i=i.At(u.key,u)):o.done()}})).next((function(){return i}))},t.prototype.c_=function(t,e){var n=this,r=__PRIVATE_maybeDocumentMap(),i=this.serializer.iT(e),s=__PRIVATE_remoteDocumentsStore(t),o=IDBKeyRange.lowerBound(i,!0);return s.wd({index:DbRemoteDocument.readTimeIndex,range:o},(function(t,e){var s=n.serializer.sT(e);r=r.At(s.key,s),i=e.readTime})).next((function(){return{h_:r,readTime:n.serializer.oT(i)}}))},t.prototype.f_=function(t){var e=this,n=__PRIVATE_remoteDocumentsStore(t),r=__PRIVATE_SnapshotVersion.MIN;return n.wd({index:DbRemoteDocument.readTimeIndex,reverse:!0},(function(t,n,i){n.readTime&&(r=e.serializer.oT(n.readTime)),i.done()})).next((function(){return r}))},t.prototype.ga=function(e){return new t.uT(this,!!e&&e.wa)},t.prototype.aT=function(t){return this.getMetadata(t).next((function(t){return t.byteSize}))},t.prototype.getMetadata=function(t){return __PRIVATE_documentGlobalStore(t).get(DbRemoteDocumentGlobal.key).next((function(t){return assert(!!t,"Missing document cache metadata"),t}))},t.prototype.Xd=function(t,e){return __PRIVATE_documentGlobalStore(t).put(DbRemoteDocumentGlobal.key,e)},t.prototype.zd=function(t){if(t){var e=this.serializer.sT(t);return e instanceof __PRIVATE_NoDocument&&e.version.isEqual(__PRIVATE_SnapshotVersion.W())?null:e}return null},t.uT=function(t){function e(e,n){var r=t.call(this)||this;return r._T=e,r.wa=n,r.cT=new __PRIVATE_ObjectMap((function(t){return t.toString()})),r}return tslib.__extends(e,t),e.prototype.io=function(t){var e=this,n=[],r=0,i=new __PRIVATE_SortedSet((function(t,e){return __PRIVATE_primitiveComparator(t.ut(),e.ut())}));return this.Hs.forEach((function(s,o){var u=e.cT.get(s);if(assert(void 0!==u,"Cannot modify a document that wasn't read (for "+s+")"),o){assert(!e.readTime.isEqual(__PRIVATE_SnapshotVersion.MIN),"Cannot add a document with a read time of zero");var a=e._T.serializer.hT(o,e.readTime);i=i.add(s.path.tt());var _=__PRIVATE_dbDocumentSize(a);r+=_-u,n.push(e._T.Js(t,s,a))}else if(r-=u,e.wa){var c=e._T.serializer.hT(new __PRIVATE_NoDocument(s,__PRIVATE_SnapshotVersion.W()),e.readTime);n.push(e._T.Js(t,s,c))}else n.push(e._T.to(t,s))})),i.forEach((function(r){n.push(e._T.co.Nd(t,r))})),n.push(this._T.updateMetadata(t,r)),PersistencePromise.$s(n)},e.prototype.no=function(t,e){var n=this;return this._T.Jd(t,e).next((function(t){return null===t?(n.cT.set(e,0),null):(n.cT.set(e,t.size),t.Zd)}))},e.prototype.ro=function(t,e){var n=this;return this._T.eT(t,e).next((function(t){var e=t.nT;return t.rT.forEach((function(t,e){n.cT.set(t,e)})),e}))},e}(__PRIVATE_RemoteDocumentChangeBuffer),t}();function __PRIVATE_documentGlobalStore(t){return __PRIVATE_IndexedDbPersistence.dd(t,DbRemoteDocumentGlobal.store)}function __PRIVATE_remoteDocumentsStore(t){return __PRIVATE_IndexedDbPersistence.dd(t,DbRemoteDocument.store)}function __PRIVATE_dbKey(t){return t.path.ot()}function __PRIVATE_dbDocumentSize(t){var e;if(t.document)e=t.document;else if(t.unknownDocument)e=t.unknownDocument;else{if(!t.noDocument)throw fail("Unknown remote document type");e=t.noDocument}return JSON.stringify(e).length}var __PRIVATE_MemoryIndexManager=function(){function t(){this.fT=new __PRIVATE_MemoryCollectionParentIndex}return t.prototype.Nd=function(t,e){return this.fT.add(e),PersistencePromise.resolve()},t.prototype.mo=function(t,e){return PersistencePromise.resolve(this.fT.getEntries(e))},t}(),__PRIVATE_MemoryCollectionParentIndex=function(){function t(){this.index={}}return t.prototype.add=function(t){assert(t.length%2==1,"Expected a collection path.");var e=t.rt(),n=t.tt(),r=this.index[e]||new __PRIVATE_SortedSet(ResourcePath.X),i=!r.has(n);return this.index[e]=r.add(n),i},t.prototype.has=function(t){var e=t.rt(),n=t.tt(),r=this.index[e];return r&&r.has(n)},t.prototype.getEntries=function(t){return(this.index[t]||new __PRIVATE_SortedSet(ResourcePath.X)).ot()},t}(),SCHEMA_VERSION=9,SchemaConverter=function(){function t(t){this.serializer=t}return t.prototype.createOrUpgrade=function(t,e,n,r){var i=this;assert(n=0&&r<=SCHEMA_VERSION,"Unexpected schema upgrade from v"+n+" to v{toVersion}.");var s=new __PRIVATE_SimpleDbTransaction(e);n<1&&r>=1&&(__PRIVATE_createPrimaryClientStore(t),__PRIVATE_createMutationQueue(t),__PRIVATE_createQueryCache(t),__PRIVATE_createRemoteDocumentCache(t));var o=PersistencePromise.resolve();return n<3&&r>=3&&(0!==n&&(__PRIVATE_dropQueryCache(t),__PRIVATE_createQueryCache(t)),o=o.next((function(){return __PRIVATE_writeEmptyTargetGlobalEntry(s)}))),n<4&&r>=4&&(0!==n&&(o=o.next((function(){return __PRIVATE_upgradeMutationBatchSchemaAndMigrateData(t,s)}))),o=o.next((function(){__PRIVATE_createClientMetadataStore(t)}))),n<5&&r>=5&&(o=o.next((function(){return i.removeAcknowledgedMutations(s)}))),n<6&&r>=6&&(o=o.next((function(){return __PRIVATE_createDocumentGlobalStore(t),i.addDocumentGlobal(s)}))),n<7&&r>=7&&(o=o.next((function(){return i.ensureSequenceNumbers(s)}))),n<8&&r>=8&&(o=o.next((function(){return i.createCollectionParentIndex(t,s)}))),n<9&&r>=9&&(o=o.next((function(){__PRIVATE_dropRemoteDocumentChangesStore(t),__PRIVATE_createRemoteDocumentReadTimeIndex(e)}))),o},t.prototype.addDocumentGlobal=function(t){var e=0;return t.store(DbRemoteDocument.store).wd((function(t,n){e+=__PRIVATE_dbDocumentSize(n)})).next((function(){var n=new DbRemoteDocumentGlobal(e);return t.store(DbRemoteDocumentGlobal.store).put(DbRemoteDocumentGlobal.key,n)}))},t.prototype.removeAcknowledgedMutations=function(t){var e=this,n=t.store(DbMutationQueue.store),r=t.store(DbMutationBatch.store);return n.vd().next((function(n){return PersistencePromise.forEach(n,(function(n){var i=IDBKeyRange.bound([n.userId,__PRIVATE_BATCHID_UNKNOWN],[n.userId,n.lastAcknowledgedBatchId]);return r.vd(DbMutationBatch.userMutationsIndex,i).next((function(r){return PersistencePromise.forEach(r,(function(r){assert(r.userId===n.userId,"Cannot process batch "+r.batchId+" from unexpected user");var i=e.serializer.Md(r);return __PRIVATE_removeMutationBatch(t,n.userId,i).next((function(){}))}))}))}))}))},t.prototype.ensureSequenceNumbers=function(t){var e=t.store(DbTargetDocument.store),n=t.store(DbRemoteDocument.store);return __PRIVATE_getHighestListenSequenceNumber(t).next((function(t){var r=[];return n.wd((function(n,i){var s=new ResourcePath(n),o=__PRIVATE_sentinelKey(s);r.push(e.get(o).next((function(n){return n?PersistencePromise.resolve():function(n){return e.put(new DbTargetDocument(0,encode(n),t))}(s)})))})).next((function(){return PersistencePromise.$s(r)}))}))},t.prototype.createCollectionParentIndex=function(t,e){t.createObjectStore(DbCollectionParent.store,{keyPath:DbCollectionParent.keyPath});var n=e.store(DbCollectionParent.store),r=new __PRIVATE_MemoryCollectionParentIndex,i=function(t){if(r.add(t)){var e=t.rt(),i=t.tt();return n.put({collectionId:e,parent:encode(i)})}};return e.store(DbRemoteDocument.store).wd({gd:!0},(function(t,e){var n=new ResourcePath(t);return i(n.tt())})).next((function(){return e.store(DbDocumentMutation.store).wd({gd:!0},(function(t,e){t[0];var n=t[1],r=(t[2],decode(n));return i(r.tt())}))}))},t}();function __PRIVATE_sentinelKey(t){return[0,encode(t)]}var DbTimestamp=function(t,e){this.seconds=t,this.nanoseconds=e},DbPrimaryClient=function(){function t(t,e,n){this.ownerId=t,this.allowTabSynchronization=e,this.leaseTimestampMs=n}return t.store="owner",t.key="owner",t}();function __PRIVATE_createPrimaryClientStore(t){t.createObjectStore(DbPrimaryClient.store)}var DbMutationQueue=function(){function t(t,e,n){this.userId=t,this.lastAcknowledgedBatchId=e,this.lastStreamToken=n}return t.store="mutationQueues",t.keyPath="userId",t}(),DbMutationBatch=function(){function t(t,e,n,r,i){this.userId=t,this.batchId=e,this.localWriteTimeMs=n,this.baseMutations=r,this.mutations=i}return t.store="mutations",t.keyPath="batchId",t.userMutationsIndex="userMutationsIndex",t.userMutationsKeyPath=["userId","batchId"],t}();function __PRIVATE_createMutationQueue(t){t.createObjectStore(DbMutationQueue.store,{keyPath:DbMutationQueue.keyPath}),t.createObjectStore(DbMutationBatch.store,{keyPath:DbMutationBatch.keyPath,autoIncrement:!0}).createIndex(DbMutationBatch.userMutationsIndex,DbMutationBatch.userMutationsKeyPath,{unique:!0}),t.createObjectStore(DbDocumentMutation.store)}function __PRIVATE_upgradeMutationBatchSchemaAndMigrateData(t,e){return e.store(DbMutationBatch.store).vd().next((function(n){t.deleteObjectStore(DbMutationBatch.store),t.createObjectStore(DbMutationBatch.store,{keyPath:DbMutationBatch.keyPath,autoIncrement:!0}).createIndex(DbMutationBatch.userMutationsIndex,DbMutationBatch.userMutationsKeyPath,{unique:!0});var r=e.store(DbMutationBatch.store),i=n.map((function(t){return r.put(t)}));return PersistencePromise.$s(i)}))}var DbDocumentMutation=function(){function t(){}return t.prefixForUser=function(t){return[t]},t.prefixForPath=function(t,e){return[t,encode(e)]},t.key=function(t,e,n){return[t,encode(e),n]},t.store="documentMutations",t.PLACEHOLDER=new t,t}();function __PRIVATE_createRemoteDocumentCache(t){t.createObjectStore(DbRemoteDocument.store)}var DbNoDocument=function(t,e){this.path=t,this.readTime=e},DbUnknownDocument=function(t,e){this.path=t,this.version=e},DbRemoteDocument=function(){function t(t,e,n,r,i,s){this.unknownDocument=t,this.noDocument=e,this.document=n,this.hasCommittedMutations=r,this.readTime=i,this.parentPath=s}return t.store="remoteDocuments",t.readTimeIndex="readTimeIndex",t.readTimeIndexPath="readTime",t.collectionReadTimeIndex="collectionReadTimeIndex",t.collectionReadTimeIndexPath=["parentPath","readTime"],t}(),DbRemoteDocumentGlobal=function(){function t(t){this.byteSize=t}return t.store="remoteDocumentGlobal",t.key="remoteDocumentGlobalKey",t}();function __PRIVATE_createDocumentGlobalStore(t){t.createObjectStore(DbRemoteDocumentGlobal.store)}var DbTarget=function(){function t(t,e,n,r,i,s,o){this.targetId=t,this.canonicalId=e,this.readTime=n,this.resumeToken=r,this.lastListenSequenceNumber=i,this.lastLimboFreeSnapshotVersion=s,this.query=o}return t.store="targets",t.keyPath="targetId",t.queryTargetsIndexName="queryTargetsIndex",t.queryTargetsKeyPath=["canonicalId","targetId"],t}(),DbTargetDocument=function(){function t(t,e,n){this.targetId=t,this.path=e,this.sequenceNumber=n,assert(0===t==(void 0!==n),"A target-document row must either have targetId == 0 and a defined sequence number, or a non-zero targetId and no sequence number")}return t.store="targetDocuments",t.keyPath=["targetId","path"],t.documentTargetsIndex="documentTargetsIndex",t.documentTargetsKeyPath=["path","targetId"],t}(),DbTargetGlobal=function(){function t(t,e,n,r){this.highestTargetId=t,this.highestListenSequenceNumber=e,this.lastRemoteSnapshotVersion=n,this.targetCount=r}return t.key="targetGlobalKey",t.store="targetGlobal",t}(),DbCollectionParent=function(){function t(t,e){this.collectionId=t,this.parent=e}return t.store="collectionParents",t.keyPath=["collectionId","parent"],t}();function __PRIVATE_createQueryCache(t){t.createObjectStore(DbTargetDocument.store,{keyPath:DbTargetDocument.keyPath}).createIndex(DbTargetDocument.documentTargetsIndex,DbTargetDocument.documentTargetsKeyPath,{unique:!0}),t.createObjectStore(DbTarget.store,{keyPath:DbTarget.keyPath}).createIndex(DbTarget.queryTargetsIndexName,DbTarget.queryTargetsKeyPath,{unique:!0}),t.createObjectStore(DbTargetGlobal.store)}function __PRIVATE_dropQueryCache(t){t.deleteObjectStore(DbTargetDocument.store),t.deleteObjectStore(DbTarget.store),t.deleteObjectStore(DbTargetGlobal.store)}function __PRIVATE_dropRemoteDocumentChangesStore(t){t.objectStoreNames.contains("remoteDocumentChanges")&&t.deleteObjectStore("remoteDocumentChanges")}function __PRIVATE_writeEmptyTargetGlobalEntry(t){var e=t.store(DbTargetGlobal.store),n=new DbTargetGlobal(0,0,__PRIVATE_SnapshotVersion.MIN.Y(),0);return e.put(DbTargetGlobal.key,n)}function __PRIVATE_createRemoteDocumentReadTimeIndex(t){var e=t.objectStore(DbRemoteDocument.store);e.createIndex(DbRemoteDocument.readTimeIndex,DbRemoteDocument.readTimeIndexPath,{unique:!1}),e.createIndex(DbRemoteDocument.collectionReadTimeIndex,DbRemoteDocument.collectionReadTimeIndexPath,{unique:!1})}var DbClientMetadata=function(){function t(t,e,n,r){this.clientId=t,this.updateTimeMs=e,this.networkEnabled=n,this.inForeground=r}return t.store="clientMetadata",t.keyPath="clientId",t}();function __PRIVATE_createClientMetadataStore(t){t.createObjectStore(DbClientMetadata.store,{keyPath:DbClientMetadata.keyPath})}var V1_STORES=[DbMutationQueue.store,DbMutationBatch.store,DbDocumentMutation.store,DbRemoteDocument.store,DbTarget.store,DbPrimaryClient.store,DbTargetGlobal.store,DbTargetDocument.store],V3_STORES=V1_STORES,V4_STORES=tslib.__spreadArrays(V3_STORES,[DbClientMetadata.store]),V6_STORES=tslib.__spreadArrays(V4_STORES,[DbRemoteDocumentGlobal.store]),V8_STORES=tslib.__spreadArrays(V6_STORES,[DbCollectionParent.store]),ALL_STORES=V8_STORES,__PRIVATE_IndexedDbIndexManager=function(){function t(){this.lT=new __PRIVATE_MemoryCollectionParentIndex}return t.prototype.Nd=function(t,e){var n=this;if(assert(e.length%2==1,"Expected a collection path."),!this.lT.has(e)){var r=e.rt(),i=e.tt();t.oo((function(){n.lT.add(e)}));var s={collectionId:r,parent:encode(i)};return __PRIVATE_collectionParentsStore(t).put(s)}return PersistencePromise.resolve()},t.prototype.mo=function(t,e){var n=[],r=IDBKeyRange.bound([e,""],[__PRIVATE_immediateSuccessor(e),""],!1,!0);return __PRIVATE_collectionParentsStore(t).vd(r).next((function(t){for(var r=0,i=t;rn)||(error("Detected an update time that is in the future: "+t+" > "+n),!1))},t.prototype.FT=function(){var t=this;null!==this.document&&"function"==typeof this.document.addEventListener&&(this.mT=function(){t.q_.Jo((function(){return t.inForeground="visible"===t.document.visibilityState,t.OT()}))},this.document.addEventListener("visibilitychange",this.mT),this.inForeground="visible"===this.document.visibilityState)},t.prototype.zT=function(){this.mT&&(assert(null!==this.document&&"function"==typeof this.document.addEventListener,"Expected 'document.addEventListener' to be a function"),this.document.removeEventListener("visibilitychange",this.mT),this.mT=null)},t.prototype.NT=function(){var t=this;"function"==typeof this.window.addEventListener&&(this.VT=function(){t.XT(),t.q_.Jo((function(){return t.gh()}))},this.window.addEventListener("unload",this.VT))},t.prototype.JT=function(){this.VT&&(assert("function"==typeof this.window.removeEventListener,"Expected 'window.removeEventListener' to be a function"),this.window.removeEventListener("unload",this.VT),this.VT=null)},t.prototype.HT=function(t){try{var e=null!==this.yT.getItem(this.YT(t));return debug(__PRIVATE_LOG_TAG$9,"Client '"+t+"' "+(e?"is":"is not")+" zombied in LocalStorage"),e}catch(t){return error(__PRIVATE_LOG_TAG$9,"Failed to get zombied client id.",t),!1}},t.prototype.XT=function(){try{this.yT.setItem(this.YT(this.clientId),String(Date.now()))}catch(t){error("Failed to set zombie client id.",t)}},t.prototype.ZT=function(){try{this.yT.removeItem(this.YT(this.clientId))}catch(t){}},t.prototype.YT=function(t){return __PRIVATE_ZOMBIED_CLIENTS_KEY_PREFIX+"_"+this.persistenceKey+"_"+t},t.wT="main",t}();function __PRIVATE_primaryClientStore(t){return t.store(DbPrimaryClient.store)}function __PRIVATE_clientMetadataStore(t){return t.store(DbClientMetadata.store)}var __PRIVATE_IndexedDbLruDelegate=function(){function t(t,e){this.db=t,this.nE=null,this.Lu=new __PRIVATE_LruGarbageCollector(this,e)}return t.prototype.Wu=function(t){var e=this.rE(t);return this.db.ha().Hd(t).next((function(t){return e.next((function(e){return t+e}))}))},t.prototype.rE=function(t){var e=0;return this.Yu(t,(function(t){e++})).next((function(){return e}))},t.prototype.jr=function(t,e){return this.db.ha().jr(t,e)},t.prototype.Yu=function(t,e){return this.iE(t,(function(t,n){return e(n)}))},t.prototype.sa=function(t){this.nE=t},t.prototype.Ss=function(t,e){return __PRIVATE_writeSentinelKey(t,e)},t.prototype.Cs=function(t,e){return __PRIVATE_writeSentinelKey(t,e)},t.prototype.Hu=function(t,e,n){return this.db.ha().Hu(t,e,n)},t.prototype.Bd=function(t,e){return __PRIVATE_writeSentinelKey(t,e)},t.prototype.sE=function(t,e){return this.nE.Gs(e)?PersistencePromise.resolve(!0):__PRIVATE_mutationQueuesContainKey(t,e)},t.prototype.Xu=function(t,e){var n=this,r=this.db._a().ga(),i=[],s=0;return this.iE(t,(function(o,u){if(u<=e){var a=n.sE(t,o).next((function(e){if(!e)return s++,r.eo(t,o).next((function(){return r.to(o),__PRIVATE_documentTargetStore(t).delete(__PRIVATE_sentinelKey$1(o))}))}));i.push(a)}})).next((function(){return PersistencePromise.$s(i)})).next((function(){return r.apply(t)})).next((function(){return s}))},t.prototype.removeTarget=function(t,e){var n=e.Gn(t.ka);return this.db.ha().Ka(t,n)},t.prototype.ja=function(t,e){return __PRIVATE_writeSentinelKey(t,e)},t.prototype.iE=function(t,e){var n,r=__PRIVATE_documentTargetStore(t),i=__PRIVATE_ListenSequence.Fo;return r.wd({index:DbTargetDocument.documentTargetsIndex},(function(t,r){var s=t[0],o=(t[1],r.path),u=r.sequenceNumber;0===s?(i!==__PRIVATE_ListenSequence.Fo&&e(new __PRIVATE_DocumentKey(decode(n)),i),i=u,n=o):i=__PRIVATE_ListenSequence.Fo})).next((function(){i!==__PRIVATE_ListenSequence.Fo&&e(new __PRIVATE_DocumentKey(decode(n)),i)}))},t.prototype.Ju=function(t){return this.db._a().aT(t)},t}();function __PRIVATE_sentinelKey$1(t){return[0,encode(t.path)]}function __PRIVATE_sentinelRow(t,e){return new DbTargetDocument(0,encode(t.path),e)}function __PRIVATE_writeSentinelKey(t,e){return __PRIVATE_documentTargetStore(t).put(__PRIVATE_sentinelRow(e,t.ka))}var __PRIVATE_IndexFreeQueryEngine=function(){function t(){}return t.prototype.da=function(t){this.oE=t},t.prototype.Ao=function(t,e,n,r){var i=this;return assert(void 0!==this.oE,"setLocalDocumentsView() not called"),e.An()?this.uE(t,e):n.isEqual(__PRIVATE_SnapshotVersion.MIN)?this.uE(t,e):this.oE.To(t,r).next((function(s){var o=i.aE(e,s);return(e.bn()||e.gn())&&i.tl(e.rn,o,r,n)?i.uE(t,e):(__PRIVATE_getLogLevel()<=LogLevel.DEBUG&&debug("IndexFreeQueryEngine","Re-using previous result from %s to execute query: %s",n.toString(),e.toString()),i.oE.Ao(t,e,n).next((function(t){return o.forEach((function(e){t=t.At(e.key,e)})),t})))}))},t.prototype.aE=function(t,e){var n=new __PRIVATE_SortedSet((function(e,n){return t.In(e,n)}));return e.forEach((function(e,r){r instanceof Document&&t.matches(r)&&(n=n.add(r))})),n},t.prototype.tl=function(t,e,n,r){if(n.size!==e.size)return!0;var i=t===__PRIVATE_LimitType.tn?e.last():e.first();return!!i&&(i.hasPendingWrites||i.version._(r)>0)},t.prototype.uE=function(t,e){return __PRIVATE_getLogLevel()<=LogLevel.DEBUG&&debug("IndexFreeQueryEngine","Using full collection scan to execute query: %s",e.toString()),this.oE.Ao(t,e,__PRIVATE_SnapshotVersion.MIN)},t}(),__PRIVATE_MemoryMutationQueue=function(){function t(t,e){this.co=t,this.oa=e,this._o=[],this._E=1,this.lastStreamToken=__PRIVATE_emptyByteString(),this.cE=new __PRIVATE_SortedSet(__PRIVATE_DocReference.$e)}return t.prototype.Cd=function(t){return PersistencePromise.resolve(0===this._o.length)},t.prototype.ba=function(t,e,n){var r=e.batchId,i=this.hE(r,"acknowledged");assert(0===i,"Can only acknowledge the first batch in the mutation queue");var s=this._o[i];return assert(r===s.batchId,"Queue ordering failure: expected batch "+r+", got batch "+s.batchId),this.lastStreamToken=n,PersistencePromise.resolve()},t.prototype.Na=function(t){return PersistencePromise.resolve(this.lastStreamToken)},t.prototype.Ma=function(t,e){return this.lastStreamToken=e,PersistencePromise.resolve()},t.prototype.ma=function(t,e,n,r){assert(0!==r.length,"Mutation batches should not be empty");var i=this._E;(this._E++,this._o.length>0)&&assert(this._o[this._o.length-1].batchIdi?this._o[i]:null)},t.prototype.Fa=function(){return PersistencePromise.resolve(0===this._o.length?__PRIVATE_BATCHID_UNKNOWN:this._E-1)},t.prototype.Pa=function(t){return PersistencePromise.resolve(this._o.slice())},t.prototype.fo=function(t,e){var n=this,r=new __PRIVATE_DocReference(e,0),i=new __PRIVATE_DocReference(e,Number.POSITIVE_INFINITY),s=[];return this.cE.Wt([r,i],(function(t){assert(e.isEqual(t.key),"Should only iterate over a single key's batches");var r=n.fE(t.Bs);assert(null!==r,"Batches in the index must exist in the main table"),s.push(r)})),PersistencePromise.resolve(s)},t.prototype.Po=function(t,e){var n=this,r=new __PRIVATE_SortedSet(__PRIVATE_primitiveComparator);return e.forEach((function(t){var e=new __PRIVATE_DocReference(t,0),i=new __PRIVATE_DocReference(t,Number.POSITIVE_INFINITY);n.cE.Wt([e,i],(function(e){assert(t.isEqual(e.key),"For each key, should only iterate over a single key's batches"),r=r.add(e.Bs)}))})),PersistencePromise.resolve(this.dE(r))},t.prototype.vo=function(t,e){assert(!e.yn(),"CollectionGroup queries should be handled in LocalDocumentsView");var n=e.path,r=n.length+1,i=n;__PRIVATE_DocumentKey.dt(i)||(i=i.child(""));var s=new __PRIVATE_DocReference(new __PRIVATE_DocumentKey(i),0),o=new __PRIVATE_SortedSet(__PRIVATE_primitiveComparator);return this.cE.$t((function(t){var e=t.key.path;return!!n.it(e)&&(e.length===r&&(o=o.add(t.Bs)),!0)}),s),PersistencePromise.resolve(this.dE(o))},t.prototype.dE=function(t){var e=this,n=[];return t.forEach((function(t){var r=e.fE(t);null!==r&&n.push(r)})),n},t.prototype.Oa=function(t,e){var n=this;assert(0===this.hE(e.batchId,"removed"),"Can only remove the first entry of the mutation queue"),this._o.shift();var r=this.cE;return PersistencePromise.forEach(e.mutations,(function(i){var s=new __PRIVATE_DocReference(i.key,e.batchId);return r=r.delete(s),n.oa.Bd(t,i.key)})).next((function(){n.cE=r}))},t.prototype.u_=function(t){},t.prototype.Gs=function(t,e){var n=new __PRIVATE_DocReference(e,0),r=this.cE.Yt(n);return PersistencePromise.resolve(e.isEqual(r&&r.key))},t.prototype.Sa=function(t){return 0===this._o.length&&assert(this.cE.et(),"Document leak -- detected dangling mutation references when queue is empty."),PersistencePromise.resolve()},t.prototype.hE=function(t,e){var n=this.lE(t);return assert(n>=0&&n=this._o.length)return null;var n=this._o[e];return assert(n.batchId===t,"If found batch must match"),n},t}();function __PRIVATE_documentEntryMap(){return new __PRIVATE_SortedMap(__PRIVATE_DocumentKey.X)}var __PRIVATE_MemoryRemoteDocumentCache=function(){function t(t,e){this.co=t,this.TE=e,this.docs=__PRIVATE_documentEntryMap(),this.size=0}return t.prototype.Js=function(t,e,n){assert(!n.isEqual(__PRIVATE_SnapshotVersion.MIN),"Cannot add a document with a read time of zero");var r=e.key,i=this.docs.get(r),s=i?i.size:0,o=this.TE(e);return this.docs=this.docs.At(r,{Zd:e,size:o,readTime:n}),this.size+=o-s,this.co.Nd(t,r.path.tt())},t.prototype.to=function(t){var e=this.docs.get(t);e&&(this.docs=this.docs.remove(t),this.size-=e.size)},t.prototype.eo=function(t,e){var n=this.docs.get(e);return PersistencePromise.resolve(n?n.Zd:null)},t.prototype.getEntries=function(t,e){var n=this,r=__PRIVATE_nullableMaybeDocumentMap();return e.forEach((function(t){var e=n.docs.get(t);r=r.At(t,e?e.Zd:null)})),PersistencePromise.resolve(r)},t.prototype.Ao=function(t,e,n){assert(!e.yn(),"CollectionGroup queries should be handled in LocalDocumentsView");for(var r=__PRIVATE_documentMap(),i=new __PRIVATE_DocumentKey(e.path.child("")),s=this.docs.wt(i);s.Ft();){var o=s.Ot(),u=o.key,a=o.value,_=a.Zd,c=a.readTime;if(!e.path.it(u.path))break;c._(n)<=0||_ instanceof Document&&e.matches(_)&&(r=r.At(_.key,_))}return PersistencePromise.resolve(r)},t.prototype.EE=function(t,e){return PersistencePromise.forEach(this.docs,(function(t){return e(t)}))},t.prototype.c_=function(t,e){throw new Error("getNewDocumentChanges() is not supported with MemoryPersistence")},t.prototype.f_=function(t){return PersistencePromise.resolve(__PRIVATE_SnapshotVersion.MIN)},t.prototype.ga=function(e){return new t.uT(this)},t.prototype.aT=function(t){return PersistencePromise.resolve(this.size)},t.uT=function(t){function e(e){var n=t.call(this)||this;return n._T=e,n}return tslib.__extends(e,t),e.prototype.io=function(t){var e=this,n=[];return this.Hs.forEach((function(r,i){i?n.push(e._T.Js(t,i,e.readTime)):e._T.to(r)})),PersistencePromise.$s(n)},e.prototype.no=function(t,e){return this._T.eo(t,e)},e.prototype.ro=function(t,e){return this._T.getEntries(t,e)},e}(__PRIVATE_RemoteDocumentChangeBuffer),t}(),__PRIVATE_MemoryTargetCache=function(){function t(t){this.persistence=t,this.PE=new __PRIVATE_ObjectMap((function(t){return t.canonicalId()})),this.lastRemoteSnapshotVersion=__PRIVATE_SnapshotVersion.MIN,this.highestTargetId=0,this.AE=0,this.RE=new __PRIVATE_ReferenceSet,this.targetCount=0,this.Ud=__PRIVATE_TargetIdGenerator.qf()}return t.prototype.jr=function(t,e){return this.PE.forEach((function(t,n){return e(n)})),PersistencePromise.resolve()},t.prototype.La=function(t){return PersistencePromise.resolve(this.lastRemoteSnapshotVersion)},t.prototype.Kd=function(t){return PersistencePromise.resolve(this.AE)},t.prototype.Ja=function(t){var e=this.Ud.after(this.highestTargetId);return this.highestTargetId=e,PersistencePromise.resolve(e)},t.prototype.qa=function(t,e,n){return n&&(this.lastRemoteSnapshotVersion=n),e>this.AE&&(this.AE=e),PersistencePromise.resolve()},t.prototype.jd=function(t){this.PE.set(t.target,t);var e=t.targetId;e>this.highestTargetId&&(this.highestTargetId=e),t.sequenceNumber>this.AE&&(this.AE=t.sequenceNumber)},t.prototype.Za=function(t,e){return assert(!this.PE.has(e.target),"Adding a target that already exists"),this.jd(e),this.targetCount+=1,PersistencePromise.resolve()},t.prototype.Ka=function(t,e){return assert(this.PE.has(e.target),"Updating a non-existent target"),this.jd(e),PersistencePromise.resolve()},t.prototype.Qd=function(t,e){return assert(this.targetCount>0,"Removing a target from an empty cache"),assert(this.PE.has(e.target),"Removing a non-existent target from the cache"),this.PE.delete(e.target),this.RE.Ns(e.targetId),this.targetCount-=1,PersistencePromise.resolve()},t.prototype.Hu=function(t,e,n){var r=this,i=0,s=[];return this.PE.forEach((function(o,u){u.sequenceNumber<=e&&null===n.get(u.targetId)&&(r.PE.delete(o),s.push(r.Wd(t,u.targetId)),i++)})),PersistencePromise.$s(s).next((function(){return i}))},t.prototype.Hd=function(t){return PersistencePromise.resolve(this.targetCount)},t.prototype.za=function(t,e){var n=this.PE.get(e)||null;return PersistencePromise.resolve(n)},t.prototype.ti=function(t,e){return fail("Not yet implemented.")},t.prototype.Ua=function(t,e,n){this.RE.Ds(e,n);var r=this.persistence.oa,i=[];return r&&e.forEach((function(e){i.push(r.Ss(t,e))})),PersistencePromise.$s(i)},t.prototype.Ba=function(t,e,n){this.RE.Fs(e,n);var r=this.persistence.oa,i=[];return r&&e.forEach((function(e){i.push(r.Cs(t,e))})),PersistencePromise.$s(i)},t.prototype.Wd=function(t,e){return this.RE.Ns(e),PersistencePromise.resolve()},t.prototype.n_=function(t,e){var n=this.RE.Ls(e);return PersistencePromise.resolve(n)},t.prototype.Gs=function(t,e){return PersistencePromise.resolve(this.RE.Gs(e))},t}(),__PRIVATE_LOG_TAG$a="MemoryPersistence",__PRIVATE_MemoryPersistence=function(){function t(t,e){var n=this;this.clientId=t,this.IE={},this.LT=new __PRIVATE_ListenSequence(0),this.IT=!1,this.IT=!0,this.oa=e(this),this.ca=new __PRIVATE_MemoryTargetCache(this);this.co=new __PRIVATE_MemoryIndexManager,this.ao=new __PRIVATE_MemoryRemoteDocumentCache(this.co,(function(t){return n.oa.VE(t)}))}return t.mE=function(e,n){return new t(e,(function(t){return new __PRIVATE_MemoryLruDelegate(t,n)}))},t.vE=function(e){return new t(e,(function(t){return new __PRIVATE_MemoryEagerDelegate(t)}))},t.prototype.gh=function(){return this.IT=!1,Promise.resolve()},Object.defineProperty(t.prototype,"Ku",{get:function(){return this.IT},enumerable:!0,configurable:!0}),t.prototype.s_=function(){return tslib.__awaiter(this,void 0,void 0,(function(){return tslib.__generator(this,(function(t){return[2,[this.clientId]]}))}))},t.prototype.GT=function(t){return t(!0)},t.prototype.BT=function(){},t.prototype.a_=function(t){},t.prototype.la=function(){return this.co},t.prototype.ua=function(t){var e=this.IE[t.I()];return e||(e=new __PRIVATE_MemoryMutationQueue(this.co,this.oa),this.IE[t.I()]=e),e},t.prototype.ha=function(){return this.ca},t.prototype._a=function(){return this.ao},t.prototype.runTransaction=function(t,e,n){var r=this;debug(__PRIVATE_LOG_TAG$a,"Starting transaction:",t);var i=new __PRIVATE_MemoryTransaction(this.LT.next());return this.oa.pE(),n(i).next((function(t){return r.oa.bE(i).next((function(){return t}))})).Qs().then((function(t){return i.uo(),t}))},t.prototype.gE=function(t,e){return PersistencePromise.Ys(values(this.IE).map((function(n){return function(){return n.Gs(t,e)}})))},t}(),__PRIVATE_MemoryTransaction=function(t){function e(e){var n=t.call(this)||this;return n.ka=e,n}return tslib.__extends(e,t),e}(__PRIVATE_PersistenceTransaction),__PRIVATE_MemoryEagerDelegate=function(){function t(t){this.persistence=t,this.nE=null,this.wE=null}return Object.defineProperty(t.prototype,"yE",{get:function(){if(this.wE)return this.wE;throw fail("orphanedDocuments is only valid during a transaction.")},enumerable:!0,configurable:!0}),t.prototype.sa=function(t){this.nE=t},t.prototype.Ss=function(t,e){return this.yE.delete(e),PersistencePromise.resolve()},t.prototype.Cs=function(t,e){return this.yE.add(e),PersistencePromise.resolve()},t.prototype.Bd=function(t,e){return this.yE.add(e),PersistencePromise.resolve()},t.prototype.removeTarget=function(t,e){var n=this,r=this.persistence.ha();return r.n_(t,e.targetId).next((function(t){t.forEach((function(t){return n.yE.add(t)}))})).next((function(){return r.Qd(t,e)}))},t.prototype.pE=function(){this.wE=new Set},t.prototype.bE=function(t){var e=this,n=this.persistence._a().ga();return PersistencePromise.forEach(this.yE,(function(r){return e.SE(t,r).next((function(t){t||n.to(r)}))})).next((function(){return e.wE=null,n.apply(t)}))},t.prototype.ja=function(t,e){var n=this;return this.SE(t,e).next((function(t){t?n.yE.delete(e):n.yE.add(e)}))},t.prototype.VE=function(t){return 0},t.prototype.SE=function(t,e){var n=this;return PersistencePromise.Ys([function(){return n.persistence.ha().Gs(t,e)},function(){return n.persistence.gE(t,e)},function(){return PersistencePromise.resolve(n.nE.Gs(e))}])},t}(),__PRIVATE_MemoryLruDelegate=function(){function t(t,e){this.persistence=t,this.nE=null,this.DE=new __PRIVATE_ObjectMap((function(t){return encode(t.path)})),this.Lu=new __PRIVATE_LruGarbageCollector(this,e)}return t.prototype.pE=function(){},t.prototype.bE=function(t){return PersistencePromise.resolve()},t.prototype.jr=function(t,e){return this.persistence.ha().jr(t,e)},t.prototype.Wu=function(t){var e=this.CE(t);return this.persistence.ha().Hd(t).next((function(t){return e.next((function(e){return t+e}))}))},t.prototype.CE=function(t){var e=0;return this.Yu(t,(function(t){e++})).next((function(){return e}))},t.prototype.Yu=function(t,e){var n=this;return PersistencePromise.forEach(this.DE,(function(r,i){return n.sE(t,r,i).next((function(t){return t?PersistencePromise.resolve():e(i)}))}))},t.prototype.sa=function(t){this.nE=t},t.prototype.Hu=function(t,e,n){return this.persistence.ha().Hu(t,e,n)},t.prototype.Xu=function(t,e){var n=this,r=0,i=this.persistence._a(),s=i.ga();return i.EE(t,(function(i){return n.sE(t,i,e).next((function(t){t||(r++,s.to(i))}))})).next((function(){return s.apply(t)})).next((function(){return r}))},t.prototype.Bd=function(t,e){return this.DE.set(e,t.ka),PersistencePromise.resolve()},t.prototype.removeTarget=function(t,e){var n=e.Gn(t.ka);return this.persistence.ha().Ka(t,n)},t.prototype.Ss=function(t,e){return this.DE.set(e,t.ka),PersistencePromise.resolve()},t.prototype.Cs=function(t,e){return this.DE.set(e,t.ka),PersistencePromise.resolve()},t.prototype.ja=function(t,e){return this.DE.set(e,t.ka),PersistencePromise.resolve()},t.prototype.VE=function(t){var e=t.key.toString().length;return t instanceof Document&&(e+=t.data().Ue()),e},t.prototype.sE=function(t,e,n){var r=this;return PersistencePromise.Ys([function(){return r.persistence.gE(t,e)},function(){return PersistencePromise.resolve(r.nE.Gs(e))},function(){return r.persistence.ha().Gs(t,e)},function(){var t=r.DE.get(e);return PersistencePromise.resolve(void 0!==t&&t>n)}])},t.prototype.Ju=function(t){return this.persistence._a().aT(t)},t}(),__PRIVATE_LOG_TAG$b="FirestoreClient",__PRIVATE_DOM_EXCEPTION_INVALID_STATE=11,__PRIVATE_DOM_EXCEPTION_ABORTED=20,__PRIVATE_DOM_EXCEPTION_QUOTA_EXCEEDED=22,__PRIVATE_IndexedDbPersistenceSettings=function(){function t(t,e){this.cacheSizeBytes=t,this.synchronizeTabs=e}return t.prototype.DT=function(){return __PRIVATE_LruParams.Su(this.cacheSizeBytes)},t}(),__PRIVATE_MemoryPersistenceSettings=function(){},__PRIVATE_FirestoreClient=function(){function t(t,e,n,r){this.platform=t,this.OE=e,this.credentials=n,this.jo=r,this.clientId=__PRIVATE_AutoId.s()}return t.prototype.start=function(t){var e=this;this.FE();var n=new __PRIVATE_Deferred,r=new __PRIVATE_Deferred,i=!1;return this.credentials.S((function(s){i?e.jo.Jo((function(){return e.qh(s)})):(i=!0,e.NE(t,r,s).then((function(t){return e.ME(s,t)})).then(n.resolve,n.reject))})),this.jo.Jo((function(){return n.promise})),r.promise},t.prototype.enableNetwork=function(){var t=this;return this.FE(),this.jo.enqueue((function(){return t.Dh.enableNetwork()}))},t.prototype.NE=function(t,e,n){var r=this;return t instanceof __PRIVATE_IndexedDbPersistenceSettings?this.LE(n,t).then((function(t){return e.resolve(),t})).catch((function(t){if(e.reject(t),!r.GE(t))throw t;return console.warn("Error enabling offline persistence. Falling back to persistence disabled: "+t),r.BE()})):(e.resolve(),this.BE())},t.prototype.GE=function(t){return t instanceof FirestoreError?t.code===Code.FAILED_PRECONDITION||t.code===Code.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||(t.code===__PRIVATE_DOM_EXCEPTION_QUOTA_EXCEEDED||t.code===__PRIVATE_DOM_EXCEPTION_ABORTED||t.code===__PRIVATE_DOM_EXCEPTION_INVALID_STATE)},t.prototype.FE=function(){if(this.jo.su)throw new FirestoreError(Code.FAILED_PRECONDITION,"The client has already been terminated.")},t.prototype.LE=function(t,e){var n=this,r=__PRIVATE_IndexedDbPersistence.eE(this.OE),i=new __PRIVATE_JsonProtoSerializer(this.OE.o,{ni:!0});return Promise.resolve().then((function(){return tslib.__awaiter(n,void 0,void 0,(function(){var n,s;return tslib.__generator(this,(function(o){switch(o.label){case 0:if(e.synchronizeTabs&&!__PRIVATE_WebStorageSharedClientState.ef(this.platform))throw new FirestoreError(Code.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");return n=e.DT(),this.El=e.synchronizeTabs?new __PRIVATE_WebStorageSharedClientState(this.jo,this.platform,r,this.clientId,t):new __PRIVATE_MemorySharedClientState,[4,__PRIVATE_IndexedDbPersistence.ST({allowTabSynchronization:e.synchronizeTabs,persistenceKey:r,clientId:this.clientId,platform:this.platform,q_:this.jo,serializer:i,DT:n,RT:this.El})];case 1:return s=o.sent(),this.persistence=s,[2,s.oa.Lu]}}))}))}))},t.prototype.BE=function(){return this.persistence=__PRIVATE_MemoryPersistence.vE(this.clientId),this.El=new __PRIVATE_MemorySharedClientState,Promise.resolve(null)},t.prototype.ME=function(t,e){var n=this;return debug(__PRIVATE_LOG_TAG$b,"Initializing. user=",t.uid),this.platform.UE(this.OE).then((function(r){return tslib.__awaiter(n,void 0,void 0,(function(){var n,i,s,o,u,a,_=this;return tslib.__generator(this,(function(c){switch(c.label){case 0:return n=new __PRIVATE_IndexFreeQueryEngine,this.Gu=new __PRIVATE_LocalStore(this.persistence,n,t),[4,this.Gu.start()];case 1:return c.sent(),e&&(this.kE=new __PRIVATE_LruScheduler(e,this.jo,this.Gu)),i=this.platform.xE(),s=this.platform.KE(this.OE.o),o=new __PRIVATE_Datastore(this.jo,r,this.credentials,s),u=function(t){return _.Dh.il(t,__PRIVATE_OnlineStateSource.P)},a=function(t){return _.Dh.il(t,__PRIVATE_OnlineStateSource.A)},this.al=new __PRIVATE_RemoteStore(this.Gu,o,this.jo,u,i),this.Dh=new __PRIVATE_SyncEngine(this.Gu,this.al,this.El,t),this.El.Hc=a,this.al.Dh=this.Dh,this.El.Dh=this.Dh,this.jE=new __PRIVATE_EventManager(this.Dh),[4,this.El.start()];case 2:return c.sent(),[4,this.al.start()];case 3:return c.sent(),[4,this.persistence.GT((function(t){return tslib.__awaiter(_,void 0,void 0,(function(){return tslib.__generator(this,(function(e){switch(e.label){case 0:return[4,this.Dh.Qh(t)];case 1:return e.sent(),this.kE&&(t&&!this.kE.Ku?this.kE.start():t||this.kE.stop()),[2]}}))}))}))];case 4:return c.sent(),[4,this.persistence.BT((function(){return tslib.__awaiter(_,void 0,void 0,(function(){return tslib.__generator(this,(function(t){switch(t.label){case 0:return[4,this.terminate()];case 1:return t.sent(),[2]}}))}))}))];case 5:return c.sent(),[2]}}))}))}))},t.prototype.qh=function(t){return this.jo.lu(),debug(__PRIVATE_LOG_TAG$b,"Credential Changed. Current user: "+t.uid),this.Dh.qh(t)},t.prototype.disableNetwork=function(){var t=this;return this.FE(),this.jo.enqueue((function(){return t.Dh.disableNetwork()}))},t.prototype.terminate=function(){var t=this;return this.jo.cu((function(){return tslib.__awaiter(t,void 0,void 0,(function(){return tslib.__generator(this,(function(t){switch(t.label){case 0:return this.kE&&this.kE.stop(),[4,this.al.gh()];case 1:return t.sent(),[4,this.El.gh()];case 2:return t.sent(),[4,this.persistence.gh()];case 3:return t.sent(),this.credentials.D(),[2]}}))}))}))},t.prototype.waitForPendingWrites=function(){var t=this;this.FE();var e=new __PRIVATE_Deferred;return this.jo.Jo((function(){return t.Dh.Gl(e)})),e.promise},t.prototype.listen=function(t,e,n){var r=this;this.FE();var i=new __PRIVATE_QueryListener(t,e,n);return this.jo.Jo((function(){return r.jE.listen(i)})),i},t.prototype.yh=function(t){var e=this;this.qE||this.jo.Jo((function(){return e.jE.yh(t)}))},t.prototype.QE=function(t){var e=this;return this.FE(),this.jo.enqueue((function(){return e.Gu.Ha(t)})).then((function(t){if(t instanceof Document)return t;if(t instanceof __PRIVATE_NoDocument)return null;throw new FirestoreError(Code.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)")}))},t.prototype.WE=function(t){var e=this;return this.FE(),this.jo.enqueue((function(){return tslib.__awaiter(e,void 0,void 0,(function(){var e,n,r;return tslib.__generator(this,(function(i){switch(i.label){case 0:return[4,this.Gu.e_(t,!0)];case 1:return e=i.sent(),n=new __PRIVATE_View(t,e.r_),r=n.zf(e.documents),[2,n.io(r,!1).snapshot]}}))}))}))},t.prototype.write=function(t){var e=this;this.FE();var n=new __PRIVATE_Deferred;return this.jo.Jo((function(){return e.Dh.write(t,n)})),n.promise},t.prototype.o=function(){return this.OE.o},t.prototype.Jl=function(t){var e=this;this.FE(),this.jo.Jo((function(){return e.jE.Jl(t),Promise.resolve()}))},t.prototype.Zl=function(t){this.qE||this.jE.Zl(t)},Object.defineProperty(t.prototype,"qE",{get:function(){return this.jo.su},enumerable:!0,configurable:!0}),t.prototype.transaction=function(t){var e=this;this.FE();var n=new __PRIVATE_Deferred;return this.jo.Jo((function(){return e.Dh.runTransaction(e.jo,t,n),Promise.resolve()})),n.promise},t}(),__PRIVATE_AsyncObserver=function(){function t(t){this.observer=t,this.muted=!1}return t.prototype.next=function(t){this.$E(this.observer.next,t)},t.prototype.error=function(t){this.$E(this.observer.error,t)},t.prototype.YE=function(){this.muted=!0},t.prototype.$E=function(t,e){var n=this;this.muted||setTimeout((function(){n.muted||t(e)}),0)},t}();function __PRIVATE_isPartialObserver(t){return __PRIVATE_implementsAnyMethods(t,["next","error","complete"])}function __PRIVATE_implementsAnyMethods(t,e){if("object"!=typeof t||null===t)return!1;for(var n=t,r=0,i=e;r=0)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid collection ID '"+t+"' passed to function Firestore.collectionGroup(). Collection IDs must not contain '/'.");return this.zE(),new Query$1(new Query(ResourcePath._t,t),this)},t.prototype.runTransaction=function(t){var e=this;return __PRIVATE_validateExactNumberOfArgs("Firestore.runTransaction",arguments,1),__PRIVATE_validateArgType("Firestore.runTransaction","function",1,t),this.zE().transaction((function(n){return t(new Transaction$1(e,n))}))},t.prototype.batch=function(){return this.zE(),new WriteBatch(this)},Object.defineProperty(t,"logLevel",{get:function(){switch(__PRIVATE_getLogLevel()){case LogLevel.DEBUG:return"debug";case LogLevel.ERROR:return"error";case LogLevel.SILENT:return"silent";default:return fail("Unknown log level: "+__PRIVATE_getLogLevel())}},enumerable:!0,configurable:!0}),t.setLogLevel=function(t){switch(__PRIVATE_validateExactNumberOfArgs("Firestore.setLogLevel",arguments,1),__PRIVATE_validateArgType("Firestore.setLogLevel","non-empty string",1,t),t){case"debug":setLogLevel(LogLevel.DEBUG);break;case"error":setLogLevel(LogLevel.ERROR);break;case"silent":setLogLevel(LogLevel.SILENT);break;default:throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid log level: "+t)}},t.prototype.fP=function(){return this.rP.timestampsInSnapshots},t}(),Transaction$1=function(){function t(t,e){this.lP=t,this.dP=e}return t.prototype.get=function(t){var e=this;__PRIVATE_validateExactNumberOfArgs("Transaction.get",arguments,1);var n=__PRIVATE_validateReference("Transaction.get",t,this.lP);return this.dP.Uc([n.cP]).then((function(t){if(!t||1!==t.length)return fail("Mismatch in docs returned from document lookup.");var r=t[0];if(r instanceof __PRIVATE_NoDocument)return new DocumentSnapshot(e.lP,n.cP,null,!1,!1,n.TP);if(r instanceof Document)return new DocumentSnapshot(e.lP,n.cP,r,!1,!1,n.TP);throw fail("BatchGetDocumentsRequest returned unexpected document type: "+r.constructor.name)}))},t.prototype.set=function(t,e,n){__PRIVATE_validateBetweenNumberOfArgs("Transaction.set",arguments,2,3);var r=__PRIVATE_validateReference("Transaction.set",t,this.lP);n=__PRIVATE_validateSetOptions("Transaction.set",n);var i=__PRIVATE_applyFirestoreDataConverter(r.TP,e,"Transaction.set"),s=i[0],o=i[1],u=n.merge||n.mergeFields?this.lP.iP.N_(o,s,n.mergeFields):this.lP.iP.O_(o,s);return this.dP.set(r.cP,u),this},t.prototype.update=function(t,e,n){for(var r,i,s=[],o=3;o0?[2,this.lP.zE().write(this.EP)]:[2]}))}))},t.prototype.AP=function(){if(this.PP)throw new FirestoreError(Code.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")},t}(),DocumentReference=function(){function t(t,e,n){this.cP=t,this.firestore=e,this.TP=n,this.JE=this.firestore.zE()}return t.hP=function(e,n,r){if(e.length%2!=0)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but "+e.ut()+" has "+e.length);return new t(new __PRIVATE_DocumentKey(e),n,r)},Object.defineProperty(t.prototype,"id",{get:function(){return this.cP.path.rt()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return new CollectionReference(this.cP.path.tt(),this.firestore,this.TP)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"path",{get:function(){return this.cP.path.ut()},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(__PRIVATE_validateExactNumberOfArgs("DocumentReference.collection",arguments,1),__PRIVATE_validateArgType("DocumentReference.collection","non-empty string",1,t),!t)throw new FirestoreError(Code.INVALID_ARGUMENT,"Must provide a non-empty collection name to collection()");var e=ResourcePath.at(t);return new CollectionReference(this.cP.path.child(e),this.firestore)},t.prototype.isEqual=function(e){if(!(e instanceof t))throw __PRIVATE_invalidClassError("isEqual","DocumentReference",1,e);return this.firestore===e.firestore&&this.cP.isEqual(e.cP)&&this.TP===e.TP},t.prototype.set=function(t,e){__PRIVATE_validateBetweenNumberOfArgs("DocumentReference.set",arguments,1,2),e=__PRIVATE_validateSetOptions("DocumentReference.set",e);var n=__PRIVATE_applyFirestoreDataConverter(this.TP,t,"DocumentReference.set"),r=n[0],i=n[1],s=e.merge||e.mergeFields?this.firestore.iP.N_(i,r,e.mergeFields):this.firestore.iP.O_(i,r);return this.JE.write(s.A_(this.cP,Precondition.NONE))},t.prototype.update=function(t,e){for(var n,r=[],i=2;i=",">","array-contains","in","array-contains-any"];__PRIVATE_validateStringEnum("Query.where",s,2,n);var o=__PRIVATE_fieldPathFromArgument("Query.where",e),u=__PRIVATE_Operator.at(n);if(o.ht()){if(u===__PRIVATE_Operator.ARRAY_CONTAINS||u===__PRIVATE_Operator.ARRAY_CONTAINS_ANY)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid Query. You can't perform '"+u.toString()+"' queries on FieldPath.documentId().");if(u===__PRIVATE_Operator.IN){this.yP(r,u);for(var a=[],_=0,c=r;_0)throw new FirestoreError(Code.INVALID_ARGUMENT,"Too many arguments provided to "+t+"().");var i=e;if(!i.exists)throw new FirestoreError(Code.NOT_FOUND,"Can't use a DocumentSnapshot that doesn't exist for "+t+"().");return this.FP(t,i.VP,r)}var s=[e].concat(n);return this.NP(t,s,r)},t.prototype.FP=function(t,e,n){for(var r=[],i=0,s=this.wP.orderBy;ir.length)throw new FirestoreError(Code.INVALID_ARGUMENT,"Too many arguments provided to "+t+"(). The number of arguments must be less than or equal to the number of Query.orderBy() clauses");for(var i=[],s=0;s10)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid Query. '"+e.toString()+"' filters support a maximum of 10 elements in the value array.");if(t.indexOf(null)>=0)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid Query. '"+e.toString()+"' filters cannot contain 'null' in the value array.");if(t.filter((function(t){return Number.isNaN(t)})).length>0)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid Query. '"+e.toString()+"' filters cannot contain 'NaN' in the value array.")},t.prototype.DP=function(t){if(t instanceof FieldFilter){var e=[__PRIVATE_Operator.ARRAY_CONTAINS,__PRIVATE_Operator.ARRAY_CONTAINS_ANY],n=[__PRIVATE_Operator.IN,__PRIVATE_Operator.ARRAY_CONTAINS_ANY],r=e.indexOf(t.op)>=0,i=n.indexOf(t.op)>=0;if(t.hn()){var s=this.wP.an();if(null!==s&&!s.isEqual(t.field))throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid query. All where filters with an inequality (<, <=, >, or >=) must be on the same field. But you have inequality filters on '"+s.toString()+"' and '"+t.field.toString()+"'");var o=this.wP._n();null!==o&&this.LP(t.field,o)}else if(i||r){var u=null;if(i&&(u=this.wP.wn(n)),null===u&&r&&(u=this.wP.wn(e)),null!=u)throw u===t.op?new FirestoreError(Code.INVALID_ARGUMENT,"Invalid query. You cannot use more than one '"+t.op.toString()+"' filter."):new FirestoreError(Code.INVALID_ARGUMENT,"Invalid query. You cannot use '"+t.op.toString()+"' filters with '"+u.toString()+"' filters.")}}},t.prototype.CP=function(t){if(null===this.wP._n()){var e=this.wP.an();null!==e&&this.LP(e,t.field)}},t.prototype.LP=function(t,e){if(!e.isEqual(t))throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid query. You have a where filter with an inequality (<, <=, >, or >=) on field '"+t.toString()+"' and so you must also use '"+t.toString()+"' as your first Query.orderBy(), but your first Query.orderBy() is on field '"+e.toString()+"' instead.")},t}(),QuerySnapshot=function(){function t(t,e,n,r){this.lP=t,this.GP=e,this.BP=n,this.TP=r,this.UP=null,this.kP=null,this.metadata=new SnapshotMetadata(n.hasPendingWrites,n.fromCache)}return Object.defineProperty(t.prototype,"docs",{get:function(){var t=[];return this.forEach((function(e){return t.push(e)})),t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"empty",{get:function(){return this.BP.docs.et()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"size",{get:function(){return this.BP.docs.size},enumerable:!0,configurable:!0}),t.prototype.forEach=function(t,e){var n=this;__PRIVATE_validateBetweenNumberOfArgs("QuerySnapshot.forEach",arguments,1,2),__PRIVATE_validateArgType("QuerySnapshot.forEach","function",1,t),this.BP.docs.forEach((function(r){t.call(e,n.xP(r))}))},Object.defineProperty(t.prototype,"query",{get:function(){return new Query$1(this.GP,this.lP,this.TP)},enumerable:!0,configurable:!0}),t.prototype.docChanges=function(t){t&&(__PRIVATE_validateOptionNames("QuerySnapshot.docChanges",t,["includeMetadataChanges"]),__PRIVATE_validateNamedOptionalType("QuerySnapshot.docChanges","boolean","includeMetadataChanges",t.includeMetadataChanges));var e=!(!t||!t.includeMetadataChanges);if(e&&this.BP.tr)throw new FirestoreError(Code.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this.UP&&this.kP===e||(this.UP=__PRIVATE_changesFromSnapshot(this.lP,e,this.BP,this.TP),this.kP=e),this.UP},t.prototype.isEqual=function(e){if(!(e instanceof t))throw __PRIVATE_invalidClassError("isEqual","QuerySnapshot",1,e);return this.lP===e.lP&&this.GP.isEqual(e.GP)&&this.BP.isEqual(e.BP)&&this.TP===e.TP},t.prototype.xP=function(t){return new QueryDocumentSnapshot(this.lP,t.key,t,this.metadata.fromCache,this.BP.Jn.has(t.key),this.TP)},t}();function __PRIVATE_throwDocChangesMethodError(){throw new FirestoreError(Code.INVALID_ARGUMENT,'QuerySnapshot.docChanges has been changed from a property into a method, so usages like "querySnapshot.docChanges" should become "querySnapshot.docChanges()"')}var __PRIVATE_docChangesPropertiesToOverride=tslib.__spreadArrays(["length","forEach","map"],"undefined"!=typeof Symbol?[Symbol.iterator]:[]);__PRIVATE_docChangesPropertiesToOverride.forEach((function(t){try{Object.defineProperty(QuerySnapshot.prototype.docChanges,t,{get:function(){return __PRIVATE_throwDocChangesMethodError()}})}catch(t){}}));var CollectionReference=function(t){function e(e,n,r){var i=t.call(this,Query.un(e),n,r)||this;if(i.KP=e,e.length%2!=1)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but "+e.ut()+" has "+e.length);return i}return tslib.__extends(e,t),Object.defineProperty(e.prototype,"id",{get:function(){return this.wP.path.rt()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){var t=this.wP.path.tt();return t.et()?null:new DocumentReference(new __PRIVATE_DocumentKey(t),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return this.wP.path.ut()},enumerable:!0,configurable:!0}),e.prototype.doc=function(t){if(__PRIVATE_validateBetweenNumberOfArgs("CollectionReference.doc",arguments,0,1),0===arguments.length&&(t=__PRIVATE_AutoId.s()),__PRIVATE_validateArgType("CollectionReference.doc","non-empty string",1,t),""===t)throw new FirestoreError(Code.INVALID_ARGUMENT,"Document path must be a non-empty string");var e=ResourcePath.at(t);return DocumentReference.hP(this.wP.path.child(e),this.firestore,this.TP)},e.prototype.add=function(t){__PRIVATE_validateExactNumberOfArgs("CollectionReference.add",arguments,1),__PRIVATE_validateArgType("CollectionReference.add","object",1,t);var e=this.doc();return e.set(t).then((function(){return e}))},e.prototype.withConverter=function(t){return new e(this.KP,this.firestore,t)},e}(Query$1);function __PRIVATE_validateSetOptions(t,e){if(void 0===e)return{merge:!1};if(__PRIVATE_validateOptionNames(t,e,["merge","mergeFields"]),__PRIVATE_validateNamedOptionalType(t,"boolean","merge",e.merge),__PRIVATE_validateOptionalArrayElements(t,"mergeFields","a string or a FieldPath",e.mergeFields,(function(t){return"string"==typeof t||t instanceof FieldPath$1})),void 0!==e.mergeFields&&void 0!==e.merge)throw new FirestoreError(Code.INVALID_ARGUMENT,"Invalid options passed to function "+t+'(): You cannot specify both "merge" and "mergeFields".');return e}function __PRIVATE_validateSnapshotOptions(t,e){return void 0===e?{}:(__PRIVATE_validateOptionNames(t,e,["serverTimestamps"]),__PRIVATE_validateNamedOptionalPropertyEquals(t,"options","serverTimestamps",e.serverTimestamps,["estimate","previous","none"]),e)}function __PRIVATE_validateGetOptions(t,e){__PRIVATE_validateOptionalArgType(t,"object",1,e),e&&(__PRIVATE_validateOptionNames(t,e,["source"]),__PRIVATE_validateNamedOptionalPropertyEquals(t,"options","source",e.source,["default","server","cache"]))}function __PRIVATE_validateReference(t,e,n){if(e instanceof DocumentReference){if(e.firestore!==n)throw new FirestoreError(Code.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}throw __PRIVATE_invalidClassError(t,"DocumentReference",1,e)}function __PRIVATE_changesFromSnapshot(t,e,n,r){if(n.zn.et()){var i,s=0;return n.docChanges.map((function(e){var o=new QueryDocumentSnapshot(t,e.doc.key,e.doc,n.fromCache,n.Jn.has(e.doc.key),r);return assert(e.type===__PRIVATE_ChangeType.jn,"Invalid event type for first snapshot"),assert(!i||n.query.In(i,e.doc)<0,"Got added events in wrong order"),i=e.doc,{type:"added",doc:o,oldIndex:-1,newIndex:s++}}))}var o=n.zn;return n.docChanges.filter((function(t){return e||t.type!==__PRIVATE_ChangeType.Wn})).map((function(e){var i=new QueryDocumentSnapshot(t,e.doc.key,e.doc,n.fromCache,n.Jn.has(e.doc.key),r),s=-1,u=-1;return e.type!==__PRIVATE_ChangeType.jn&&(assert((s=o.indexOf(e.doc.key))>=0,"Index for document not found"),o=o.delete(e.doc.key)),e.type!==__PRIVATE_ChangeType.qn&&(u=(o=o.add(e.doc)).indexOf(e.doc.key)),{type:__PRIVATE_resultChangeType(e.type),doc:i,oldIndex:s,newIndex:u}}))}function __PRIVATE_resultChangeType(t){switch(t){case __PRIVATE_ChangeType.jn:return"added";case __PRIVATE_ChangeType.Qn:case __PRIVATE_ChangeType.Wn:return"modified";case __PRIVATE_ChangeType.qn:return"removed";default:return fail("Unknown change type: "+t)}}function __PRIVATE_applyFirestoreDataConverter(t,e,n){var r;return t?(r=t.toFirestore(e),n="toFirestore() in "+n):r=e,[r,n]}var __PRIVATE_PublicFirestore=__PRIVATE_makeConstructorPrivate(Firestore,"Use firebase.firestore() instead."),__PRIVATE_PublicTransaction=__PRIVATE_makeConstructorPrivate(Transaction$1,"Use firebase.firestore().runTransaction() instead."),__PRIVATE_PublicWriteBatch=__PRIVATE_makeConstructorPrivate(WriteBatch,"Use firebase.firestore().batch() instead."),__PRIVATE_PublicDocumentReference=__PRIVATE_makeConstructorPrivate(DocumentReference,"Use firebase.firestore().doc() instead."),__PRIVATE_PublicDocumentSnapshot=__PRIVATE_makeConstructorPrivate(DocumentSnapshot),__PRIVATE_PublicQueryDocumentSnapshot=__PRIVATE_makeConstructorPrivate(QueryDocumentSnapshot),__PRIVATE_PublicQuery=__PRIVATE_makeConstructorPrivate(Query$1),__PRIVATE_PublicQuerySnapshot=__PRIVATE_makeConstructorPrivate(QuerySnapshot),__PRIVATE_PublicCollectionReference=__PRIVATE_makeConstructorPrivate(CollectionReference,"Use firebase.firestore().collection() instead."),__PRIVATE_firestoreNamespace={Firestore:__PRIVATE_PublicFirestore,GeoPoint:GeoPoint,Timestamp:Timestamp,Blob:__PRIVATE_PublicBlob,Transaction:__PRIVATE_PublicTransaction,WriteBatch:__PRIVATE_PublicWriteBatch,DocumentReference:__PRIVATE_PublicDocumentReference,DocumentSnapshot:__PRIVATE_PublicDocumentSnapshot,Query:__PRIVATE_PublicQuery,QueryDocumentSnapshot:__PRIVATE_PublicQueryDocumentSnapshot,QuerySnapshot:__PRIVATE_PublicQuerySnapshot,CollectionReference:__PRIVATE_PublicCollectionReference,FieldPath:FieldPath$1,FieldValue:__PRIVATE_PublicFieldValue,setLogLevel:Firestore.setLogLevel,CACHE_SIZE_UNLIMITED:CACHE_SIZE_UNLIMITED};function __PRIVATE_configureForFirebase(t){t.INTERNAL.registerComponent(new component.Component("firestore",(function(t){var e=t.getProvider("app").getImmediate();return new Firestore(e,t.getProvider("auth-internal"))}),"PUBLIC").setServiceProps(__PRIVATE_shallowCopy(__PRIVATE_firestoreNamespace)))}var __PRIVATE_NoopConnectivityMonitor=function(){function t(){}return t.prototype.ah=function(t){},t.prototype.gh=function(){},t}(),__PRIVATE_LOG_TAG$c="ConnectivityMonitor",__PRIVATE_BrowserConnectivityMonitor=function(){function t(){var t=this;this.jP=function(){return t.qP()},this.QP=function(){return t.WP()},this.$P=[],this.YP()}return t.prototype.ah=function(t){this.$P.push(t)},t.prototype.gh=function(){window.removeEventListener("online",this.jP),window.removeEventListener("offline",this.QP)},t.prototype.YP=function(){window.addEventListener("online",this.jP),window.addEventListener("offline",this.QP)},t.prototype.qP=function(){debug(__PRIVATE_LOG_TAG$c,"Network connectivity changed: AVAILABLE");for(var t=0,e=this.$P;t0){var r=u.getResponseJson().error;if(r&&r.status&&r.message){var i=__PRIVATE_mapCodeFromHttpResponseErrorStatus(r.status);o(new FirestoreError(i,r.message))}else o(new FirestoreError(Code.UNKNOWN,"Server responded with status "+u.getStatus()))}else debug(__PRIVATE_LOG_TAG$d,'RPC "'+t+'" failed'),o(new FirestoreError(Code.UNAVAILABLE,"Connection failed."));break;default:fail('RPC "'+t+'" failed with unanticipated webchannel error '+u.getLastErrorCode()+": "+u.getLastError()+", giving up.")}}finally{debug(__PRIVATE_LOG_TAG$d,'RPC "'+t+'" completed.')}}));var a=tslib.__assign({},e);delete a.database;var _=JSON.stringify(a);debug(__PRIVATE_LOG_TAG$d,"XHR sending: ",i+" "+_);var c={"Content-Type":"text/plain"};r.iA(c,n),u.send(i,"POST",_,c,__PRIVATE_XHR_TIMEOUT_SECS)}))},t.prototype.kc=function(t,e,n){return this.Bc(t,e,n)},t.prototype.gc=function(t,e){var n=[this.rA,"/",__PRIVATE_RPC_STREAM_SERVICE,"/",t,"/channel"],r=webchannelWrapper.createWebChannelTransport(),i={backgroundChannelTest:!0,httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:"projects/"+this.o.projectId+"/databases/"+this.o.database},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling};this.iA(i.initMessageHeaders,e),util.isReactNative()||util.isElectron()||util.isIE()||util.isUWP()||util.isBrowserExtension()||(i.httpHeadersOverwriteParam="$httpHeaders");var s=n.join("");debug(__PRIVATE_LOG_TAG$d,"Creating WebChannel: "+s+" "+i);var o=r.createWebChannel(s,i),u=!1,a=!1,_=new __PRIVATE_StreamBridge({HP:function(t){a?debug(__PRIVATE_LOG_TAG$d,"Not sending because WebChannel is closed:",t):(u||(debug(__PRIVATE_LOG_TAG$d,"Opening WebChannel transport."),o.open(),u=!0),debug(__PRIVATE_LOG_TAG$d,"WebChannel sending:",t),o.send(t))},XP:function(){return o.close()}}),c=function(t,e){o.listen(t,(function(t){try{e(t)}catch(t){setTimeout((function(){throw t}),0)}}))};return c(webchannelWrapper.WebChannel.EventType.OPEN,(function(){a||debug(__PRIVATE_LOG_TAG$d,"WebChannel transport opened.")})),c(webchannelWrapper.WebChannel.EventType.CLOSE,(function(){a||(a=!0,debug(__PRIVATE_LOG_TAG$d,"WebChannel transport closed"),_.eA())})),c(webchannelWrapper.WebChannel.EventType.ERROR,(function(t){a||(a=!0,debug(__PRIVATE_LOG_TAG$d,"WebChannel transport errored:",t),_.eA(new FirestoreError(Code.UNAVAILABLE,"The operation could not be completed")))})),c(webchannelWrapper.WebChannel.EventType.MESSAGE,(function(t){var e;if(!a){var n=t.data[0];assert(!!n,"Got a webchannel message without data.");var r=n,i=r.error||(null===(e=r[0])||void 0===e?void 0:e.error);if(i){debug(__PRIVATE_LOG_TAG$d,"WebChannel received error:",i);var s=i.status,u=__PRIVATE_mapCodeFromRpcStatus(s),c=i.message;void 0===u&&(u=Code.INTERNAL,c="Unknown error status: "+s+" with message "+i.message),a=!0,_.eA(new FirestoreError(u,c)),o.close()}else debug(__PRIVATE_LOG_TAG$d,"WebChannel received:",n),_.nA(n)}})),setTimeout((function(){_.tA()}),0),_},t.prototype.sA=function(t){var e=__PRIVATE_RPC_NAME_REST_MAPPING[t];return assert(void 0!==e,"Unknown REST mapping for: "+t),this.rA+"/"+__PRIVATE_RPC_URL_VERSION+"/projects/"+this.o.projectId+"/databases/"+this.o.database+"/documents:"+e},t}(),__PRIVATE_BrowserPlatform=function(){function t(){this.ei="",this.As="undefined"!=typeof atob}return Object.defineProperty(t.prototype,"document",{get:function(){return"undefined"!=typeof document?document:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"window",{get:function(){return"undefined"!=typeof window?window:null},enumerable:!0,configurable:!0}),t.prototype.UE=function(t){return Promise.resolve(new __PRIVATE_WebChannelConnection(t))},t.prototype.xE=function(){return __PRIVATE_BrowserConnectivityMonitor.ef()?new __PRIVATE_BrowserConnectivityMonitor:new __PRIVATE_NoopConnectivityMonitor},t.prototype.KE=function(t){return new __PRIVATE_JsonProtoSerializer(t,{ni:!0})},t.prototype.i=function(t){return JSON.stringify(t)},t.prototype.atob=function(t){return atob(t)},t.prototype.btoa=function(t){return btoa(t)},t}();__PRIVATE_PlatformSupport.Ps(new __PRIVATE_BrowserPlatform);var name="@firebase/firestore",version="1.10.0";function __PRIVATE_registerFirestore(t){__PRIVATE_configureForFirebase(t),t.registerVersion(name,version)}__PRIVATE_registerFirestore(firebase),exports.__PRIVATE_registerFirestore=__PRIVATE_registerFirestore; //# sourceMappingURL=index.cjs.min.js.map