/*! For license information please see LICENSES */ (window.webpackJsonp=window.webpackJsonp||[]).push([[6],{100:function(t,e,n){"use strict";var r={name:"NoSsr",functional:!0,props:{placeholder:String,placeholderTag:{type:String,default:"div"}},render:function(t,e){var n=e.parent,r=e.slots,o=e.props,c=r(),h=c.default;void 0===h&&(h=[]);var l=c.placeholder;return n._isMounted?h:(n.$once("hook:mounted",function(){n.$forceUpdate()}),o.placeholderTag&&(o.placeholder||l)?t(o.placeholderTag,{class:["no-ssr-placeholder"]},o.placeholder||l):h.length>0?h.map(function(){return t(!1)}):t(!1))}};t.exports=r},12:function(t,e,n){"use strict";var r,o=(r=n(28))&&"object"==typeof r&&"default"in r?r.default:r;t.exports=o},152:function(t,e,n){"use strict";t.exports=function(t,e){return"string"!=typeof t?t:(/^['"].*['"]$/.test(t)&&(t=t.slice(1,-1)),/["'() \t\n]/.test(t)||e?'"'+t.replace(/"/g,'\\"').replace(/\n/g,"\\n")+'"':t)}},163:function(t,e,n){"use strict";n(164)},164:function(t,e,n){"use strict";(function(t){Object.defineProperty(e,"__esModule",{value:!0});var r,o,c=(r=n(28))&&"object"==typeof r&&"default"in r?r.default:r,h=n(97),l=n(27),f=n(96),d=n(165),m=c.SDK_VERSION,y=new h.Logger("@firebase/firestore");function v(){return y.logLevel===h.LogLevel.DEBUG?o.DEBUG:y.logLevel===h.LogLevel.SILENT?o.SILENT:o.ERROR}function w(t){switch(t){case o.DEBUG:y.logLevel=h.LogLevel.DEBUG;break;case o.ERROR:y.logLevel=h.LogLevel.ERROR;break;case o.SILENT:y.logLevel=h.LogLevel.SILENT;break;default:y.error("Firestore ("+m+"): Invalid value passed to `setLogLevel`")}}function E(t,e){for(var n=[],r=2;rr)throw new N(A.INVALID_ARGUMENT,"Function "+t+"() requires between "+n+" and "+r+" arguments, but was called with "+et(e.length,"argument")+".")}function V(t,e,n,r){H(t,e,tt(n)+" argument",r)}function j(t,e,n,r){void 0!==r&&V(t,e,n,r)}function Q(t,e,n,r){H(t,e,n+" option",r)}function W(t,e,n,r){void 0!==r&&Q(t,e,n,r)}function K(t,e,n,r,o){void 0!==r&&function(t,e,n,r,o){if(!(r instanceof Array))throw new N(A.INVALID_ARGUMENT,"Function "+t+"() requires its "+e+" option to be an array, but it was: "+X(r));for(var i=0;i20&&(input=input.substring(0,20)+"..."),JSON.stringify(input);if("number"==typeof input||"boolean"==typeof input)return""+input;if("object"==typeof input){if(input instanceof Array)return"an array";var t=function(input){if(input.constructor){var t=/function\s+([^\s(]+)\s*\(/.exec(input.constructor.toString());if(t&&t.length>1)return t[1]}return null}(input);return t?"a custom "+t+" object":"an object"}return"function"==typeof input?"a function":T("Unknown wrong type: "+typeof input)}function J(t,e,n){if(void 0===n)throw new N(A.INVALID_ARGUMENT,"Function "+t+"() requires a valid "+tt(e)+" argument, but it was undefined.")}function $(t,e,n){P(e,function(e,r){if(n.indexOf(e)<0)throw new N(A.INVALID_ARGUMENT,"Unknown option '"+e+"' passed to function "+t+"(). Available options: "+n.join(", "))})}function Z(t,e,n,r){var o=X(r);return new N(A.INVALID_ARGUMENT,"Function "+t+"() requires its "+tt(n)+" argument to be a "+e+", but it was: "+o)}function tt(t){switch(t){case 1:return"first";case 2:return"second";case 3:return"third";default:return t+"th"}}function et(t,e){return t+" "+e+(1===t?"":"s")}var nt=function(){function t(){}return t.newId=function(){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e="",i=0;i<20;i++)e+=t.charAt(Math.floor(Math.random()*t.length));return I(20===e.length,"Invalid auto ID: "+e),e},t}();function it(t,e){return te?1:0}function ot(t,e){if(t.length!==e.length)return!1;for(var i=0;it.length&&T("offset "+e+" out of range "+t.length),void 0===n?n=t.length-e:n>t.length-e&&T("length "+n+" out of range "+(t.length-e)),this.segments=t,this.offset=e,this.len=n},t.prototype.construct=function(t,e,n){var path=Object.create(Object.getPrototypeOf(this));return path.init(t,e,n),path},Object.defineProperty(t.prototype,"length",{get:function(){return this.len},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(e){return 0===t.comparator(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)}):"string"==typeof e?n.push(e):T("Unknown parameter type for Path.child(): "+e),this.construct(n)},t.prototype.limit=function(){return this.offset+this.length},t.prototype.popFirst=function(t){return t=void 0===t?1:t,I(this.length>=t,"Can't call popFirst() with less segments"),this.construct(this.segments,this.offset+t,this.length-t)},t.prototype.popLast=function(){return I(!this.isEmpty(),"Can't call popLast() on empty path"),this.construct(this.segments,this.offset,this.length-1)},t.prototype.firstSegment=function(){return I(!this.isEmpty(),"Can't call firstSegment() on empty path"),this.segments[this.offset]},t.prototype.lastSegment=function(){return this.get(this.length-1)},t.prototype.get=function(t){return I(to)return 1}return t.lengthe.length?1:0},t}(),vt=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return l.__extends(e,t),e.prototype.canonicalString=function(){return this.toArray().join("/")},e.prototype.toString=function(){return this.canonicalString()},e.fromString=function(path){if(path.indexOf("//")>=0)throw new N(A.INVALID_ARGUMENT,"Invalid path ("+path+"). Paths must not contain // in them.");return new e(path.split("/").filter(function(t){return t.length>0}))},e.EMPTY_PATH=new e([]),e}(gt),bt=/^[_a-zA-Z][_a-zA-Z0-9]*$/,wt=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return l.__extends(e,t),e.isValidIdentifier=function(t){return bt.test(t)},e.prototype.canonicalString=function(){return this.toArray().map(function(t){return t=t.replace("\\","\\\\").replace("`","\\`"),e.isValidIdentifier(t)||(t="`"+t+"`"),t}).join(".")},e.prototype.toString=function(){return this.canonicalString()},e.prototype.isKeyField=function(){return 1===this.length&&"__name__"===this.get(0)},e.keyField=function(){return new e(["__name__"])},e.fromServerFormat=function(path){for(var t=[],n="",i=0,r=function(){if(0===n.length)throw new N(A.INVALID_ARGUMENT,"Invalid field path ("+path+"). Paths must not be empty, begin with '.', end with '.', or contain '..'");t.push(n),n=""},o=!1;i=2&&this.path.get(this.path.length-2)===t},t.prototype.isEqual=function(t){return null!==t&&0===vt.comparator(this.path,t.path)},t.prototype.toString=function(){return this.path.toString()},t.comparator=function(t,e){return vt.comparator(t.path,e.path)},t.isDocumentKey=function(path){return path.length%2==0},t.fromSegments=function(e){return new t(new vt(e.slice()))},t.fromPathString=function(path){return new t(vt.fromString(path))},t.EMPTY=new t(new vt([])),t}(),St=function(){var t=this;this.promise=new Promise(function(e,n){t.resolve=e,t.reject=n})};!function(t){t.All="all",t.ListenStreamIdle="listen_stream_idle",t.ListenStreamConnectionBackoff="listen_stream_connection_backoff",t.WriteStreamIdle="write_stream_idle",t.WriteStreamConnectionBackoff="write_stream_connection_backoff",t.OnlineStateTimeout="online_state_timeout",t.ClientMetadataRefresh="client_metadata_refresh",t.LruGarbageCollection="lru_garbage_collection"}(ct||(ct={}));var _t=function(){function t(t,e,n,r,o){this.asyncQueue=t,this.timerId=e,this.targetTimeMs=n,this.op=r,this.removalCallback=o,this.deferred=new St,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.catch=this.deferred.promise.catch.bind(this.deferred.promise),this.deferred.promise.catch(function(t){})}return t.createAndSchedule=function(e,n,r,o,c){var h=new t(e,n,Date.now()+r,o,c);return h.start(r),h},t.prototype.start=function(t){var e=this;this.timerHandle=setTimeout(function(){return e.handleDelayElapsed()},t)},t.prototype.skipDelay=function(){return this.handleDelayElapsed()},t.prototype.cancel=function(t){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new N(A.CANCELLED,"Operation cancelled"+(t?": "+t:""))))},t.prototype.handleDelayElapsed=function(){var t=this;this.asyncQueue.enqueueAndForget(function(){return null!==t.timerHandle?(t.clearTimeout(),t.op().then(function(e){return t.deferred.resolve(e)})):Promise.resolve()})},t.prototype.clearTimeout=function(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)},t}(),Tt=function(){function t(){this.tail=Promise.resolve(),this.delayedOperations=[],this.operationInProgress=!1}return t.prototype.enqueueAndForget=function(t){this.enqueue(t)},t.prototype.enqueue=function(t){var e=this;this.verifyNotFailed();var n=this.tail.then(function(){return e.operationInProgress=!0,t().catch(function(t){e.failure=t,e.operationInProgress=!1;var n=t.stack||t.message||"";throw S("INTERNAL UNHANDLED ERROR: ",n),n.indexOf("Firestore Test Simulated Error")<0&&setTimeout(function(){throw t},0),t}).then(function(t){return e.operationInProgress=!1,t})});return this.tail=n,n},t.prototype.enqueueAfterDelay=function(t,e,n){var r=this;this.verifyNotFailed(),I(e>=0,"Attempted to schedule an operation with a negative delay of "+e),I(!this.containsDelayedOperation(t),"Attempted to schedule multiple operations with timer id "+t+".");var o=_t.createAndSchedule(this,t,e,n,function(t){return r.removeDelayedOperation(t)});return this.delayedOperations.push(o),o},t.prototype.verifyNotFailed=function(){this.failure&&T("AsyncQueue is already failed: "+(this.failure.stack||this.failure.message))},t.prototype.verifyOperationInProgress=function(){I(this.operationInProgress,"verifyOpInProgress() called when no op in progress on this queue.")},t.prototype.drain=function(){return this.enqueue(function(){return Promise.resolve()})},t.prototype.containsDelayedOperation=function(t){for(var e=0,n=this.delayedOperations;e=0,"Delayed operation not found."),this.delayedOperations.splice(e,1)},t}(),It="",Ct="",Dt="",At="";function Nt(path){for(var t="",i=0;i0&&(t=kt(t)),t=Rt(path.get(i),t);return kt(t)}function Rt(t,e){for(var n=e,r=t.length,i=0;i=2,"Invalid path "+path),2===t)return I(path.charAt(0)===It&&path.charAt(1)===Ct,"Non-empty path "+path+" had length 2"),vt.EMPTY_PATH;for(var e=t-2,n=[],r="",o=0;oe)&&T('Invalid encoded resource path: "'+path+'"'),path.charAt(c+1)){case Ct:var h=path.substring(o,c),l=void 0;0===r.length?l=h:(l=r+=h,r=""),n.push(l);break;case Dt:r+=path.substring(o,c),r+="\0";break;case At:r+=path.substring(o,c+1);break;default:T('Invalid encoded resource path: "'+path+'"')}o=c+2}return new vt(n)}var Mt=function(){function t(t,e){if(this.seconds=t,this.nanoseconds=e,e<0)throw new N(A.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(e>=1e9)throw new N(A.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+e);if(t<-62135596800)throw new N(A.INVALID_ARGUMENT,"Timestamp seconds out of range: "+t);if(t>=253402300800)throw new N(A.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._compareTo=function(t){return this.seconds===t.seconds?it(this.nanoseconds,t.nanoseconds):it(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}(),Pt=function(){function t(t){this.timestamp=t}return t.fromMicroseconds=function(e){var n=Math.floor(e/1e6);return new t(new Mt(n,e%1e6*1e3))},t.fromTimestamp=function(e){return new t(e)},t.forDeletedDoc=function(){return t.MIN},t.prototype.compareTo=function(t){return this.timestamp._compareTo(t.timestamp)},t.prototype.isEqual=function(t){return this.timestamp.isEqual(t.timestamp)},t.prototype.toMicroseconds=function(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3},t.prototype.toString=function(){return"SnapshotVersion("+this.timestamp.toString()+")"},t.prototype.toTimestamp=function(){return this.timestamp},t.MIN=new t(new Mt(0,0)),t}(),Lt=function(){function t(t,e){this.comparator=t,this.root=e||Ut.EMPTY}return t.prototype.insert=function(e,n){return new t(this.comparator,this.root.insert(e,n,this.comparator).copy(null,null,Ut.BLACK,null,null))},t.prototype.remove=function(e){return new t(this.comparator,this.root.remove(e,this.comparator).copy(null,null,Ut.BLACK,null,null))},t.prototype.get=function(t){for(var e=this.root;!e.isEmpty();){var n=this.comparator(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.isEmpty();){var r=this.comparator(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.isEmpty=function(){return this.root.isEmpty()},Object.defineProperty(t.prototype,"size",{get:function(){return this.root.size},enumerable:!0,configurable:!0}),t.prototype.minKey=function(){return this.root.minKey()},t.prototype.maxKey=function(){return this.root.maxKey()},t.prototype.inorderTraversal=function(t){return this.root.inorderTraversal(t)},t.prototype.forEach=function(t){this.inorderTraversal(function(e,n){return t(e,n),!1})},t.prototype.toString=function(){var t=[];return this.inorderTraversal(function(e,n){return t.push(e+":"+n),!1}),"{"+t.join(", ")+"}"},t.prototype.reverseTraversal=function(t){return this.root.reverseTraversal(t)},t.prototype.getIterator=function(){return new xt(this.root,null,this.comparator,!1)},t.prototype.getIteratorFrom=function(t){return new xt(this.root,t,this.comparator,!1)},t.prototype.getReverseIterator=function(){return new xt(this.root,null,this.comparator,!0)},t.prototype.getReverseIteratorFrom=function(t){return new xt(this.root,t,this.comparator,!0)},t}(),xt=function(){function t(t,e,n,r){this.isReverse=r,this.nodeStack=[];for(var o=1;!t.isEmpty();)if(o=e?n(t.key,e):1,r&&(o*=-1),o<0)t=this.isReverse?t.left:t.right;else{if(0===o){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}return t.prototype.getNext=function(){I(this.nodeStack.length>0,"getNext() called on iterator when hasNext() is false.");var t=this.nodeStack.pop(),e={key:t.key,value:t.value};if(this.isReverse)for(t=t.left;!t.isEmpty();)this.nodeStack.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack.push(t),t=t.left;return e},t.prototype.hasNext=function(){return this.nodeStack.length>0},t.prototype.peek=function(){if(0===this.nodeStack.length)return null;var t=this.nodeStack[this.nodeStack.length-1];return{key:t.key,value:t.value}},t}(),Ut=function(){function t(e,n,r,o,c){this.key=e,this.value=n,this.color=null!=r?r:t.RED,this.left=null!=o?o:t.EMPTY,this.right=null!=c?c:t.EMPTY,this.size=this.left.size+1+this.right.size}return t.prototype.copy=function(e,n,r,o,c){return new t(null!=e?e:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=o?o:this.left,null!=c?c:this.right)},t.prototype.isEmpty=function(){return!1},t.prototype.inorderTraversal=function(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)},t.prototype.reverseTraversal=function(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)},t.prototype.min=function(){return this.left.isEmpty()?this:this.left.min()},t.prototype.minKey=function(){return this.min().key},t.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},t.prototype.insert=function(t,e,n){var r=this,o=n(t,r.key);return(r=o<0?r.copy(null,null,null,r.left.insert(t,e,n),null):0===o?r.copy(null,e,null,null,null):r.copy(null,null,null,null,r.right.insert(t,e,n))).fixUp()},t.prototype.removeMin=function(){if(this.left.isEmpty())return t.EMPTY;var e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),(e=e.copy(null,null,null,e.left.removeMin(),null)).fixUp()},t.prototype.remove=function(e,n){var r,o=this;if(n(e,o.key)<0)o.left.isEmpty()||o.left.isRed()||o.left.left.isRed()||(o=o.moveRedLeft()),o=o.copy(null,null,null,o.left.remove(e,n),null);else{if(o.left.isRed()&&(o=o.rotateRight()),o.right.isEmpty()||o.right.isRed()||o.right.left.isRed()||(o=o.moveRedRight()),0===n(e,o.key)){if(o.right.isEmpty())return t.EMPTY;r=o.right.min(),o=o.copy(r.key,r.value,null,null,o.right.removeMin())}o=o.copy(null,null,null,null,o.right.remove(e,n))}return o.fixUp()},t.prototype.isRed=function(){return this.color},t.prototype.fixUp=function(){var t=this;return t.right.isRed()&&!t.left.isRed()&&(t=t.rotateLeft()),t.left.isRed()&&t.left.left.isRed()&&(t=t.rotateRight()),t.left.isRed()&&t.right.isRed()&&(t=t.colorFlip()),t},t.prototype.moveRedLeft=function(){var t=this.colorFlip();return t.right.left.isRed()&&(t=(t=(t=t.copy(null,null,null,null,t.right.rotateRight())).rotateLeft()).colorFlip()),t},t.prototype.moveRedRight=function(){var t=this.colorFlip();return t.left.left.isRed()&&(t=(t=t.rotateRight()).colorFlip()),t},t.prototype.rotateLeft=function(){var e=this.copy(null,null,t.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)},t.prototype.rotateRight=function(){var e=this.copy(null,null,t.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)},t.prototype.colorFlip=function(){var t=this.left.copy(null,null,!this.left.color,null,null),e=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,e)},t.prototype.checkMaxDepth=function(){var t=this.check();return Math.pow(2,t)<=this.size+1},t.prototype.check=function(){if(this.isRed()&&this.left.isRed())throw T("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed())throw T("Right child of ("+this.key+","+this.value+") is red");var t=this.left.check();if(t!==this.right.check())throw T("Black depths differ");return t+(this.isRed()?0:1)},t.EMPTY=null,t.RED=!0,t.BLACK=!1,t}(),qt=function(){function t(){this.size=0}return t.prototype.copy=function(t,e,n,r,o){return this},t.prototype.insert=function(t,e,n){return new Ut(t,e)},t.prototype.remove=function(t,e){return this},t.prototype.isEmpty=function(){return!0},t.prototype.inorderTraversal=function(t){return!1},t.prototype.reverseTraversal=function(t){return!1},t.prototype.minKey=function(){return null},t.prototype.maxKey=function(){return null},t.prototype.isRed=function(){return!1},t.prototype.checkMaxDepth=function(){return!0},t.prototype.check=function(){return 0},t}();Ut.EMPTY=new qt;var Ft=function(){function t(t){this.comparator=t,this.data=new Lt(this.comparator)}return t.fromMapKeys=function(map){var e=new t(map.comparator);return map.forEach(function(t){e=e.add(t)}),e},t.prototype.has=function(t){return null!==this.data.get(t)},t.prototype.first=function(){return this.data.minKey()},t.prototype.last=function(){return this.data.maxKey()},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.inorderTraversal(function(e,n){return t(e),!1})},t.prototype.forEachInRange=function(t,e){for(var n=this.data.getIteratorFrom(t[0]);n.hasNext();){var r=n.getNext();if(this.comparator(r.key,t[1])>=0)return;e(r.key)}},t.prototype.forEachWhile=function(t,e){var n;for(n=void 0!==e?this.data.getIteratorFrom(e):this.data.getIterator();n.hasNext();){if(!t(n.getNext().key))return}},t.prototype.firstAfterOrEqual=function(t){var e=this.data.getIteratorFrom(t);return e.hasNext()?e.getNext().key:null},t.prototype.getIterator=function(){return new Bt(this.data.getIterator())},t.prototype.getIteratorFrom=function(t){return new Bt(this.data.getIteratorFrom(t))},t.prototype.add=function(t){return this.copy(this.data.remove(t).insert(t,!0))},t.prototype.delete=function(t){return this.has(t)?this.copy(this.data.remove(t)):this},t.prototype.isEmpty=function(){return this.data.isEmpty()},t.prototype.unionWith=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.getIterator(),r=e.data.getIterator();n.hasNext();){var o=n.getNext().key,c=r.getNext().key;if(0!==this.comparator(o,c))return!1}return!0},t.prototype.toArray=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.copy=function(data){var e=new t(this.comparator);return e.data=data,e},t}(),Bt=function(){function t(t){this.iter=t}return t.prototype.getNext=function(){return this.iter.getNext().key},t.prototype.hasNext=function(){return this.iter.hasNext()},t}(),Vt=new Lt(Et.comparator);function jt(){return Vt}function Qt(){return jt()}var Wt=new Lt(Et.comparator);function Kt(){return Wt}var Gt=new Lt(Et.comparator);function zt(){return Gt}var Ht=new Ft(Et.comparator);function Yt(){for(var t=[],e=0;e0,"Cannot create an empty mutation batch")}return t.prototype.applyToRemoteDocument=function(t,e,n){e&&I(e.key.isEqual(t),"applyToRemoteDocument: key "+t+" should match maybeDoc key\n "+e.key);var r=n.mutationResults;I(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=r,"Should have found mutation after "+r),c=n.serializer.fromDbMutationBatch(e)),o.done()}).next(function(){return c})},t.prototype.getAllMutationBatches=function(t){var e=this,n=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return oe(t).loadAll(Ke.userMutationsIndex,n).next(function(t){return t.map(function(t){return e.serializer.fromDbMutationBatch(t)})})},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=Ge.prefixForPath(this.userId,e.path),o=IDBKeyRange.lowerBound(r),c=[];return ae(t).iterate({range:o},function(r,o,h){var l=r[0],f=r[1],d=r[2],path=Ot(f);if(l===n.userId&&e.path.isEqual(path))return oe(t).get(d).next(function(t){if(!t)throw T("Dangling document-mutation reference found: "+r+" which points to "+d);I(t.userId===n.userId,"Unexpected user '"+t.userId+"' for mutation batch "+d),c.push(n.serializer.fromDbMutationBatch(t))});h.done()}).next(function(){return c})},t.prototype.getAllMutationBatchesAffectingDocumentKeys=function(t,e){var n=this,r=new Ft(it),o=[];return e.forEach(function(e){var c=Ge.prefixForPath(n.userId,e.path),h=IDBKeyRange.lowerBound(c),l=ae(t).iterate({range:h},function(t,o,c){var h=t[0],l=t[1],f=t[2],path=Ot(l);h===n.userId&&e.path.isEqual(path)?r=r.add(f):c.done()});o.push(l)}),te.waitFor(o).next(function(){return n.lookupMutationBatches(t,r)})},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=this;I(!e.isDocumentQuery(),"Document queries shouldn't go down this path"),I(!e.isCollectionGroupQuery(),"CollectionGroup queries should be handled in LocalDocumentsView");var r=e.path,o=r.length+1,c=Ge.prefixForPath(this.userId,r),h=IDBKeyRange.lowerBound(c),l=new Ft(it);return ae(t).iterate({range:h},function(t,e,c){var h=t[0],f=t[1],d=t[2],path=Ot(f);h===n.userId&&r.isPrefixOf(path)?path.length===o&&(l=l.add(d)):c.done()}).next(function(){return n.lookupMutationBatches(t,l)})},t.prototype.lookupMutationBatches=function(t,e){var n=this,r=[],o=[];return e.forEach(function(e){o.push(oe(t).get(e).next(function(t){if(null===t)throw T("Dangling document-mutation reference found, which points to "+e);I(t.userId===n.userId,"Unexpected user '"+t.userId+"' for mutation batch "+e),r.push(n.serializer.fromDbMutationBatch(t))}))}),te.waitFor(o).next(function(){return r})},t.prototype.removeMutationBatch=function(t,e){var n=this;return re(t.simpleDbTransaction,this.userId,e).next(function(r){return n.removeCachedMutationKeys(e.batchId),te.forEach(r,function(e){return n.referenceDelegate.removeMutationReference(t,e)})})},t.prototype.removeCachedMutationKeys=function(t){delete this.documentKeysByBatchId[t]},t.prototype.performConsistencyCheck=function(t){var e=this;return this.checkEmpty(t).next(function(n){if(!n)return te.resolve();var r=IDBKeyRange.lowerBound(Ge.prefixForUser(e.userId)),o=[];return ae(t).iterate({range:r},function(t,n,r){if(t[0]===e.userId){var path=Ot(t[1]);o.push(path)}else r.done()}).next(function(){I(0===o.length,"Document leak -- detected dangling mutation references when queue is empty. Dangling keys: "+o.map(function(p){return p.canonicalString()}))})})},t.prototype.containsKey=function(t,e){return ne(t,this.userId,e)},t.prototype.getMutationQueueMetadata=function(t){var e=this;return se(t).get(this.userId).next(function(t){return t||new We(e.userId,-1,"")})},t}();function ne(t,e,n){var r=Ge.prefixForPath(e,n.path),o=r[1],c=IDBKeyRange.lowerBound(r),h=!1;return ae(t).iterate({range:c,keysOnly:!0},function(t,n,r){var c=t[0],l=t[1];t[2];c===e&&l===o&&(h=!0),r.done()}).next(function(){return h})}function re(t,e,n){var r=t.store(Ke.store),o=t.store(Ge.store),c=[],h=IDBKeyRange.only(n.batchId),l=0,f=r.iterate({range:h},function(t,e,n){return l++,n.delete()});c.push(f.next(function(){I(1===l,"Dangling document-mutation reference found: Missing batch "+n.batchId)}));for(var d=[],m=0,y=n.mutations;m0||n.indexOf("Trident/")>0||n.indexOf("Edge/")>0||o||h)},e.getStore=function(t,e){return t.store(e)},e.getIOSVersion=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)},e.getAndroidVersion=function(t){var e=t.match(/Android ([\d.]+)/i),n=e?e[1].split(".").slice(0,2).join("."):"-1";return Number(n)},e.prototype.setVersionChangeListener=function(t){this.db.onversionchange=function(e){return t(e)}},e.prototype.runTransaction=function(t,e,n){var r=de.open(this.db,t,e),o=n(r).catch(function(t){return r.abort(t),te.reject(t)}).toPromise();return o.catch(function(){}),r.completionPromise.then(function(){return o})},e.prototype.close=function(){this.db.close()},e}(),pe=function(){function t(t){this.dbCursor=t,this.shouldStop=!1,this.nextKey=null}return Object.defineProperty(t.prototype,"isDone",{get:function(){return this.shouldStop},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skipToKey",{get:function(){return this.nextKey},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cursor",{set:function(t){this.dbCursor=t},enumerable:!0,configurable:!0}),t.prototype.done=function(){this.shouldStop=!0},t.prototype.skip=function(t){this.nextKey=t},t.prototype.delete=function(){return ye(this.dbCursor.delete())},t}(),de=function(){function t(t){var e=this;this.transaction=t,this.aborted=!1,this.completionDeferred=new St,this.transaction.oncomplete=function(){e.completionDeferred.resolve()},this.transaction.onabort=function(){t.error?e.completionDeferred.reject(t.error):e.completionDeferred.resolve()},this.transaction.onerror=function(t){var n=ve(t.target.error);e.completionDeferred.reject(n)}}return t.open=function(e,n,r){return new t(e.transaction(r,n))},Object.defineProperty(t.prototype,"completionPromise",{get:function(){return this.completionDeferred.promise},enumerable:!0,configurable:!0}),t.prototype.abort=function(t){t&&this.completionDeferred.reject(t),this.aborted||(E(le,"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 I(!!e,"Object store not part of transaction: "+t),new me(e)},t}(),me=function(){function t(t){this.store=t}return t.prototype.put=function(t,e){var n;return void 0!==e?(E(le,"PUT",this.store.name,t,e),n=this.store.put(e,t)):(E(le,"PUT",this.store.name,"",t),n=this.store.put(t)),ye(n)},t.prototype.add=function(t){return E(le,"ADD",this.store.name,t,t),ye(this.store.add(t))},t.prototype.get=function(t){var e=this;return ye(this.store.get(t)).next(function(n){return void 0===n&&(n=null),E(le,"GET",e.store.name,t,n),n})},t.prototype.delete=function(t){return E(le,"DELETE",this.store.name,t),ye(this.store.delete(t))},t.prototype.count=function(){return E(le,"COUNT",this.store.name),ye(this.store.count())},t.prototype.loadAll=function(t,e){var cursor=this.cursor(this.options(t,e)),n=[];return this.iterateCursor(cursor,function(t,e){n.push(e)}).next(function(){return n})},t.prototype.deleteAll=function(t,e){E(le,"DELETE ALL",this.store.name);var n=this.options(t,e);n.keysOnly=!1;var cursor=this.cursor(n);return this.iterateCursor(cursor,function(t,e,n){return n.delete()})},t.prototype.iterate=function(t,e){var n;e?n=t:(n={},e=t);var cursor=this.cursor(n);return this.iterateCursor(cursor,e)},t.prototype.iterateSerial=function(t){var e=this.cursor({});return new te(function(n,r){e.onerror=function(t){var e=ve(t.target.error);r(e)},e.onsuccess=function(e){var cursor=e.target.result;cursor?t(cursor.primaryKey,cursor.value).next(function(t){t?cursor.continue():n()}):n()}})},t.prototype.iterateCursor=function(t,e){var n=[];return new te(function(r,o){t.onerror=function(t){o(t.target.error)},t.onsuccess=function(t){var cursor=t.target.result;if(cursor){var o=new pe(cursor),c=e(cursor.primaryKey,cursor.value,o);if(c instanceof te){var h=c.catch(function(t){return o.done(),te.reject(t)});n.push(h)}o.isDone?r():null===o.skipToKey?cursor.continue():cursor.continue(o.skipToKey)}else r()}}).next(function(){return te.waitFor(n)})},t.prototype.options=function(t,e){var n=void 0;return void 0!==t&&("string"==typeof t?n=t:(I(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.keysOnly?n.openKeyCursor(t.range,e):n.openCursor(t.range,e)}return this.store.openCursor(t.range,e)},t}();function ye(t){return new te(function(e,n){t.onsuccess=function(t){var n=t.target.result;e(n)},t.onerror=function(t){var e=ve(t.target.error);n(e)}})}var ge=!1;function ve(t){var e=fe.getIOSVersion(f.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 N("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 ge||(ge=!0,setTimeout(function(){throw r},0)),r}}return t}var be=function(){function t(t,e){this.referenceDelegate=t,this.serializer=e,this.targetIdGenerator=he.forQueryCache()}return t.prototype.allocateTargetId=function(t){var e=this;return this.retrieveMetadata(t).next(function(n){return n.highestTargetId=e.targetIdGenerator.after(n.highestTargetId),e.saveMetadata(t,n).next(function(){return n.highestTargetId})})},t.prototype.getLastRemoteSnapshotVersion=function(t){return this.retrieveMetadata(t).next(function(t){return Pt.fromTimestamp(new Mt(t.lastRemoteSnapshotVersion.seconds,t.lastRemoteSnapshotVersion.nanoseconds))})},t.prototype.getHighestSequenceNumber=function(t){return Se(t.simpleDbTransaction)},t.prototype.setTargetsMetadata=function(t,e,n){var r=this;return this.retrieveMetadata(t).next(function(o){return o.highestListenSequenceNumber=e,n&&(o.lastRemoteSnapshotVersion=n.toTimestamp()),e>o.highestListenSequenceNumber&&(o.highestListenSequenceNumber=e),r.saveMetadata(t,o)})},t.prototype.addQueryData=function(t,e){var n=this;return this.saveQueryData(t,e).next(function(){return n.retrieveMetadata(t).next(function(r){return r.targetCount+=1,n.updateMetadataFromQueryData(e,r),n.saveMetadata(t,r)})})},t.prototype.updateQueryData=function(t,e){return this.saveQueryData(t,e)},t.prototype.removeQueryData=function(t,e){var n=this;return this.removeMatchingKeysForTargetId(t,e.targetId).next(function(){return we(t).delete(e.targetId)}).next(function(){return n.retrieveMetadata(t)}).next(function(e){return I(e.targetCount>0,"Removing from an empty query cache"),e.targetCount-=1,n.saveMetadata(t,e)})},t.prototype.removeTargets=function(t,e,n){var r=this,o=0,c=[];return we(t).iterate(function(h,l){var f=r.serializer.fromDbTarget(l);f.sequenceNumber<=e&&void 0===n[f.targetId]&&(o++,c.push(r.removeQueryData(t,f)))}).next(function(){return te.waitFor(c)}).next(function(){return o})},t.prototype.forEachTarget=function(t,e){var n=this;return we(t).iterate(function(t,r){var o=n.serializer.fromDbTarget(r);e(o)})},t.prototype.retrieveMetadata=function(t){return Ee(t.simpleDbTransaction)},t.prototype.saveMetadata=function(t,e){return(n=t,Sn.getStore(n,Ze.store)).put(Ze.key,e);var n},t.prototype.saveQueryData=function(t,e){return we(t).put(this.serializer.toDbTarget(e))},t.prototype.updateMetadataFromQueryData=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.getQueryCount=function(t){return this.retrieveMetadata(t).next(function(t){return t.targetCount})},t.prototype.getQueryData=function(t,e){var n=this,r=e.canonicalId(),o=IDBKeyRange.bound([r,Number.NEGATIVE_INFINITY],[r,Number.POSITIVE_INFINITY]),c=null;return we(t).iterate({range:o,index:Je.queryTargetsIndexName},function(t,r,o){var h=n.serializer.fromDbTarget(r);e.isEqual(h.query)&&(c=h,o.done())}).next(function(){return c})},t.prototype.addMatchingKeys=function(t,e,n){var r=this,o=[],c=_e(t);return e.forEach(function(e){var path=Nt(e.path);o.push(c.put(new $e(n,path))),o.push(r.referenceDelegate.addReference(t,e))}),te.waitFor(o)},t.prototype.removeMatchingKeys=function(t,e,n){var r=this,o=_e(t);return te.forEach(e,function(e){var path=Nt(e.path);return te.waitFor([o.delete([n,path]),r.referenceDelegate.removeReference(t,e)])})},t.prototype.removeMatchingKeysForTargetId=function(t,e){var n=_e(t),r=IDBKeyRange.bound([e],[e+1],!1,!0);return n.delete(r)},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=IDBKeyRange.bound([e],[e+1],!1,!0),r=_e(t),o=Yt();return r.iterate({range:n,keysOnly:!0},function(t,e,n){var path=Ot(t[1]),r=new Et(path);o=o.add(r)}).next(function(){return o})},t.prototype.containsKey=function(t,e){var path=Nt(e.path),n=IDBKeyRange.bound([path],[at(path)],!1,!0),r=0;return _e(t).iterate({index:$e.documentTargetsIndex,keysOnly:!0,range:n},function(t,e,n){var o=t[0];t[1];0!==o&&(r++,n.done())}).next(function(){return r>0})},t.prototype.getQueryDataForTarget=function(t,e){var n=this;return we(t).get(e).next(function(t){return t?n.serializer.fromDbTarget(t):null})},t}();function we(t){return Sn.getStore(t,Je.store)}function Ee(t){return fe.getStore(t,Ze.store).get(Ze.key).next(function(t){return I(null!==t,"Missing metadata row."),t})}function Se(t){return Ee(t).next(function(t){return t.highestListenSequenceNumber})}function _e(t){return Sn.getStore(t,$e.store)}var Te=function(){function t(t,e){this.key=t,this.version=e}return t.compareByKey=function(t,e){return Et.comparator(t.key,e.key)},t}(),Ie=function(t){function e(e,n,data,r,o){var c=t.call(this,e,n)||this;return c.data=data,c.proto=o,c.hasLocalMutations=!!r.hasLocalMutations,c.hasCommittedMutations=!!r.hasCommittedMutations,c}return l.__extends(e,t),e.prototype.field=function(path){return this.data.field(path)},e.prototype.fieldValue=function(path){var t=this.field(path);return t?t.value():void 0},e.prototype.value=function(){return this.data.value()},e.prototype.isEqual=function(t){return t instanceof e&&this.key.isEqual(t.key)&&this.version.isEqual(t.version)&&this.data.isEqual(t.data)&&this.hasLocalMutations===t.hasLocalMutations&&this.hasCommittedMutations===t.hasCommittedMutations},e.prototype.toString=function(){return"Document("+this.key+", "+this.version+", "+this.data.toString()+", {hasLocalMutations: "+this.hasLocalMutations+"}), {hasCommittedMutations: "+this.hasCommittedMutations+"})"},Object.defineProperty(e.prototype,"hasPendingWrites",{get:function(){return this.hasLocalMutations||this.hasCommittedMutations},enumerable:!0,configurable:!0}),e.compareByField=function(t,e,n){var r=e.field(t),o=n.field(t);return void 0!==r&&void 0!==o?r.compareTo(o):T("Trying to compare documents on fields that don't exist")},e}(Te),Ce=function(t){function e(e,n,r){var o=t.call(this,e,n)||this;return o.hasCommittedMutations=!(!r||!r.hasCommittedMutations),o}return l.__extends(e,t),e.prototype.toString=function(){return"NoDocument("+this.key+", "+this.version+")"},Object.defineProperty(e.prototype,"hasPendingWrites",{get:function(){return this.hasCommittedMutations},enumerable:!0,configurable:!0}),e.prototype.isEqual=function(t){return t instanceof e&&t.hasCommittedMutations===this.hasCommittedMutations&&t.version.isEqual(this.version)&&t.key.isEqual(this.key)},e}(Te),De=function(t){function e(e,n){return t.call(this,e,n)||this}return l.__extends(e,t),e.prototype.toString=function(){return"UnknownDocument("+this.key+", "+this.version+")"},Object.defineProperty(e.prototype,"hasPendingWrites",{get:function(){return!0},enumerable:!0,configurable:!0}),e.prototype.isEqual=function(t){return t instanceof e&&t.version.isEqual(this.version)&&t.key.isEqual(this.key)},e}(Te),Ae=function(){function t(t){this.mapKeyFn=t,this.inner={}}return t.prototype.get=function(t){var e=this.mapKeyFn(t),n=this.inner[e];if(void 0!==n)for(var r=0,o=n;r0){for(var o=Pe(t),c=Yt(),h=0,l=e;h=0&&r<=Be,"Unexpected schema upgrade from v"+n+" to v{toVersion}."),n<1&&r>=1&&(function(t){t.createObjectStore(Qe.store)}(t),function(t){t.createObjectStore(We.store,{keyPath:We.keyPath}),t.createObjectStore(Ke.store,{keyPath:Ke.keyPath,autoIncrement:!0}).createIndex(Ke.userMutationsIndex,Ke.userMutationsKeyPath,{unique:!0}),t.createObjectStore(Ge.store)}(t),en(t),function(t){t.createObjectStore(Ye.store)}(t));var p=te.resolve();return n<3&&r>=3&&(0!==n&&(!function(t){t.deleteObjectStore($e.store),t.deleteObjectStore(Je.store),t.deleteObjectStore(Ze.store)}(t),en(t)),p=p.next(function(){return function(t){var e=t.store(Ze.store),n=new Ze(0,0,Pt.MIN.toTimestamp(),0);return e.put(Ze.key,n)}(e)})),n<4&&r>=4&&(0!==n&&(p=p.next(function(){return function(t,e){return e.store(Ke.store).loadAll().next(function(n){t.deleteObjectStore(Ke.store);var r=t.createObjectStore(Ke.store,{keyPath:Ke.keyPath,autoIncrement:!0});r.createIndex(Ke.userMutationsIndex,Ke.userMutationsKeyPath,{unique:!0});var o=e.store(Ke.store),c=n.map(function(t){return o.put(t)});return te.waitFor(c)})}(t,e)})),p=p.next(function(){!function(t){t.createObjectStore(rn.store,{keyPath:rn.keyPath})}(t),function(t){t.createObjectStore(nn.store,{keyPath:"id",autoIncrement:!0})}(t)})),n<5&&r>=5&&(p=p.next(function(){return o.removeAcknowledgedMutations(e)})),n<6&&r>=6&&(p=p.next(function(){return function(t){t.createObjectStore(Xe.store)}(t),o.addDocumentGlobal(e)})),n<7&&r>=7&&(p=p.next(function(){return o.ensureSequenceNumbers(e)})),n<8&&r>=8&&(p=p.next(function(){return o.createCollectionParentIndex(t,e)})),p},t.prototype.addDocumentGlobal=function(t){var e=0;return t.store(Ye.store).iterate(function(t,n){e+=Ue(n)}).next(function(){var n=new Xe(e);return t.store(Xe.store).put(Xe.key,n)})},t.prototype.removeAcknowledgedMutations=function(t){var e=this,n=t.store(We.store),r=t.store(Ke.store);return n.loadAll().next(function(n){return te.forEach(n,function(n){var o=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return r.loadAll(Ke.userMutationsIndex,o).next(function(r){return te.forEach(r,function(r){I(r.userId===n.userId,"Cannot process batch "+r.batchId+" from unexpected user");var o=e.serializer.fromDbMutationBatch(r);return re(t,n.userId,o).next(function(){})})})})})},t.prototype.ensureSequenceNumbers=function(t){var e=t.store($e.store),n=t.store(Ye.store);return Se(t).next(function(t){var r=[];return n.iterate(function(n,o){var path=new vt(n),c=function(path){return[0,Nt(path)]}(path);r.push(e.get(c).next(function(n){return n?te.resolve():function(path){return e.put(new $e(0,Nt(path),t))}(path)}))}).next(function(){return te.waitFor(r)})})},t.prototype.createCollectionParentIndex=function(t,e){t.createObjectStore(tn.store,{keyPath:tn.keyPath});var n=e.store(tn.store),r=new Fe,o=function(t){if(r.add(t)){var e=t.lastSegment(),o=t.popLast();return n.put({collectionId:e,parent:Nt(o)})}};return e.store(Ye.store).iterate({keysOnly:!0},function(t,e){var path=new vt(t);return o(path.popLast())}).next(function(){return e.store(Ge.store).iterate({keysOnly:!0},function(t,e){t[0];var n=t[1],path=(t[2],Ot(n));return o(path.popLast())})})},t}();var je=function(t,e){this.seconds=t,this.nanoseconds=e},Qe=function(){function t(t,e,n){this.ownerId=t,this.allowTabSynchronization=e,this.leaseTimestampMs=n}return t.store="owner",t.key="owner",t}();var We=function(){function t(t,e,n){this.userId=t,this.lastAcknowledgedBatchId=e,this.lastStreamToken=n}return t.store="mutationQueues",t.keyPath="userId",t}(),Ke=function(){function t(t,e,n,r,o){this.userId=t,this.batchId=e,this.localWriteTimeMs=n,this.baseMutations=r,this.mutations=o}return t.store="mutations",t.keyPath="batchId",t.userMutationsIndex="userMutationsIndex",t.userMutationsKeyPath=["userId","batchId"],t}();var Ge=function(){function t(){}return t.prefixForUser=function(t){return[t]},t.prefixForPath=function(t,path){return[t,Nt(path)]},t.key=function(t,path,e){return[t,Nt(path),e]},t.store="documentMutations",t.PLACEHOLDER=new t,t}();var ze=function(path,t){this.path=path,this.readTime=t},He=function(path,t){this.path=path,this.version=t},Ye=function(){function t(t,e,n,r){this.unknownDocument=t,this.noDocument=e,this.document=n,this.hasCommittedMutations=r}return t.store="remoteDocuments",t}(),Xe=function(){function t(t){this.byteSize=t}return t.store="remoteDocumentGlobal",t.key="remoteDocumentGlobalKey",t}();var Je=function(){function t(t,e,n,r,o,c){this.targetId=t,this.canonicalId=e,this.readTime=n,this.resumeToken=r,this.lastListenSequenceNumber=o,this.query=c}return t.store="targets",t.keyPath="targetId",t.queryTargetsIndexName="queryTargetsIndex",t.queryTargetsKeyPath=["canonicalId","targetId"],t}(),$e=function(){function t(t,path,e){this.targetId=t,this.path=path,this.sequenceNumber=e,I(0===t==(void 0!==e),"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}(),Ze=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}(),tn=function(){function t(t,e){this.collectionId=t,this.parent=e}return t.store="collectionParents",t.keyPath=["collectionId","parent"],t}();function en(t){t.createObjectStore($e.store,{keyPath:$e.keyPath}).createIndex($e.documentTargetsIndex,$e.documentTargetsKeyPath,{unique:!0}),t.createObjectStore(Je.store,{keyPath:Je.keyPath}).createIndex(Je.queryTargetsIndexName,Je.queryTargetsKeyPath,{unique:!0}),t.createObjectStore(Ze.store)}var nn=function(){function t(t){this.changes=t}return t.store="remoteDocumentChanges",t.keyPath="id",t}();var rn=function(){function t(t,e,n,r,o){this.clientId=t,this.updateTimeMs=e,this.networkEnabled=n,this.inForeground=r,this.lastProcessedDocumentChangeId=o}return t.store="clientMetadata",t.keyPath="clientId",t}();var on,an=[We.store,Ke.store,Ge.store,Ye.store,Je.store,Qe.store,Ze.store,$e.store].concat([rn.store,nn.store]).concat([Xe.store]).concat([tn.store]),sn=function(){function t(){this.collectionParentsCache=new Fe}return t.prototype.addToCollectionParentIndex=function(t,e){if(I(e.length%2==1,"Expected a collection path."),this.collectionParentsCache.add(e)){I(e.length>=1,"Invalid collection path.");var n=e.lastSegment(),r=e.popLast();return un(t).put({collectionId:n,parent:Nt(r)})}return te.resolve()},t.prototype.getCollectionParents=function(t,e){var n=[],r=IDBKeyRange.bound([e,""],[at(e),""],!1,!0);return un(t).loadAll(r).next(function(t){for(var r=0,o=t;ry.params.maximumSequenceNumbersToCollect?(E("LruGarbageCollector","Capping sequence numbers to collect down to the maximum of "+y.params.maximumSequenceNumbersToCollect+" from "+e),r=y.params.maximumSequenceNumbersToCollect):r=e,l=Date.now(),y.nthSequenceNumber(t,r)}).next(function(r){return n=r,f=Date.now(),y.removeTargets(t,n,e)}).next(function(e){return c=e,d=Date.now(),y.removeOrphanedDocuments(t,n)}).next(function(t){(m=Date.now(),v()<=o.DEBUG)&&E("LruGarbageCollector","LRU Garbage Collection\n\tCounted targets in "+(l-h)+"ms\n\tDetermined least recently used "+r+" in "+(f-l)+"ms\n\tRemoved "+c+" targets in "+(d-f)+"ms\n\tRemoved "+t+" documents in "+(m-d)+"ms\nTotal Duration: "+(m-h)+"ms");return te.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:c,documentsRemoved:t})})},t}(),gn="IndexedDbPersistence",vn="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",bn="Another tab has exclusive access to the persistence layer. To allow shared access, make sure to invoke `enablePersistence()` with `synchronizeTabs:true` in all tabs.",wn="This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.",En=function(t){function e(e,n){var r=t.call(this)||this;return r.simpleDbTransaction=e,r.currentSequenceNumber=n,r}return l.__extends(e,t),e}(function(){}),Sn=function(){function t(e,n,r,o,c,h,l){if(this.persistenceKey=e,this.clientId=n,this.queue=o,this.multiClientParams=l,this._started=!1,this.isPrimary=!1,this.networkEnabled=!0,this.inForeground=!1,this.lastGarbageCollectionTime=Number.NEGATIVE_INFINITY,this.primaryStateListener=function(t){return Promise.resolve()},!t.isAvailable())throw new N(A.UNIMPLEMENTED,wn);if(this.referenceDelegate=new An(this,h),this.dbName=e+t.MAIN_DATABASE,this.serializer=new hn(c),this.document=r.document,this.allowTabSynchronization=void 0!==l,this.queryCache=new be(this.referenceDelegate,this.serializer),this.indexManager=new sn,this.remoteDocumentCache=new ke(this.serializer,this.indexManager,this.allowTabSynchronization),!r.window||!r.window.localStorage)throw new N(A.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");this.window=r.window,this.webStorage=this.window.localStorage}return t.getStore=function(t,e){if(t instanceof En)return fe.getStore(t.simpleDbTransaction,e);throw T("IndexedDbPersistence must use instances of IndexedDbTransaction")},t.createIndexedDbPersistence=function(e,n,r,o,c,h){return l.__awaiter(this,void 0,void 0,function(){var f;return l.__generator(this,function(l){switch(l.label){case 0:return[4,(f=new t(e,n,r,o,c,h)).start()];case 1:return l.sent(),[2,f]}})})},t.createMultiClientIndexedDbPersistence=function(e,n,r,o,c,h,f){return l.__awaiter(this,void 0,void 0,function(){var d;return l.__generator(this,function(l){switch(l.label){case 0:return[4,(d=new t(e,n,r,o,c,h,f)).start()];case 1:return l.sent(),[2,d]}})})},t.prototype.start=function(){var t=this;return I(!this.started,"IndexedDbPersistence double-started!"),I(null!==this.window,"Expected 'window' to be defined"),fe.openOrCreate(this.dbName,Be,new Ve(this.serializer)).then(function(e){return t.simpleDb=e,t.updateClientMetadataAndTryBecomePrimary()}).then(function(){return t.attachVisibilityHandler(),t.attachWindowUnloadHook(),t.scheduleClientMetadataAndPrimaryLeaseRefreshes(),t.startRemoteDocumentCache()}).then(function(){return t.simpleDb.runTransaction("readonly",[Ze.store],function(e){return Se(e).next(function(e){var n=t.multiClientParams?t.multiClientParams.sequenceNumberSyncer:void 0;t.listenSequence=new yt(e,n)})})}).then(function(){t._started=!0}).catch(function(e){return t.simpleDb&&t.simpleDb.close(),Promise.reject(e)})},t.prototype.startRemoteDocumentCache=function(){var t=this;return this.simpleDb.runTransaction("readonly",an,function(e){return t.remoteDocumentCache.start(e)})},t.prototype.setPrimaryStateListener=function(t){var e=this;return this.primaryStateListener=function(n){return l.__awaiter(e,void 0,void 0,function(){return l.__generator(this,function(e){return this.started?[2,t(n)]:[2]})})},t(this.isPrimary)},t.prototype.setDatabaseDeletedListener=function(t){var e=this;this.simpleDb.setVersionChangeListener(function(n){return l.__awaiter(e,void 0,void 0,function(){return l.__generator(this,function(e){switch(e.label){case 0:return null!==n.newVersion?[3,2]:[4,t()];case 1:e.sent(),e.label=2;case 2:return[2]}})})})},t.prototype.setNetworkEnabled=function(t){var e=this;this.networkEnabled!==t&&(this.networkEnabled=t,this.queue.enqueueAndForget(function(){return l.__awaiter(e,void 0,void 0,function(){return l.__generator(this,function(t){switch(t.label){case 0:return this.started?[4,this.updateClientMetadataAndTryBecomePrimary()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})})}))},t.prototype.updateClientMetadataAndTryBecomePrimary=function(){var t=this;return this.simpleDb.runTransaction("readwrite",an,function(e){return In(e).put(new rn(t.clientId,Date.now(),t.networkEnabled,t.inForeground,t.remoteDocumentCache.lastProcessedDocumentChangeId)).next(function(){if(t.isPrimary)return t.verifyPrimaryLease(e).next(function(e){e||(t.isPrimary=!1,t.queue.enqueueAndForget(function(){return t.primaryStateListener(!1)}))})}).next(function(){return t.canActAsPrimary(e)}).next(function(n){var r=t.isPrimary;return t.isPrimary=n,r!==t.isPrimary&&t.queue.enqueueAndForget(function(){return t.primaryStateListener(t.isPrimary)}),r&&!t.isPrimary?t.releasePrimaryLeaseIfHeld(e):t.isPrimary?t.acquireOrExtendPrimaryLease(e):void 0})})},t.prototype.verifyPrimaryLease=function(t){var e=this;return Tn(t).get(Qe.key).next(function(t){return te.resolve(e.isLocalClient(t))})},t.prototype.removeClientMetadata=function(t){return In(t).delete(this.clientId)},t.prototype.maybeGarbageCollectMultiClientState=function(){return l.__awaiter(this,void 0,void 0,function(){var e,n,r=this;return l.__generator(this,function(o){switch(o.label){case 0:return!this.isPrimary||this.isWithinAge(this.lastGarbageCollectionTime,18e5)?[3,2]:(this.lastGarbageCollectionTime=Date.now(),n=[],[4,this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",function(o){var c=t.getStore(o,rn.store);return c.loadAll().next(function(t){e=r.filterActiveClients(t,18e5),n=t.filter(function(t){return-1===e.indexOf(t)})}).next(function(){return te.forEach(n,function(t){return c.delete(t.clientId)})}).next(function(){if((e=e.filter(function(t){return t.clientId!==r.clientId})).length>0){var t=e.map(function(t){return t.lastProcessedDocumentChangeId||0}),n=Math.min.apply(Math,t);return r.remoteDocumentCache.removeDocumentChangesThroughChangeId(o,n)}})})]);case 1:o.sent(),n.forEach(function(t){r.window.localStorage.removeItem(r.zombiedClientLocalStorageKey(t.clientId))}),o.label=2;case 2:return[2]}})})},t.prototype.scheduleClientMetadataAndPrimaryLeaseRefreshes=function(){var t=this;this.clientMetadataRefresher=this.queue.enqueueAfterDelay(ct.ClientMetadataRefresh,4e3,function(){return t.updateClientMetadataAndTryBecomePrimary().then(function(){return t.maybeGarbageCollectMultiClientState()}).then(function(){return t.scheduleClientMetadataAndPrimaryLeaseRefreshes()})})},t.prototype.isLocalClient=function(t){return!!t&&t.ownerId===this.clientId},t.prototype.canActAsPrimary=function(t){var e=this;return Tn(t).get(Qe.key).next(function(n){if(null!==n&&e.isWithinAge(n.leaseTimestampMs,5e3)&&!e.isClientZombied(n.ownerId)){if(e.isLocalClient(n)&&e.networkEnabled)return!0;if(!e.isLocalClient(n)){if(!n.allowTabSynchronization)throw new N(A.FAILED_PRECONDITION,bn);return!1}}return!(!e.networkEnabled||!e.inForeground)||In(t).loadAll().next(function(t){return void 0===e.filterActiveClients(t,5e3).find(function(t){if(e.clientId!==t.clientId){var n=!e.networkEnabled&&t.networkEnabled,r=!e.inForeground&&t.inForeground,o=e.networkEnabled===t.networkEnabled;if(n||r&&o)return!0}return!1})})}).next(function(t){return e.isPrimary!==t&&E(gn,"Client "+(t?"is":"is not")+" eligible for a primary lease."),t})},t.prototype.shutdown=function(){return l.__awaiter(this,void 0,void 0,function(){var t=this;return l.__generator(this,function(e){switch(e.label){case 0:return this._started=!1,this.markClientZombied(),this.clientMetadataRefresher&&this.clientMetadataRefresher.cancel(),this.detachVisibilityHandler(),this.detachWindowUnloadHook(),[4,this.simpleDb.runTransaction("readwrite",[Qe.store,rn.store],function(e){return t.releasePrimaryLeaseIfHeld(e).next(function(){return t.removeClientMetadata(e)})})];case 1:return e.sent(),this.simpleDb.close(),this.removeClientZombiedEntry(),[2]}})})},t.prototype.filterActiveClients=function(t,e){var n=this;return t.filter(function(t){return n.isWithinAge(t.updateTimeMs,e)&&!n.isClientZombied(t.clientId)})},t.prototype.getActiveClients=function(){var t=this;return this.simpleDb.runTransaction("readonly",[rn.store],function(e){return In(e).loadAll().next(function(e){return t.filterActiveClients(e,18e5).map(function(t){return t.clientId})})})},t.clearPersistence=function(e){return l.__awaiter(this,void 0,void 0,function(){var n;return l.__generator(this,function(r){switch(r.label){case 0:return t.isAvailable()?(n=e+t.MAIN_DATABASE,[4,fe.delete(n)]):[2,Promise.resolve()];case 1:return r.sent(),[2]}})})},Object.defineProperty(t.prototype,"started",{get:function(){return this._started},enumerable:!0,configurable:!0}),t.prototype.getMutationQueue=function(t){return I(this.started,"Cannot initialize MutationQueue before persistence is started."),ee.forUser(t,this.serializer,this.indexManager,this.referenceDelegate)},t.prototype.getQueryCache=function(){return I(this.started,"Cannot initialize QueryCache before persistence is started."),this.queryCache},t.prototype.getRemoteDocumentCache=function(){return I(this.started,"Cannot initialize RemoteDocumentCache before persistence is started."),this.remoteDocumentCache},t.prototype.getIndexManager=function(){return I(this.started,"Cannot initialize IndexManager before persistence is started."),this.indexManager},t.prototype.runTransaction=function(t,e,n){var r=this;return E(gn,"Starting transaction:",t),this.simpleDb.runTransaction("readonly"===e?"readonly":"readwrite",an,function(o){return"readwrite-primary"===e?r.verifyPrimaryLease(o).next(function(e){if(!e)throw S("Failed to obtain primary lease for action '"+t+"'."),r.isPrimary=!1,r.queue.enqueueAndForget(function(){return r.primaryStateListener(!1)}),new N(A.FAILED_PRECONDITION,vn);return n(new En(o,r.listenSequence.next()))}).next(function(t){return r.acquireOrExtendPrimaryLease(o).next(function(){return t})}):r.verifyAllowTabSynchronization(o).next(function(){return n(new En(o,r.listenSequence.next()))})})},t.prototype.verifyAllowTabSynchronization=function(t){var e=this;return Tn(t).get(Qe.key).next(function(t){if(null!==t&&e.isWithinAge(t.leaseTimestampMs,5e3)&&!e.isClientZombied(t.ownerId)&&!e.isLocalClient(t)&&!t.allowTabSynchronization)throw new N(A.FAILED_PRECONDITION,bn)})},t.prototype.acquireOrExtendPrimaryLease=function(t){var e=new Qe(this.clientId,this.allowTabSynchronization,Date.now());return Tn(t).put(Qe.key,e)},t.isAvailable=function(){return fe.isAvailable()},t.buildStoragePrefix=function(t){var e=t.databaseId.projectId;return t.databaseId.isDefaultDatabase||(e+="."+t.databaseId.database),"firestore/"+t.persistenceKey+"/"+e+"/"},t.prototype.releasePrimaryLeaseIfHeld=function(t){var e=this,n=Tn(t);return n.get(Qe.key).next(function(t){return e.isLocalClient(t)?(E(gn,"Releasing primary lease."),n.delete(Qe.key)):te.resolve()})},t.prototype.isWithinAge=function(t,e){var n=Date.now();return!(tn)||(S("Detected an update time that is in the future: "+t+" > "+n),!1))},t.prototype.attachVisibilityHandler=function(){var t=this;null!==this.document&&"function"==typeof this.document.addEventListener&&(this.documentVisibilityHandler=function(){t.queue.enqueueAndForget(function(){return t.inForeground="visible"===t.document.visibilityState,t.updateClientMetadataAndTryBecomePrimary()})},this.document.addEventListener("visibilitychange",this.documentVisibilityHandler),this.inForeground="visible"===this.document.visibilityState)},t.prototype.detachVisibilityHandler=function(){this.documentVisibilityHandler&&(I(null!==this.document&&"function"==typeof this.document.addEventListener,"Expected 'document.addEventListener' to be a function"),this.document.removeEventListener("visibilitychange",this.documentVisibilityHandler),this.documentVisibilityHandler=null)},t.prototype.attachWindowUnloadHook=function(){var t=this;"function"==typeof this.window.addEventListener&&(this.windowUnloadHandler=function(){t.markClientZombied(),t.queue.enqueueAndForget(function(){return t.shutdown()})},this.window.addEventListener("unload",this.windowUnloadHandler))},t.prototype.detachWindowUnloadHook=function(){this.windowUnloadHandler&&(I("function"==typeof this.window.removeEventListener,"Expected 'window.removeEventListener' to be a function"),this.window.removeEventListener("unload",this.windowUnloadHandler),this.windowUnloadHandler=null)},t.prototype.isClientZombied=function(t){try{var e=null!==this.webStorage.getItem(this.zombiedClientLocalStorageKey(t));return E(gn,"Client '"+t+"' "+(e?"is":"is not")+" zombied in LocalStorage"),e}catch(t){return S(gn,"Failed to get zombied client id.",t),!1}},t.prototype.markClientZombied=function(){try{this.webStorage.setItem(this.zombiedClientLocalStorageKey(this.clientId),String(Date.now()))}catch(t){S("Failed to set zombie client id.",t)}},t.prototype.removeClientZombiedEntry=function(){try{this.webStorage.removeItem(this.zombiedClientLocalStorageKey(this.clientId))}catch(t){}},t.prototype.zombiedClientLocalStorageKey=function(t){return"firestore_zombie_"+this.persistenceKey+"_"+t},t.MAIN_DATABASE="main",t}();function _n(t){return l.__awaiter(this,void 0,void 0,function(){return l.__generator(this,function(e){if(!function(t){return t.code===A.FAILED_PRECONDITION&&t.message===vn}(t))throw t;return E(gn,"Unexpectedly lost primary lease"),[2]})})}function Tn(t){return t.store(Qe.store)}function In(t){return t.store(rn.store)}var Cn,Dn,An=function(){function t(t,e){this.db=t,this.garbageCollector=new yn(this,e)}return t.prototype.getSequenceNumberCount=function(t){var e=this.orphanedDocmentCount(t);return this.db.getQueryCache().getQueryCount(t).next(function(t){return e.next(function(e){return t+e})})},t.prototype.orphanedDocmentCount=function(t){var e=0;return this.forEachOrphanedDocumentSequenceNumber(t,function(t){e++}).next(function(){return e})},t.prototype.forEachTarget=function(t,e){return this.db.getQueryCache().forEachTarget(t,e)},t.prototype.forEachOrphanedDocumentSequenceNumber=function(t,e){return this.forEachOrphanedDocument(t,function(t,n){return e(n)})},t.prototype.setInMemoryPins=function(t){this.inMemoryPins=t},t.prototype.addReference=function(t,e){return Nn(t,e)},t.prototype.removeReference=function(t,e){return Nn(t,e)},t.prototype.removeTargets=function(t,e,n){return this.db.getQueryCache().removeTargets(t,e,n)},t.prototype.removeMutationReference=function(t,e){return Nn(t,e)},t.prototype.isPinned=function(t,e){return this.inMemoryPins.containsKey(e)?te.resolve(!0):function(t,e){var n=!1;return se(t).iterateSerial(function(r){return ne(t,r,e).next(function(t){return t&&(n=!0),te.resolve(!t)})}).next(function(){return n})}(t,e)},t.prototype.removeOrphanedDocuments=function(t,e){var n=this,r=0,o=0,c=[];return this.forEachOrphanedDocument(t,function(h,l){if(l<=e){var p=n.isPinned(t,h).next(function(e){if(!e)return r++,n.removeOrphanedDocument(t,h).next(function(t){o+=t})});c.push(p)}}).next(function(){return te.waitFor(c)}).next(function(){return n.db.getRemoteDocumentCache().updateSize(t,-o)}).next(function(){return r})},t.prototype.removeOrphanedDocument=function(t,e){var n,r=0,o=this.db.getRemoteDocumentCache();return te.waitFor([_e(t).delete((n=e,[0,Nt(n.path)])),o.removeEntry(t,e).next(function(t){r+=t})]).next(function(){return r})},t.prototype.removeTarget=function(t,e){var n=e.copy({sequenceNumber:t.currentSequenceNumber});return this.db.getQueryCache().updateQueryData(t,n)},t.prototype.updateLimboDocument=function(t,e){return Nn(t,e)},t.prototype.forEachOrphanedDocument=function(t,e){var n,r=_e(t),o=yt.INVALID;return r.iterate({index:$e.documentTargetsIndex},function(t,r){var c=t[0],path=(t[1],r.path),h=r.sequenceNumber;0===c?(o!==yt.INVALID&&e(new Et(Ot(n)),o),o=h,n=path):o=yt.INVALID}).next(function(){o!==yt.INVALID&&e(new Et(Ot(n)),o)})},t.prototype.getCacheSize=function(t){return this.db.getRemoteDocumentCache().getSize(t)},t}();function Nn(t,e){return _e(t).put(function(t,e){return new $e(0,Nt(t.path),e)}(e,t.currentSequenceNumber))}!function(t){t[t.NullValue=0]="NullValue",t[t.BooleanValue=1]="BooleanValue",t[t.NumberValue=2]="NumberValue",t[t.TimestampValue=3]="TimestampValue",t[t.StringValue=4]="StringValue",t[t.BlobValue=5]="BlobValue",t[t.RefValue=6]="RefValue",t[t.GeoPointValue=7]="GeoPointValue",t[t.ArrayValue=8]="ArrayValue",t[t.ObjectValue=9]="ObjectValue"}(Cn||(Cn={})),function(t){t[t.Default=0]="Default",t[t.Estimate=1]="Estimate",t[t.Previous=2]="Previous"}(Dn||(Dn={}));var Rn=function(){function t(t,e){this.serverTimestampBehavior=t,this.timestampsInSnapshots=e}return t.fromSnapshotOptions=function(e,n){switch(e.serverTimestamps){case"estimate":return new t(Dn.Estimate,n);case"previous":return new t(Dn.Previous,n);case"none":case void 0:return new t(Dn.Default,n);default:return T("fromSnapshotOptions() called with invalid options.")}},t}(),kn=function(){function t(){}return t.prototype.toString=function(){var t=this.value();return null===t?"null":t.toString()},t.prototype.defaultCompareTo=function(t){return I(this.typeOrder!==t.typeOrder,"Default compareTo should not be used for values of same type."),it(this.typeOrder,t.typeOrder)},t}(),On=function(t){function e(){var e=t.call(this)||this;return e.typeOrder=Cn.NullValue,e.internalValue=null,e}return l.__extends(e,t),e.prototype.value=function(t){return null},e.prototype.isEqual=function(t){return t instanceof e},e.prototype.compareTo=function(t){return t instanceof e?0:this.defaultCompareTo(t)},e.INSTANCE=new e,e}(kn),Mn=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Cn.BooleanValue,n}return l.__extends(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?it(this,t):this.defaultCompareTo(t)},e.of=function(t){return t?e.TRUE:e.FALSE},e.TRUE=new e(!0),e.FALSE=new e(!1),e}(kn),Pn=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Cn.NumberValue,n}return l.__extends(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.compareTo=function(t){return t instanceof e?(n=this.internalValue,r=t.internalValue,nr?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1):this.defaultCompareTo(t);var n,r},e}(kn);function Ln(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}var xn,Un=function(t){function e(e){return t.call(this,e)||this}return l.__extends(e,t),e.prototype.isEqual=function(t){return t instanceof e&&Ln(this.internalValue,t.internalValue)},e}(Pn),qn=function(t){function e(e){var n=t.call(this,e)||this;return n.internalValue=e,n}return l.__extends(e,t),e.prototype.isEqual=function(t){return t instanceof e&&Ln(this.internalValue,t.internalValue)},e.NAN=new e(NaN),e.POSITIVE_INFINITY=new e(1/0),e.NEGATIVE_INFINITY=new e(-1/0),e}(Pn),Fn=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Cn.StringValue,n}return l.__extends(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?it(this.internalValue,t.internalValue):this.defaultCompareTo(t)},e}(kn),Bn=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Cn.TimestampValue,n}return l.__extends(e,t),e.prototype.value=function(t){return!t||t.timestampsInSnapshots?this.internalValue:this.internalValue.toDate()},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue.isEqual(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue._compareTo(t.internalValue):t instanceof Vn?-1:this.defaultCompareTo(t)},e}(kn),Vn=function(t){function e(e,n){var r=t.call(this)||this;return r.localWriteTime=e,r.previousValue=n,r.typeOrder=Cn.TimestampValue,r}return l.__extends(e,t),e.prototype.value=function(t){return t&&t.serverTimestampBehavior===Dn.Estimate?new Bn(this.localWriteTime).value(t):t&&t.serverTimestampBehavior===Dn.Previous&&this.previousValue?this.previousValue.value(t):null},e.prototype.isEqual=function(t){return t instanceof e&&this.localWriteTime.isEqual(t.localWriteTime)},e.prototype.compareTo=function(t){return t instanceof e?this.localWriteTime._compareTo(t.localWriteTime):t instanceof Bn?1:this.defaultCompareTo(t)},e.prototype.toString=function(){return""},e}(kn),jn=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Cn.BlobValue,n}return l.__extends(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue.isEqual(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue._compareTo(t.internalValue):this.defaultCompareTo(t)},e}(kn),Qn=function(t){function e(e,n){var r=t.call(this)||this;return r.databaseId=e,r.key=n,r.typeOrder=Cn.RefValue,r}return l.__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.databaseId.isEqual(t.databaseId))},e.prototype.compareTo=function(t){if(t instanceof e){var n=this.databaseId.compareTo(t.databaseId);return 0!==n?n:Et.comparator(this.key,t.key)}return this.defaultCompareTo(t)},e}(kn),Wn=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Cn.GeoPointValue,n}return l.__extends(e,t),e.prototype.value=function(t){return this.internalValue},e.prototype.isEqual=function(t){return t instanceof e&&this.internalValue.isEqual(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue._compareTo(t.internalValue):this.defaultCompareTo(t)},e}(kn),Kn=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Cn.ObjectValue,n}return l.__extends(e,t),e.prototype.value=function(t){var e={};return this.internalValue.inorderTraversal(function(n,r){e[n]=r.value(t)}),e},e.prototype.forEach=function(t){this.internalValue.inorderTraversal(t)},e.prototype.isEqual=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var o=n.getNext(),c=r.getNext();if(o.key!==c.key||!o.value.isEqual(c.value))return!1}return!n.hasNext()&&!r.hasNext()}return!1},e.prototype.compareTo=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var o=n.getNext(),c=r.getNext(),h=it(o.key,c.key)||o.value.compareTo(c.value);if(h)return h}return it(n.hasNext(),r.hasNext())}return this.defaultCompareTo(t)},e.prototype.set=function(path,t){if(I(!path.isEmpty(),"Cannot set field for empty path on ObjectValue"),1===path.length)return this.setChild(path.firstSegment(),t);var n=this.child(path.firstSegment());n instanceof e||(n=e.EMPTY);var r=n.set(path.popFirst(),t);return this.setChild(path.firstSegment(),r)},e.prototype.delete=function(path){if(I(!path.isEmpty(),"Cannot delete field for empty path on ObjectValue"),1===path.length)return new e(this.internalValue.remove(path.firstSegment()));var t=this.child(path.firstSegment());if(t instanceof e){var n=t.delete(path.popFirst());return new e(this.internalValue.insert(path.firstSegment(),n))}return this},e.prototype.contains=function(path){return void 0!==this.field(path)},e.prototype.field=function(path){I(!path.isEmpty(),"Can't get field of empty path");var t=this;return path.forEach(function(n){t=t instanceof e&&t.internalValue.get(n)||void 0}),t},e.prototype.toString=function(){return this.internalValue.toString()},e.prototype.child=function(t){return this.internalValue.get(t)||void 0},e.prototype.setChild=function(t,n){return new e(this.internalValue.insert(t,n))},e.EMPTY=new e(new Lt(it)),e}(kn),Gn=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=Cn.ArrayValue,n}return l.__extends(e,t),e.prototype.value=function(t){return this.internalValue.map(function(e){return e.value(t)})},e.prototype.contains=function(t){for(var e=0,n=this.internalValue;e0){var m=f;f=f.copy({resumeToken:d,snapshotVersion:e.snapshotVersion}),n.queryDataByTarget[r]=f,t.shouldPersistQueryData(m,f,l)&&c.push(n.queryCache.updateQueryData(o,f))}}});var l=jt(),f=Yt();e.documentUpdates.forEach(function(t,e){f=f.add(t)}),c.push(r.getEntries(o,f).next(function(t){e.documentUpdates.forEach(function(f,d){var m=t.get(f);null==m||d.version.isEqual(Pt.MIN)||h.has(d.key)&&!m.hasPendingWrites||d.version.compareTo(m.version)>=0?(r.addEntry(d),l=l.insert(f,d)):E("LocalStore","Ignoring outdated watch update for ",f,". Current version:",m.version," Watch version:",d.version),e.resolvedLimboDocuments.has(f)&&c.push(n.persistence.referenceDelegate.updateLimboDocument(o,f))})}));var d=e.snapshotVersion;if(!d.isEqual(Pt.MIN)){var m=n.queryCache.getLastRemoteSnapshotVersion(o).next(function(t){return I(d.compareTo(t)>=0,"Watch stream reverted to previous snapshot?? "+d+" < "+t),n.queryCache.setTargetsMetadata(o,o.currentSequenceNumber,d)});c.push(m)}return te.waitFor(c).next(function(){return r.apply(o)}).next(function(){return n.localDocuments.getLocalViewOfDocuments(o,l)})})},t.shouldPersistQueryData=function(t,e,n){return 0!==e.resumeToken.length&&(0===t.resumeToken.length||(e.snapshotVersion.toMicroseconds()-t.snapshotVersion.toMicroseconds()>=this.RESUME_TOKEN_MAX_AGE_MICROS||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0))},t.prototype.notifyLocalViewChanges=function(t){var e=this;return this.persistence.runTransaction("notifyLocalViewChanges","readwrite",function(n){return te.forEach(t,function(t){return e.localViewReferences.addReferences(t.addedKeys,t.targetId),e.localViewReferences.removeReferences(t.removedKeys,t.targetId),te.forEach(t.removedKeys,function(t){return e.persistence.referenceDelegate.removeReference(n,t)})})})},t.prototype.nextMutationBatch=function(t){var e=this;return this.persistence.runTransaction("Get next mutation batch","readonly",function(n){return void 0===t&&(t=-1),e.mutationQueue.getNextMutationBatchAfterBatchId(n,t)})},t.prototype.readDocument=function(t){var e=this;return this.persistence.runTransaction("read document","readonly",function(n){return e.localDocuments.getDocument(n,t)})},t.prototype.allocateQuery=function(t){var e=this;return this.persistence.runTransaction("Allocate query","readwrite",function(n){var r;return e.queryCache.getQueryData(n,t).next(function(o){return o?(r=o,te.resolve()):e.queryCache.allocateTargetId(n).next(function(o){return r=new cn(t,o,on.Listen,n.currentSequenceNumber),e.queryCache.addQueryData(n,r)})}).next(function(){return I(!e.queryDataByTarget[r.targetId],"Tried to allocate an already allocated query: "+t),e.queryDataByTarget[r.targetId]=r,r})})},t.prototype.releaseQuery=function(t,e){var n=this,r=e?"readwrite":"readwrite-primary";return this.persistence.runTransaction("Release query",r,function(r){return n.queryCache.getQueryData(r,t).next(function(o){I(null!=o,"Tried to release nonexistent query: "+t);var c=o.targetId,h=n.queryDataByTarget[c],l=n.localViewReferences.removeReferencesForId(c);return delete n.queryDataByTarget[c],e?te.resolve():te.forEach(l,function(t){return n.persistence.referenceDelegate.removeReference(r,t)}).next(function(){return n.persistence.referenceDelegate.removeTarget(r,h)})})})},t.prototype.executeQuery=function(t){var e=this;return this.persistence.runTransaction("Execute query","readonly",function(n){return e.localDocuments.getDocumentsMatchingQuery(n,t)})},t.prototype.remoteDocumentKeys=function(t){var e=this;return this.persistence.runTransaction("Remote document keys","readonly",function(n){return e.queryCache.getMatchingKeysForTargetId(n,t)})},t.prototype.getActiveClients=function(){return this.persistence.getActiveClients()},t.prototype.removeCachedMutationBatchMetadata=function(t){this.mutationQueue.removeCachedMutationKeys(t)},t.prototype.setNetworkEnabled=function(t){this.persistence.setNetworkEnabled(t)},t.prototype.applyWriteToRemoteDocuments=function(t,e,n){var r=this,o=e.batch,c=o.keys(),h=te.resolve();return c.forEach(function(r){h=h.next(function(){return n.getEntry(t,r)}).next(function(t){var c=t,h=e.docVersions.get(r);I(null!==h,"ackVersions should contain every doc in the write."),(!c||c.version.compareTo(h)<0)&&((c=o.applyToRemoteDocument(r,c,e))?n.addEntry(c):I(!t,"Mutation batch "+o+" applied to document "+t+" resulted in null"))})}),h.next(function(){return r.mutationQueue.removeMutationBatch(t,o)})},t.prototype.collectGarbage=function(t){var e=this;return this.persistence.runTransaction("Collect garbage","readwrite-primary",function(n){return t.collect(n,e.queryDataByTarget)})},t.prototype.getQueryForTarget=function(t){var e=this;return this.queryDataByTarget[t]?Promise.resolve(this.queryDataByTarget[t].query):this.persistence.runTransaction("Get query data","readonly",function(n){return e.queryCache.getQueryDataForTarget(n,t).next(function(t){return t?t.query:null})})},t.prototype.getNewDocumentChanges=function(){var t=this;return this.persistence.runTransaction("Get new document changes","readonly",function(e){return t.remoteDocuments.getNewDocumentChanges(e)})},t.RESUME_TOKEN_MAX_AGE_MICROS=3e8,t}(),sr=function(){function t(t,e){this.indexManager=t,this.referenceDelegate=e,this.mutationQueue=[],this.nextBatchId=1,this.lastStreamToken=D(),this.batchesByDocumentKey=new Ft(or.compareByKey)}return t.prototype.checkEmpty=function(t){return te.resolve(0===this.mutationQueue.length)},t.prototype.acknowledgeBatch=function(t,e,n){var r=e.batchId,o=this.indexOfExistingBatchId(r,"acknowledged");I(0===o,"Can only acknowledge the first batch in the mutation queue");var c=this.mutationQueue[o];return I(r===c.batchId,"Queue ordering failure: expected batch "+r+", got batch "+c.batchId),this.lastStreamToken=n,te.resolve()},t.prototype.getLastStreamToken=function(t){return te.resolve(this.lastStreamToken)},t.prototype.setLastStreamToken=function(t,e){return this.lastStreamToken=e,te.resolve()},t.prototype.addMutationBatch=function(t,e,n,r){I(0!==r.length,"Mutation batches should not be empty");var o=this.nextBatchId;(this.nextBatchId++,this.mutationQueue.length>0)&&I(this.mutationQueue[this.mutationQueue.length-1].batchIdo?this.mutationQueue[o]:null)},t.prototype.getAllMutationBatches=function(t){return te.resolve(this.mutationQueue.slice())},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=new or(e,0),o=new or(e,Number.POSITIVE_INFINITY),c=[];return this.batchesByDocumentKey.forEachInRange([r,o],function(t){I(e.isEqual(t.key),"Should only iterate over a single key's batches");var r=n.findMutationBatch(t.targetOrBatchId);I(null!==r,"Batches in the index must exist in the main table"),c.push(r)}),te.resolve(c)},t.prototype.getAllMutationBatchesAffectingDocumentKeys=function(t,e){var n=this,r=new Ft(it);return e.forEach(function(t){var e=new or(t,0),o=new or(t,Number.POSITIVE_INFINITY);n.batchesByDocumentKey.forEachInRange([e,o],function(e){I(t.isEqual(e.key),"For each key, should only iterate over a single key's batches"),r=r.add(e.targetOrBatchId)})}),te.resolve(this.findMutationBatches(r))},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){I(!e.isCollectionGroupQuery(),"CollectionGroup queries should be handled in LocalDocumentsView");var n=e.path,r=n.length+1,o=n;Et.isDocumentKey(o)||(o=o.child(""));var c=new or(new Et(o),0),h=new Ft(it);return this.batchesByDocumentKey.forEachWhile(function(t){var e=t.key.path;return!!n.isPrefixOf(e)&&(e.length===r&&(h=h.add(t.targetOrBatchId)),!0)},c),te.resolve(this.findMutationBatches(h))},t.prototype.findMutationBatches=function(t){var e=this,n=[];return t.forEach(function(t){var r=e.findMutationBatch(t);null!==r&&n.push(r)}),n},t.prototype.removeMutationBatch=function(t,e){var n=this;I(0===this.indexOfExistingBatchId(e.batchId,"removed"),"Can only remove the first entry of the mutation queue"),this.mutationQueue.shift();var r=this.batchesByDocumentKey;return te.forEach(e.mutations,function(o){var c=new or(o.key,e.batchId);return r=r.delete(c),n.referenceDelegate.removeMutationReference(t,o.key)}).next(function(){n.batchesByDocumentKey=r})},t.prototype.removeCachedMutationKeys=function(t){},t.prototype.containsKey=function(t,e){var n=new or(e,0),r=this.batchesByDocumentKey.firstAfterOrEqual(n);return te.resolve(e.isEqual(r&&r.key))},t.prototype.performConsistencyCheck=function(t){return 0===this.mutationQueue.length&&I(this.batchesByDocumentKey.isEmpty(),"Document leak -- detected dangling mutation references when queue is empty."),te.resolve()},t.prototype.indexOfExistingBatchId=function(t,e){var n=this.indexOfBatchId(t);return I(n>=0&&n=this.mutationQueue.length)return null;var n=this.mutationQueue[e];return I(n.batchId===t,"If found batch must match"),n},t}(),ur=function(){function t(t){this.persistence=t,this.queries=new Ae(function(q){return q.canonicalId()}),this.lastRemoteSnapshotVersion=Pt.MIN,this.highestTargetId=0,this.highestSequenceNumber=0,this.references=new ir,this.targetCount=0,this.targetIdGenerator=he.forQueryCache()}return t.prototype.getTargetCount=function(t){return te.resolve(this.targetCount)},t.prototype.forEachTarget=function(t,e){return this.queries.forEach(function(t,n){return e(n)}),te.resolve()},t.prototype.getLastRemoteSnapshotVersion=function(t){return te.resolve(this.lastRemoteSnapshotVersion)},t.prototype.getHighestSequenceNumber=function(t){return te.resolve(this.highestSequenceNumber)},t.prototype.allocateTargetId=function(t){var e=this.targetIdGenerator.after(this.highestTargetId);return this.highestTargetId=e,te.resolve(e)},t.prototype.setTargetsMetadata=function(t,e,n){return n&&(this.lastRemoteSnapshotVersion=n),e>this.highestSequenceNumber&&(this.highestSequenceNumber=e),te.resolve()},t.prototype.saveQueryData=function(t){this.queries.set(t.query,t);var e=t.targetId;e>this.highestTargetId&&(this.highestTargetId=e),t.sequenceNumber>this.highestSequenceNumber&&(this.highestSequenceNumber=t.sequenceNumber)},t.prototype.addQueryData=function(t,e){return I(!this.queries.has(e.query),"Adding a query that already exists"),this.saveQueryData(e),this.targetCount+=1,te.resolve()},t.prototype.updateQueryData=function(t,e){return I(this.queries.has(e.query),"Updating a non-existent query"),this.saveQueryData(e),te.resolve()},t.prototype.removeQueryData=function(t,e){return I(this.targetCount>0,"Removing a target from an empty cache"),I(this.queries.has(e.query),"Removing a non-existent target from the cache"),this.queries.delete(e.query),this.references.removeReferencesForId(e.targetId),this.targetCount-=1,te.resolve()},t.prototype.removeTargets=function(t,e,n){var r=this,o=0,c=[];return this.queries.forEach(function(h,l){l.sequenceNumber<=e&&!n[l.targetId]&&(r.queries.delete(h),c.push(r.removeMatchingKeysForTargetId(t,l.targetId)),o++)}),te.waitFor(c).next(function(){return o})},t.prototype.getQueryCount=function(t){return te.resolve(this.targetCount)},t.prototype.getQueryData=function(t,e){var n=this.queries.get(e)||null;return te.resolve(n)},t.prototype.getQueryDataForTarget=function(t,e){return T("Not yet implemented.")},t.prototype.addMatchingKeys=function(t,e,n){this.references.addReferences(e,n);var r=this.persistence.referenceDelegate,o=[];return r&&e.forEach(function(e){o.push(r.addReference(t,e))}),te.waitFor(o)},t.prototype.removeMatchingKeys=function(t,e,n){this.references.removeReferences(e,n);var r=this.persistence.referenceDelegate,o=[];return r&&e.forEach(function(e){o.push(r.removeReference(t,e))}),te.waitFor(o)},t.prototype.removeMatchingKeysForTargetId=function(t,e){return this.references.removeReferencesForId(e),te.resolve()},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=this.references.referencesForId(e);return te.resolve(n)},t.prototype.containsKey=function(t,e){return te.resolve(this.references.containsKey(e))},t}();var cr=function(){function t(t,e){this.indexManager=t,this.sizer=e,this.docs=new Lt(Et.comparator),this.newDocumentChanges=Yt(),this.size=0}return t.prototype.addEntries=function(t,e,n){for(var r=[],o=0,c=e;on)}])},t.prototype.getCacheSize=function(t){return this.persistence.getRemoteDocumentCache().getSize(t)},t}(),yr=Number,gr=yr.MIN_SAFE_INTEGER||-(Math.pow(2,53)-1),vr=yr.MAX_SAFE_INTEGER||Math.pow(2,53)-1,wr=yr.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function Er(t){return null==t}function Sr(t){return wr(t)&&t<=vr&&t>=gr}var _r,Tr=function(){function t(t,e,n,r,o){this.queue=t,this.timerId=e,this.initialDelayMs=n,this.backoffFactor=r,this.maxDelayMs=o,this.timerPromise=null,this.lastAttemptTime=Date.now(),this.reset()}return t.prototype.reset=function(){this.currentBaseMs=0},t.prototype.resetToMax=function(){this.currentBaseMs=this.maxDelayMs},t.prototype.backoffAndRun=function(t){var e=this;this.cancel();var n=Math.floor(this.currentBaseMs+this.jitterDelayMs()),r=Math.max(0,Date.now()-this.lastAttemptTime),o=Math.max(0,n-r);this.currentBaseMs>0&&E("ExponentialBackoff","Backing off for "+o+" ms (base delay: "+this.currentBaseMs+" ms, delay with jitter: "+n+" ms, last attempt: "+r+" ms ago)"),this.timerPromise=this.queue.enqueueAfterDelay(this.timerId,o,function(){return e.lastAttemptTime=Date.now(),t()}),this.currentBaseMs*=this.backoffFactor,this.currentBaseMsthis.maxDelayMs&&(this.currentBaseMs=this.maxDelayMs)},t.prototype.cancel=function(){null!==this.timerPromise&&(this.timerPromise.cancel(),this.timerPromise=null)},t.prototype.jitterDelayMs=function(){return(Math.random()-.5)*this.currentBaseMs},t}();!function(t){t[t.Initial=0]="Initial",t[t.Starting=1]="Starting",t[t.Open=2]="Open",t[t.Error=3]="Error",t[t.Backoff=4]="Backoff"}(_r||(_r={}));var Ir,Cr,Dr=1e3,Ar=6e4,Nr=1.5,Rr=function(){function t(t,e,n,r,o,c){this.queue=t,this.idleTimerId=n,this.connection=r,this.credentialsProvider=o,this.listener=c,this.state=_r.Initial,this.closeCount=0,this.idleTimer=null,this.stream=null,this.backoff=new Tr(t,e,Dr,Nr,Ar)}return t.prototype.isStarted=function(){return this.state===_r.Starting||this.state===_r.Open||this.state===_r.Backoff},t.prototype.isOpen=function(){return this.state===_r.Open},t.prototype.start=function(){this.state!==_r.Error?(I(this.state===_r.Initial,"Already started"),this.auth()):this.performBackoff()},t.prototype.stop=function(){return l.__awaiter(this,void 0,void 0,function(){return l.__generator(this,function(t){switch(t.label){case 0:return this.isStarted()?[4,this.close(_r.Initial)]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})})},t.prototype.inhibitBackoff=function(){I(!this.isStarted(),"Can only inhibit backoff in a stopped state"),this.state=_r.Initial,this.backoff.reset()},t.prototype.markIdle=function(){var t=this;this.isOpen()&&null===this.idleTimer&&(this.idleTimer=this.queue.enqueueAfterDelay(this.idleTimerId,6e4,function(){return t.handleIdleCloseTimer()}))},t.prototype.sendRequest=function(t){this.cancelIdleCheck(),this.stream.send(t)},t.prototype.handleIdleCloseTimer=function(){return l.__awaiter(this,void 0,void 0,function(){return l.__generator(this,function(t){return this.isOpen()?[2,this.close(_r.Initial)]:[2]})})},t.prototype.cancelIdleCheck=function(){this.idleTimer&&(this.idleTimer.cancel(),this.idleTimer=null)},t.prototype.close=function(t,e){return l.__awaiter(this,void 0,void 0,function(){return l.__generator(this,function(n){switch(n.label){case 0:return I(this.isStarted(),"Only started streams should be closed."),I(t===_r.Error||Er(e),"Can't provide an error when not in an error state."),this.cancelIdleCheck(),this.backoff.cancel(),this.closeCount++,t!==_r.Error?this.backoff.reset():e&&e.code===A.RESOURCE_EXHAUSTED?(S(e.toString()),S("Using maximum backoff delay to prevent overloading the backend."),this.backoff.resetToMax()):e&&e.code===A.UNAUTHENTICATED&&this.credentialsProvider.invalidateToken(),null!==this.stream&&(this.tearDown(),this.stream.close(),this.stream=null),this.state=t,[4,this.listener.onClose(e)];case 1:return n.sent(),[2]}})})},t.prototype.tearDown=function(){},t.prototype.auth=function(){var t=this;I(this.state===_r.Initial,"Must be in initial state to auth"),this.state=_r.Starting;var e=this.getCloseGuardedDispatcher(this.closeCount),n=this.closeCount;this.credentialsProvider.getToken().then(function(e){t.closeCount===n&&t.startStream(e)},function(n){e(function(){var e=new N(A.UNKNOWN,"Fetching auth token failed: "+n.message);return t.handleStreamClose(e)})})},t.prototype.startStream=function(t){var e=this;I(this.state===_r.Starting,"Trying to start stream in a non-starting state");var n=this.getCloseGuardedDispatcher(this.closeCount);this.stream=this.startRpc(t),this.stream.onOpen(function(){n(function(){return I(e.state===_r.Starting,"Expected stream to be in state Starting, but was "+e.state),e.state=_r.Open,e.listener.onOpen()})}),this.stream.onClose(function(t){n(function(){return e.handleStreamClose(t)})}),this.stream.onMessage(function(t){n(function(){return e.onMessage(t)})})},t.prototype.performBackoff=function(){var t=this;I(this.state===_r.Error,"Should only perform backoff when in Error state"),this.state=_r.Backoff,this.backoff.backoffAndRun(function(){return l.__awaiter(t,void 0,void 0,function(){return l.__generator(this,function(t){return I(this.state===_r.Backoff,"Backoff elapsed but state is now: "+this.state),this.state=_r.Initial,this.start(),I(this.isStarted(),"PersistentStream should have started"),[2]})})})},t.prototype.handleStreamClose=function(t){return I(this.isStarted(),"Can't handle server close on non-started stream"),E("PersistentStream","close with error: "+t),this.stream=null,this.close(_r.Error,t)},t.prototype.getCloseGuardedDispatcher=function(t){var e=this;return function(n){e.queue.enqueueAndForget(function(){return e.closeCount===t?n():(E("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())})}},t}(),kr=function(t){function e(e,n,r,o,c){var h=t.call(this,e,ct.ListenStreamConnectionBackoff,ct.ListenStreamIdle,n,r,c)||this;return h.serializer=o,h}return l.__extends(e,t),e.prototype.startRpc=function(t){return this.connection.openStream("Listen",t)},e.prototype.onMessage=function(t){this.backoff.reset();var e=this.serializer.fromWatchChange(t),n=this.serializer.versionFromListenResponse(t);return this.listener.onWatchChange(e,n)},e.prototype.watch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.addTarget=this.serializer.toTarget(t);var n=this.serializer.toListenRequestLabels(t);n&&(e.labels=n),this.sendRequest(e)},e.prototype.unwatch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.removeTarget=t,this.sendRequest(e)},e}(Rr),Or=function(t){function e(e,n,r,o,c){var h=t.call(this,e,ct.WriteStreamConnectionBackoff,ct.WriteStreamIdle,n,r,c)||this;return h.serializer=o,h.handshakeComplete_=!1,h}return l.__extends(e,t),Object.defineProperty(e.prototype,"handshakeComplete",{get:function(){return this.handshakeComplete_},enumerable:!0,configurable:!0}),e.prototype.start=function(){this.handshakeComplete_=!1,t.prototype.start.call(this)},e.prototype.tearDown=function(){this.handshakeComplete_&&this.writeMutations([])},e.prototype.startRpc=function(t){return this.connection.openStream("Write",t)},e.prototype.onMessage=function(t){if(I(!!t.streamToken,"Got a write response without a stream token"),this.lastStreamToken=t.streamToken,this.handshakeComplete_){this.backoff.reset();var e=this.serializer.fromWriteResults(t.writeResults,t.commitTime),n=this.serializer.fromVersion(t.commitTime);return this.listener.onMutationResult(n,e)}return I(!t.writeResults||0===t.writeResults.length,"Got mutation results for handshake"),this.handshakeComplete_=!0,this.listener.onHandshakeComplete()},e.prototype.writeHandshake=function(){I(this.isOpen(),"Writing handshake requires an opened stream"),I(!this.handshakeComplete_,"Handshake already completed");var t={};t.database=this.serializer.encodedDatabaseId,this.sendRequest(t)},e.prototype.writeMutations=function(t){var e=this;I(this.isOpen(),"Writing mutations requires an opened stream"),I(this.handshakeComplete_,"Handshake must be complete before writing mutations"),I(this.lastStreamToken.length>0,"Trying to write mutation without a token");var n={streamToken:this.lastStreamToken,writes:t.map(function(t){return e.serializer.toMutation(t)})};this.sendRequest(n)},e}(Rr),Mr=function(){function t(t,e,n,r){this.queue=t,this.connection=e,this.credentials=n,this.serializer=r}return t.prototype.newPersistentWriteStream=function(t){return new Or(this.queue,this.connection,this.credentials,this.serializer,t)},t.prototype.newPersistentWatchStream=function(t){return new kr(this.queue,this.connection,this.credentials,this.serializer,t)},t.prototype.commit=function(t){var e=this,n={database:this.serializer.encodedDatabaseId,writes:t.map(function(t){return e.serializer.toMutation(t)})};return this.invokeRPC("Commit",n).then(function(t){return e.serializer.fromWriteResults(t.writeResults,t.commitTime)})},t.prototype.lookup=function(t){var e=this,n={database:this.serializer.encodedDatabaseId,documents:t.map(function(t){return e.serializer.toName(t)})};return this.invokeStreamingRPC("BatchGetDocuments",n).then(function(n){var r=jt();n.forEach(function(t){var n=e.serializer.fromMaybeDocument(t);r=r.insert(n.key,n)});var o=[];return t.forEach(function(t){var e=r.get(t);I(!!e,"Missing entity in write response for "+t),o.push(e)}),o})},t.prototype.invokeRPC=function(t,e){var n=this;return this.credentials.getToken().then(function(r){return n.connection.invokeRPC(t,e,r)}).catch(function(t){throw t.code===A.UNAUTHENTICATED&&n.credentials.invalidateToken(),t})},t.prototype.invokeStreamingRPC=function(t,e){var n=this;return this.credentials.getToken().then(function(r){return n.connection.invokeStreamingRPC(t,e,r)}).catch(function(t){throw t.code===A.UNAUTHENTICATED&&n.credentials.invalidateToken(),t})},t}(),Pr=function(){function t(t){this.datastore=t,this.readVersions=zt(),this.mutations=[],this.committed=!1}return t.prototype.recordVersion=function(t){var e;if(t instanceof Ie)e=t.version;else{if(!(t instanceof Ce))throw T("Document in a transaction was a "+t.constructor.name);e=Pt.forDeletedDoc()}var n=this.readVersions.get(t.key);if(null!==n){if(!e.isEqual(n))throw new N(A.ABORTED,"Document version changed between two reads.")}else this.readVersions=this.readVersions.insert(t.key,e)},t.prototype.lookup=function(t){var e=this;return this.committed?Promise.reject("Transaction has already completed."):this.mutations.length>0?Promise.reject("Transactions lookups are invalid after writes."):this.datastore.lookup(t).then(function(t){return t.forEach(function(t){t instanceof Ce||t instanceof Ie?e.recordVersion(t):T("Document in a transaction was a "+t.constructor.name)}),t})},t.prototype.write=function(t){if(this.committed)throw new N(A.FAILED_PRECONDITION,"Transaction has already completed.");this.mutations=this.mutations.concat(t)},t.prototype.precondition=function(t){var e=this.readVersions.get(t);return e?Xn.updateTime(e):Xn.NONE},t.prototype.preconditionForUpdate=function(t){var e=this.readVersions.get(t);if(e&&e.isEqual(Pt.forDeletedDoc()))throw new N(A.FAILED_PRECONDITION,"Can't update a document that doesn't exist.");return e?Xn.updateTime(e):Xn.exists(!0)},t.prototype.set=function(t,data){this.write(data.toMutations(t,this.precondition(t)))},t.prototype.update=function(t,data){this.write(data.toMutations(t,this.preconditionForUpdate(t)))},t.prototype.delete=function(t){this.write([new nr(t,this.precondition(t))]),this.readVersions=this.readVersions.insert(t,Pt.forDeletedDoc())},t.prototype.commit=function(){var t=this,e=this.readVersions;return this.mutations.forEach(function(t){e=e.remove(t.key)}),e.isEmpty()?this.datastore.commit(this.mutations).then(function(){t.committed=!0}):Promise.reject(Error("Every document read in a transaction must also be written."))},t}();!function(t){t[t.Unknown=0]="Unknown",t[t.Online=1]="Online",t[t.Offline=2]="Offline"}(Ir||(Ir={})),function(t){t[t.RemoteStore=0]="RemoteStore",t[t.SharedClientState=1]="SharedClientState"}(Cr||(Cr={}));var Lr,xr=function(){function t(t,e){this.asyncQueue=t,this.onlineStateHandler=e,this.state=Ir.Unknown,this.watchStreamFailures=0,this.onlineStateTimer=null,this.shouldWarnClientIsOffline=!0}return t.prototype.handleWatchStreamStart=function(){var t=this;0===this.watchStreamFailures&&(this.setAndBroadcast(Ir.Unknown),I(null===this.onlineStateTimer,"onlineStateTimer shouldn't be started yet"),this.onlineStateTimer=this.asyncQueue.enqueueAfterDelay(ct.OnlineStateTimeout,1e4,function(){return t.onlineStateTimer=null,I(t.state===Ir.Unknown,"Timer should be canceled if we transitioned to a different state."),t.logClientOfflineWarningIfNecessary("Backend didn't respond within 10 seconds."),t.setAndBroadcast(Ir.Offline),Promise.resolve()}))},t.prototype.handleWatchStreamFailure=function(t){this.state===Ir.Online?(this.setAndBroadcast(Ir.Unknown),I(0===this.watchStreamFailures,"watchStreamFailures must be 0"),I(null===this.onlineStateTimer,"onlineStateTimer must be null")):(this.watchStreamFailures++,this.watchStreamFailures>=1&&(this.clearOnlineStateTimer(),this.logClientOfflineWarningIfNecessary("Connection failed 1 times. Most recent error: "+t.toString()),this.setAndBroadcast(Ir.Offline)))},t.prototype.set=function(t){this.clearOnlineStateTimer(),this.watchStreamFailures=0,t===Ir.Online&&(this.shouldWarnClientIsOffline=!1),this.setAndBroadcast(t)},t.prototype.setAndBroadcast=function(t){t!==this.state&&(this.state=t,this.onlineStateHandler(t))},t.prototype.logClientOfflineWarningIfNecessary=function(details){var t="Could not reach Cloud Firestore backend. "+details+"\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.shouldWarnClientIsOffline?(S(t),this.shouldWarnClientIsOffline=!1):E("OnlineStateTracker",t)},t.prototype.clearOnlineStateTimer=function(){null!==this.onlineStateTimer&&(this.onlineStateTimer.cancel(),this.onlineStateTimer=null)},t}();function Ur(code){switch(code){case A.OK:return T("Treated status OK as error");case A.CANCELLED:case A.UNKNOWN:case A.DEADLINE_EXCEEDED:case A.RESOURCE_EXHAUSTED:case A.INTERNAL:case A.UNAVAILABLE:case A.UNAUTHENTICATED:return!1;case A.INVALID_ARGUMENT:case A.NOT_FOUND:case A.ALREADY_EXISTS:case A.PERMISSION_DENIED:case A.FAILED_PRECONDITION:case A.ABORTED:case A.OUT_OF_RANGE:case A.UNIMPLEMENTED:case A.DATA_LOSS:return!0;default:return T("Unknown status code: "+code)}}function qr(code){if(void 0===code)return S("GRPC error has no .code"),A.UNKNOWN;switch(code){case Lr.OK:return A.OK;case Lr.CANCELLED:return A.CANCELLED;case Lr.UNKNOWN:return A.UNKNOWN;case Lr.DEADLINE_EXCEEDED:return A.DEADLINE_EXCEEDED;case Lr.RESOURCE_EXHAUSTED:return A.RESOURCE_EXHAUSTED;case Lr.INTERNAL:return A.INTERNAL;case Lr.UNAVAILABLE:return A.UNAVAILABLE;case Lr.UNAUTHENTICATED:return A.UNAUTHENTICATED;case Lr.INVALID_ARGUMENT:return A.INVALID_ARGUMENT;case Lr.NOT_FOUND:return A.NOT_FOUND;case Lr.ALREADY_EXISTS:return A.ALREADY_EXISTS;case Lr.PERMISSION_DENIED:return A.PERMISSION_DENIED;case Lr.FAILED_PRECONDITION:return A.FAILED_PRECONDITION;case Lr.ABORTED:return A.ABORTED;case Lr.OUT_OF_RANGE:return A.OUT_OF_RANGE;case Lr.UNIMPLEMENTED:return A.UNIMPLEMENTED;case Lr.DATA_LOSS:return A.DATA_LOSS;default:return T("Unknown status code: "+code)}}function Fr(code){if(void 0===code)return Lr.OK;switch(code){case A.OK:return Lr.OK;case A.CANCELLED:return Lr.CANCELLED;case A.UNKNOWN:return Lr.UNKNOWN;case A.DEADLINE_EXCEEDED:return Lr.DEADLINE_EXCEEDED;case A.RESOURCE_EXHAUSTED:return Lr.RESOURCE_EXHAUSTED;case A.INTERNAL:return Lr.INTERNAL;case A.UNAVAILABLE:return Lr.UNAVAILABLE;case A.UNAUTHENTICATED:return Lr.UNAUTHENTICATED;case A.INVALID_ARGUMENT:return Lr.INVALID_ARGUMENT;case A.NOT_FOUND:return Lr.NOT_FOUND;case A.ALREADY_EXISTS:return Lr.ALREADY_EXISTS;case A.PERMISSION_DENIED:return Lr.PERMISSION_DENIED;case A.FAILED_PRECONDITION:return Lr.FAILED_PRECONDITION;case A.ABORTED:return Lr.ABORTED;case A.OUT_OF_RANGE:return Lr.OUT_OF_RANGE;case A.UNIMPLEMENTED:return Lr.UNIMPLEMENTED;case A.DATA_LOSS:return Lr.DATA_LOSS;default:return T("Unknown status code: "+code)}}!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"}(Lr||(Lr={}));var Br,Vr,jr=function(){function t(t){this.comparator=t?function(e,n){return t(e,n)||Et.comparator(e.key,n.key)}:function(t,e){return Et.comparator(t.key,e.key)},this.keyedMap=Kt(),this.sortedSet=new Lt(this.comparator)}return t.emptySet=function(e){return new t(e.comparator)},t.prototype.has=function(t){return null!=this.keyedMap.get(t)},t.prototype.get=function(t){return this.keyedMap.get(t)},t.prototype.first=function(){return this.sortedSet.minKey()},t.prototype.last=function(){return this.sortedSet.maxKey()},t.prototype.isEmpty=function(){return this.sortedSet.isEmpty()},t.prototype.indexOf=function(t){var e=this.keyedMap.get(t);return e?this.sortedSet.indexOf(e):-1},Object.defineProperty(t.prototype,"size",{get:function(){return this.sortedSet.size},enumerable:!0,configurable:!0}),t.prototype.forEach=function(t){this.sortedSet.inorderTraversal(function(e,n){return t(e),!1})},t.prototype.add=function(t){var e=this.delete(t.key);return e.copy(e.keyedMap.insert(t.key,t),e.sortedSet.insert(t,null))},t.prototype.delete=function(t){var e=this.get(t);return e?this.copy(this.keyedMap.remove(t),this.sortedSet.remove(e)):this},t.prototype.isEqual=function(e){if(!(e instanceof t))return!1;if(this.size!==e.size)return!1;for(var n=this.sortedSet.getIterator(),r=e.sortedSet.getIterator();n.hasNext();){var o=n.getNext().key,c=r.getNext().key;if(!o.isEqual(c))return!1}return!0},t.prototype.toString=function(){var t=[];return this.forEach(function(e){t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"},t.prototype.copy=function(e,n){var r=new t;return r.comparator=this.comparator,r.keyedMap=e,r.sortedSet=n,r},t}();!function(t){t[t.Added=0]="Added",t[t.Removed=1]="Removed",t[t.Modified=2]="Modified",t[t.Metadata=3]="Metadata"}(Br||(Br={})),function(t){t[t.Local=0]="Local",t[t.Synced=1]="Synced"}(Vr||(Vr={}));var Qr,Wr=function(){function t(){this.changeMap=new Lt(Et.comparator)}return t.prototype.track=function(t){var e=t.doc.key,n=this.changeMap.get(e);n?t.type!==Br.Added&&n.type===Br.Metadata?this.changeMap=this.changeMap.insert(e,t):t.type===Br.Metadata&&n.type!==Br.Removed?this.changeMap=this.changeMap.insert(e,{type:n.type,doc:t.doc}):t.type===Br.Modified&&n.type===Br.Modified?this.changeMap=this.changeMap.insert(e,{type:Br.Modified,doc:t.doc}):t.type===Br.Modified&&n.type===Br.Added?this.changeMap=this.changeMap.insert(e,{type:Br.Added,doc:t.doc}):t.type===Br.Removed&&n.type===Br.Added?this.changeMap=this.changeMap.remove(e):t.type===Br.Removed&&n.type===Br.Modified?this.changeMap=this.changeMap.insert(e,{type:Br.Removed,doc:n.doc}):t.type===Br.Added&&n.type===Br.Removed?this.changeMap=this.changeMap.insert(e,{type:Br.Modified,doc:t.doc}):T("unsupported combination of changes: "+JSON.stringify(t)+" after "+JSON.stringify(n)):this.changeMap=this.changeMap.insert(e,t)},t.prototype.getChanges=function(){var t=[];return this.changeMap.inorderTraversal(function(e,n){t.push(n)}),t},t}(),Kr=function(){function t(t,e,n,r,o,c,h,l){this.query=t,this.docs=e,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=o,this.fromCache=c,this.syncStateChanged=h,this.excludesMetadataChanges=l}return t.fromInitialDocuments=function(e,n,r,o){var c=[];return n.forEach(function(t){c.push({type:Br.Added,doc:t})}),new t(e,n,jr.emptySet(n),c,r,o,!0,!1)},Object.defineProperty(t.prototype,"hasPendingWrites",{get:function(){return!this.mutatedKeys.isEmpty()},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(t){if(!(this.fromCache===t.fromCache&&this.syncStateChanged===t.syncStateChanged&&this.mutatedKeys.isEqual(t.mutatedKeys)&&this.query.isEqual(t.query)&&this.docs.isEqual(t.docs)&&this.oldDocs.isEqual(t.oldDocs)))return!1;var e=this.docChanges,n=t.docChanges;if(e.length!==n.length)return!1;for(var i=0;i0&&(this._hasPendingChanges=!0,this._resumeToken=t)},t.prototype.toTargetChange=function(){var t=Yt(),e=Yt(),n=Yt();return this.documentChanges.forEach(function(r,o){switch(o){case Br.Added:t=t.add(r);break;case Br.Modified:e=e.add(r);break;case Br.Removed:n=n.add(r);break;default:T("Encountered invalid change type: "+o)}}),new zr(this._resumeToken,this._current,t,e,n)},t.prototype.clearPendingChanges=function(){this._hasPendingChanges=!1,this.documentChanges=ti()},t.prototype.addDocumentChange=function(t,e){this._hasPendingChanges=!0,this.documentChanges=this.documentChanges.insert(t,e)},t.prototype.removeDocumentChange=function(t){this._hasPendingChanges=!0,this.documentChanges=this.documentChanges.remove(t)},t.prototype.recordPendingTargetRequest=function(){this.pendingResponses+=1},t.prototype.recordTargetResponse=function(){this.pendingResponses-=1},t.prototype.markCurrent=function(){this._hasPendingChanges=!0,this._current=!0},t}(),$r=function(){function t(t){this.metadataProvider=t,this.targetStates={},this.pendingDocumentUpdates=jt(),this.pendingDocumentTargetMapping=Zr(),this.pendingTargetResets=new Ft(it)}return t.prototype.handleDocumentChange=function(t){for(var e=0,n=t.updatedTargetIds;e0?t.targetIds.forEach(e):M(this.targetStates,e)},t.prototype.handleExistenceFilter=function(t){var e=t.targetId,n=t.existenceFilter.count,r=this.queryDataForActiveTarget(e);if(r){var o=r.query;if(o.isDocumentQuery())if(0===n){var c=new Et(o.path);this.removeDocumentFromTarget(e,c,new Ce(c,Pt.forDeletedDoc()))}else I(1===n,"Single document existence filter with count: "+n);else this.getCurrentDocumentCountForTarget(e)!==n&&(this.resetTarget(e),this.pendingTargetResets=this.pendingTargetResets.add(e))}},t.prototype.createRemoteEvent=function(t){var e=this,n={};M(this.targetStates,function(r,o){var c=e.queryDataForActiveTarget(r);if(c){if(o.current&&c.query.isDocumentQuery()){var h=new Et(c.query.path);null!==e.pendingDocumentUpdates.get(h)||e.targetContainsDocument(r,h)||e.removeDocumentFromTarget(r,h,new Ce(h,t))}o.hasPendingChanges&&(n[r]=o.toTargetChange(),o.clearPendingChanges())}});var r=Yt();this.pendingDocumentTargetMapping.forEach(function(t,n){var o=!0;n.forEachWhile(function(t){var n=e.queryDataForActiveTarget(t);return!n||n.purpose===on.LimboResolution||(o=!1,!1)}),o&&(r=r.add(t))});var o=new Gr(t,n,this.pendingTargetResets,this.pendingDocumentUpdates,r);return this.pendingDocumentUpdates=jt(),this.pendingDocumentTargetMapping=Zr(),this.pendingTargetResets=new Ft(it),o},t.prototype.addDocumentToTarget=function(t,e){if(this.isActiveTarget(t)){var n=this.targetContainsDocument(t,e.key)?Br.Modified:Br.Added;this.ensureTargetState(t).addDocumentChange(e.key,n),this.pendingDocumentUpdates=this.pendingDocumentUpdates.insert(e.key,e),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(e.key,this.ensureDocumentTargetMapping(e.key).add(t))}},t.prototype.removeDocumentFromTarget=function(t,e,n){if(this.isActiveTarget(t)){var r=this.ensureTargetState(t);this.targetContainsDocument(t,e)?r.addDocumentChange(e,Br.Removed):r.removeDocumentChange(e),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(e,this.ensureDocumentTargetMapping(e).delete(t)),n&&(this.pendingDocumentUpdates=this.pendingDocumentUpdates.insert(e,n))}},t.prototype.removeTarget=function(t){delete this.targetStates[t]},t.prototype.getCurrentDocumentCountForTarget=function(t){var e=this.ensureTargetState(t).toTargetChange();return this.metadataProvider.getRemoteKeysForTarget(t).size+e.addedDocuments.size-e.removedDocuments.size},t.prototype.recordPendingTargetRequest=function(t){this.ensureTargetState(t).recordPendingTargetRequest()},t.prototype.ensureTargetState=function(t){return this.targetStates[t]||(this.targetStates[t]=new Jr),this.targetStates[t]},t.prototype.ensureDocumentTargetMapping=function(t){var e=this.pendingDocumentTargetMapping.get(t);return e||(e=new Ft(it),this.pendingDocumentTargetMapping=this.pendingDocumentTargetMapping.insert(t,e)),e},t.prototype.isActiveTarget=function(t){return null!==this.queryDataForActiveTarget(t)},t.prototype.queryDataForActiveTarget=function(t){var e=this.targetStates[t];return e&&e.isPending?null:this.metadataProvider.getQueryDataForTarget(t)},t.prototype.resetTarget=function(t){var e=this;I(!this.targetStates[t].isPending,"Should only reset active targets"),this.targetStates[t]=new Jr,this.metadataProvider.getRemoteKeysForTarget(t).forEach(function(n){e.removeDocumentFromTarget(t,n,null)})},t.prototype.targetContainsDocument=function(t,e){return this.metadataProvider.getRemoteKeysForTarget(t).has(e)},t}();function Zr(){return new Lt(Et.comparator)}function ti(){return new Lt(Et.comparator)}var ei="RemoteStore",ni=function(){function t(t,e,n,r,o){var c=this;this.localStore=t,this.datastore=e,this.writePipeline=[],this.listenTargets={},this.watchChangeAggregator=null,this.networkEnabled=!1,this.isPrimary=!1,this.connectivityMonitor=o,this.connectivityMonitor.addCallback(function(t){n.enqueueAndForget(function(){return l.__awaiter(c,void 0,void 0,function(){return l.__generator(this,function(t){switch(t.label){case 0:return this.canUseNetwork()?(E(ei,"Restarting streams for network reachability change."),[4,this.restartNetwork()]):[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})})})}),this.onlineStateTracker=new xr(n,r),this.watchStream=this.datastore.newPersistentWatchStream({onOpen:this.onWatchStreamOpen.bind(this),onClose:this.onWatchStreamClose.bind(this),onWatchChange:this.onWatchStreamChange.bind(this)}),this.writeStream=this.datastore.newPersistentWriteStream({onOpen:this.onWriteStreamOpen.bind(this),onClose:this.onWriteStreamClose.bind(this),onHandshakeComplete:this.onWriteHandshakeComplete.bind(this),onMutationResult:this.onMutationResult.bind(this)})}return t.prototype.start=function(){return this.enableNetwork()},t.prototype.enableNetwork=function(){return l.__awaiter(this,void 0,void 0,function(){var t;return l.__generator(this,function(e){switch(e.label){case 0:return this.networkEnabled=!0,this.canUseNetwork()?(t=this.writeStream,[4,this.localStore.getLastStreamToken()]):[3,3];case 1:return t.lastStreamToken=e.sent(),this.shouldStartWatchStream()?this.startWatchStream():this.onlineStateTracker.set(Ir.Unknown),[4,this.fillWritePipeline()];case 2:e.sent(),e.label=3;case 3:return[2]}})})},t.prototype.disableNetwork=function(){return l.__awaiter(this,void 0,void 0,function(){return l.__generator(this,function(t){switch(t.label){case 0:return this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return t.sent(),this.onlineStateTracker.set(Ir.Offline),[2]}})})},t.prototype.disableNetworkInternal=function(){return l.__awaiter(this,void 0,void 0,function(){return l.__generator(this,function(t){switch(t.label){case 0:return[4,this.writeStream.stop()];case 1:return t.sent(),[4,this.watchStream.stop()];case 2:return t.sent(),this.writePipeline.length>0&&(E(ei,"Stopping write stream with "+this.writePipeline.length+" pending writes"),this.writePipeline=[]),this.cleanUpWatchStreamState(),[2]}})})},t.prototype.shutdown=function(){return l.__awaiter(this,void 0,void 0,function(){return l.__generator(this,function(t){switch(t.label){case 0:return E(ei,"RemoteStore shutting down."),this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return t.sent(),this.connectivityMonitor.shutdown(),this.onlineStateTracker.set(Ir.Unknown),[2]}})})},t.prototype.listen=function(t){I(!k(this.listenTargets,t.targetId),"listen called with duplicate targetId!"),this.listenTargets[t.targetId]=t,this.shouldStartWatchStream()?this.startWatchStream():this.watchStream.isOpen()&&this.sendWatchRequest(t)},t.prototype.unlisten=function(t){I(k(this.listenTargets,t),"unlisten called without assigned target ID!"),delete this.listenTargets[t],this.watchStream.isOpen()&&this.sendUnwatchRequest(t),L(this.listenTargets)&&(this.watchStream.isOpen()?this.watchStream.markIdle():this.canUseNetwork()&&this.onlineStateTracker.set(Ir.Unknown))},t.prototype.getQueryDataForTarget=function(t){return this.listenTargets[t]||null},t.prototype.getRemoteKeysForTarget=function(t){return this.syncEngine.getRemoteKeysForTarget(t)},t.prototype.sendWatchRequest=function(t){this.watchChangeAggregator.recordPendingTargetRequest(t.targetId),this.watchStream.watch(t)},t.prototype.sendUnwatchRequest=function(t){this.watchChangeAggregator.recordPendingTargetRequest(t),this.watchStream.unwatch(t)},t.prototype.startWatchStream=function(){I(this.shouldStartWatchStream(),"startWatchStream() called when shouldStartWatchStream() is false."),this.watchChangeAggregator=new $r(this),this.watchStream.start(),this.onlineStateTracker.handleWatchStreamStart()},t.prototype.shouldStartWatchStream=function(){return this.canUseNetwork()&&!this.watchStream.isStarted()&&!L(this.listenTargets)},t.prototype.canUseNetwork=function(){return this.isPrimary&&this.networkEnabled},t.prototype.cleanUpWatchStreamState=function(){this.watchChangeAggregator=null},t.prototype.onWatchStreamOpen=function(){return l.__awaiter(this,void 0,void 0,function(){var t=this;return l.__generator(this,function(e){return M(this.listenTargets,function(e,n){t.sendWatchRequest(n)}),[2]})})},t.prototype.onWatchStreamClose=function(t){return l.__awaiter(this,void 0,void 0,function(){return l.__generator(this,function(e){return void 0===t&&I(!this.shouldStartWatchStream(),"Watch stream was stopped gracefully while still needed."),this.cleanUpWatchStreamState(),this.shouldStartWatchStream()?(this.onlineStateTracker.handleWatchStreamFailure(t),this.startWatchStream()):this.onlineStateTracker.set(Ir.Unknown),[2]})})},t.prototype.onWatchStreamChange=function(t,e){return l.__awaiter(this,void 0,void 0,function(){var n;return l.__generator(this,function(r){switch(r.label){case 0:return this.onlineStateTracker.set(Ir.Online),t instanceof Xr&&t.state===Qr.Removed&&t.cause?[2,this.handleTargetError(t)]:(t instanceof Hr?this.watchChangeAggregator.handleDocumentChange(t):t instanceof Yr?this.watchChangeAggregator.handleExistenceFilter(t):(I(t instanceof Xr,"Expected watchChange to be an instance of WatchTargetChange"),this.watchChangeAggregator.handleTargetChange(t)),e.isEqual(Pt.MIN)?[3,3]:[4,this.localStore.getLastRemoteSnapshotVersion()]);case 1:return n=r.sent(),e.compareTo(n)>=0?[4,this.raiseWatchSnapshot(e)]:[3,3];case 2:r.sent(),r.label=3;case 3:return[2]}})})},t.prototype.raiseWatchSnapshot=function(t){var e=this;I(!t.isEqual(Pt.MIN),"Can't raise event for unknown SnapshotVersion");var n=this.watchChangeAggregator.createRemoteEvent(t);return M(n.targetChanges,function(n,r){if(r.resumeToken.length>0){var o=e.listenTargets[n];o&&(e.listenTargets[n]=o.copy({resumeToken:r.resumeToken,snapshotVersion:t}))}}),n.targetMismatches.forEach(function(t){var n=e.listenTargets[t];if(n){e.listenTargets[t]=n.copy({resumeToken:D()}),e.sendUnwatchRequest(t);var r=new cn(n.query,t,on.ExistenceFilterMismatch,n.sequenceNumber);e.sendWatchRequest(r)}}),this.syncEngine.applyRemoteEvent(n)},t.prototype.handleTargetError=function(t){var e=this;I(!!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 l.__awaiter(e,void 0,void 0,function(){return l.__generator(this,function(e){return k(this.listenTargets,t)?(delete this.listenTargets[t],this.watchChangeAggregator.removeTarget(t),[2,this.syncEngine.rejectListen(t,n)]):[2]})})})}),r},t.prototype.fillWritePipeline=function(){return l.__awaiter(this,void 0,void 0,function(){var t,e;return l.__generator(this,function(n){switch(n.label){case 0:return this.canAddToWritePipeline()?(t=this.writePipeline.length>0?this.writePipeline[this.writePipeline.length-1].batchId:-1,[4,this.localStore.nextMutationBatch(t)]):[3,4];case 1:return null!==(e=n.sent())?[3,2]:(0===this.writePipeline.length&&this.writeStream.markIdle(),[3,4]);case 2:return this.addToWritePipeline(e),[4,this.fillWritePipeline()];case 3:n.sent(),n.label=4;case 4:return this.shouldStartWriteStream()&&this.startWriteStream(),[2]}})})},t.prototype.canAddToWritePipeline=function(){return this.canUseNetwork()&&this.writePipeline.length<10},t.prototype.outstandingWrites=function(){return this.writePipeline.length},t.prototype.addToWritePipeline=function(t){I(this.canAddToWritePipeline(),"addToWritePipeline called when pipeline is full"),this.writePipeline.push(t),this.writeStream.isOpen()&&this.writeStream.handshakeComplete&&this.writeStream.writeMutations(t.mutations)},t.prototype.shouldStartWriteStream=function(){return this.canUseNetwork()&&!this.writeStream.isStarted()&&this.writePipeline.length>0},t.prototype.startWriteStream=function(){I(this.shouldStartWriteStream(),"startWriteStream() called when shouldStartWriteStream() is false."),this.writeStream.start()},t.prototype.onWriteStreamOpen=function(){return l.__awaiter(this,void 0,void 0,function(){return l.__generator(this,function(t){return this.writeStream.writeHandshake(),[2]})})},t.prototype.onWriteHandshakeComplete=function(){var t=this;return this.localStore.setLastStreamToken(this.writeStream.lastStreamToken).then(function(){for(var e=0,n=t.writePipeline;e0,"Got result for empty write pipeline");var r=this.writePipeline.shift(),o=Zt.from(r,t,e,this.writeStream.lastStreamToken);return this.syncEngine.applySuccessfulWrite(o).then(function(){return n.fillWritePipeline()})},t.prototype.onWriteStreamClose=function(t){return l.__awaiter(this,void 0,void 0,function(){var e=this;return l.__generator(this,function(n){return void 0===t&&I(!this.shouldStartWriteStream(),"Write stream was stopped gracefully while still needed."),t&&this.writePipeline.length>0?(void 0,[2,(this.writeStream.handshakeComplete?this.handleWriteError(t):this.handleHandshakeError(t)).then(function(){e.shouldStartWriteStream()&&e.startWriteStream()})]):[2]})})},t.prototype.handleHandshakeError=function(t){return l.__awaiter(this,void 0,void 0,function(){return l.__generator(this,function(e){return Ur(t.code)?(E(ei,"RemoteStore error before completed handshake; resetting stream token: ",this.writeStream.lastStreamToken),this.writeStream.lastStreamToken=D(),[2,this.localStore.setLastStreamToken(D()).catch(_n)]):[2]})})},t.prototype.handleWriteError=function(t){return l.__awaiter(this,void 0,void 0,function(){var e,n=this;return l.__generator(this,function(r){return Ur(code=t.code)&&code!==A.ABORTED?(e=this.writePipeline.shift(),this.writeStream.inhibitBackoff(),[2,this.syncEngine.rejectFailedWrite(e.batchId,t).then(function(){return n.fillWritePipeline()})]):[2];var code})})},t.prototype.createTransaction=function(){return new Pr(this.datastore)},t.prototype.restartNetwork=function(){return l.__awaiter(this,void 0,void 0,function(){return l.__generator(this,function(t){switch(t.label){case 0:return this.networkEnabled=!1,[4,this.disableNetworkInternal()];case 1:return t.sent(),this.onlineStateTracker.set(Ir.Unknown),[4,this.enableNetwork()];case 2:return t.sent(),[2]}})})},t.prototype.handleCredentialChange=function(){return l.__awaiter(this,void 0,void 0,function(){return l.__generator(this,function(t){switch(t.label){case 0:return this.canUseNetwork()?(E(ei,"RemoteStore restarting streams for new credential"),[4,this.restartNetwork()]):[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})})},t.prototype.applyPrimaryState=function(t){return l.__awaiter(this,void 0,void 0,function(){return l.__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.disableNetworkInternal()];case 3:e.sent(),this.onlineStateTracker.set(Ir.Unknown),e.label=4;case 4:return[2]}})})},t}(),ri=function(){function t(t,e){if(U("GeoPoint",arguments,2),V("GeoPoint","number",1,t),V("GeoPoint","number",2,e),!isFinite(t)||t<-90||t>90)throw new N(A.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||e>180)throw new N(A.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this._lat=t,this._long=e}return Object.defineProperty(t.prototype,"latitude",{get:function(){return this._lat},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"longitude",{get:function(){return this._long},enumerable:!0,configurable:!0}),t.prototype.isEqual=function(t){return this._lat===t._lat&&this._long===t._long},t.prototype._compareTo=function(t){return it(this._lat,t._lat)||it(this._long,t._long)},t}(),ii=function(){function t(path,t,e,n,r,o,c){void 0===t&&(t=null),void 0===e&&(e=[]),void 0===n&&(n=[]),void 0===r&&(r=null),void 0===o&&(o=null),void 0===c&&(c=null),this.path=path,this.collectionGroup=t,this.explicitOrderBy=e,this.filters=n,this.limit=r,this.startAt=o,this.endAt=c,this.memoizedCanonicalId=null,this.memoizedOrderBy=null,this.startAt&&this.assertValidBound(this.startAt),this.endAt&&this.assertValidBound(this.endAt)}return t.atPath=function(path){return new t(path)},Object.defineProperty(t.prototype,"orderBy",{get:function(){if(null===this.memoizedOrderBy){var t=this.getInequalityFilterField(),e=this.getFirstOrderByField();if(null!==t&&null===e)t.isKeyField()?this.memoizedOrderBy=[yi]:this.memoizedOrderBy=[new mi(t),yi];else{I(null===t||null!==e&&t.isEqual(e),"First orderBy should match inequality field."),this.memoizedOrderBy=[];for(var n=!1,r=0,o=this.explicitOrderBy;r0?this.explicitOrderBy[this.explicitOrderBy.length-1].dir:pi.ASCENDING;this.memoizedOrderBy.push(h===pi.ASCENDING?yi:gi)}}}return this.memoizedOrderBy},enumerable:!0,configurable:!0}),t.prototype.addFilter=function(filter){I(null==this.getInequalityFilterField()||!(filter instanceof si)||!filter.isInequality()||filter.field.isEqual(this.getInequalityFilterField()),"Query must only have one inequality field."),I(!this.isDocumentQuery(),"No filtering allowed for document query");var e=this.filters.concat([filter]);return new t(this.path,this.collectionGroup,this.explicitOrderBy.slice(),e,this.limit,this.startAt,this.endAt)},t.prototype.addOrderBy=function(e){I(!this.startAt&&!this.endAt,"Bounds must be set after orderBy");var n=this.explicitOrderBy.concat([e]);return new t(this.path,this.collectionGroup,n,this.filters.slice(),this.limit,this.startAt,this.endAt)},t.prototype.withLimit=function(e){return new t(this.path,this.collectionGroup,this.explicitOrderBy.slice(),this.filters.slice(),e,this.startAt,this.endAt)},t.prototype.withStartAt=function(e){return new t(this.path,this.collectionGroup,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,e,this.endAt)},t.prototype.withEndAt=function(e){return new t(this.path,this.collectionGroup,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,e)},t.prototype.asCollectionQueryAtPath=function(path){return new t(path,null,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,this.endAt)},t.prototype.canonicalId=function(){if(null===this.memoizedCanonicalId){var t=this.path.canonicalString();this.isCollectionGroupQuery()&&(t+="|cg:"+this.collectionGroup),t+="|f:";for(var e=0,n=this.filters;e0&&(t+=", filters: ["+this.filters.join(", ")+"]"),Er(this.limit)||(t+=", limit: "+this.limit),this.explicitOrderBy.length>0&&(t+=", orderBy: ["+this.explicitOrderBy.join(", ")+"]"),this.startAt&&(t+=", startAt: "+this.startAt.canonicalId()),this.endAt&&(t+=", endAt: "+this.endAt.canonicalId()),t+")"},t.prototype.isEqual=function(t){if(this.limit!==t.limit)return!1;if(this.orderBy.length!==t.orderBy.length)return!1;for(var i=0;i0?this.explicitOrderBy[0].field:null},t.prototype.getInequalityFilterField=function(){for(var t=0,e=this.filters;t=0)return filter.op}return null},t.prototype.isDocumentQuery=function(){return Et.isDocumentKey(this.path)&&null===this.collectionGroup&&0===this.filters.length},t.prototype.isCollectionGroupQuery=function(){return null!==this.collectionGroup},t.prototype.matchesPathAndCollectionGroup=function(t){var e=t.key.path;return null!==this.collectionGroup?t.key.hasCollectionId(this.collectionGroup)&&this.path.isPrefixOf(e):Et.isDocumentKey(this.path)?this.path.isEqual(e):this.path.isImmediateParentOf(e)},t.prototype.matchesOrderBy=function(t){for(var e=0,n=this.explicitOrderBy;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 T("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}(),si=function(t){function e(e,n,r){var o=t.call(this)||this;return o.field=e,o.op=n,o.value=r,o}return l.__extends(e,t),e.create=function(t,n,r){if(t.isKeyField())return I(r instanceof Qn,"Comparing on key, but filter value not a RefValue"),I(n!==ai.ARRAY_CONTAINS&&n!==ai.ARRAY_CONTAINS_ANY&&n!==ai.IN,"'"+n.toString()+"' queries don't make sense on document keys."),new ui(t,n,r);if(r.isEqual(On.INSTANCE)){if(n!==ai.EQUAL)throw new N(A.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on null.");return new e(t,n,r)}if(r.isEqual(qn.NAN)){if(n!==ai.EQUAL)throw new N(A.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on NaN.");return new e(t,n,r)}return n===ai.ARRAY_CONTAINS?new ci(t,r):n===ai.IN?(I(r instanceof Gn,"IN filter has invalid value: "+r.toString()),new hi(t,r)):n===ai.ARRAY_CONTAINS_ANY?(I(r instanceof Gn,"ARRAY_CONTAINS_ANY filter has invalid value: "+r.toString()),new fi(t,r)):new e(t,n,r)},e.prototype.matches=function(t){var e=t.field(this.field);return void 0!==e&&this.value.typeOrder===e.typeOrder&&this.matchesComparison(e.compareTo(this.value))},e.prototype.matchesComparison=function(t){switch(this.op){case ai.LESS_THAN:return t<0;case ai.LESS_THAN_OR_EQUAL:return t<=0;case ai.EQUAL:return 0===t;case ai.GREATER_THAN:return t>0;case ai.GREATER_THAN_OR_EQUAL:return t>=0;default:return T("Unknown FieldFilter operator: "+this.op)}},e.prototype.isInequality=function(){return[ai.LESS_THAN,ai.LESS_THAN_OR_EQUAL,ai.GREATER_THAN,ai.GREATER_THAN_OR_EQUAL].indexOf(this.op)>=0},e.prototype.canonicalId=function(){return this.field.canonicalString()+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.canonicalString()+" "+this.op+" "+this.value.value()},e}(oi),ui=function(t){function e(e,n,r){return t.call(this,e,n,r)||this}return l.__extends(e,t),e.prototype.matches=function(t){var e=this.value,n=Et.comparator(t.key,e.key);return this.matchesComparison(n)},e}(si),ci=function(t){function e(e,n){return t.call(this,e,ai.ARRAY_CONTAINS,n)||this}return l.__extends(e,t),e.prototype.matches=function(t){var e=t.field(this.field);return e instanceof Gn&&e.contains(this.value)},e}(si),hi=function(t){function e(e,n){return t.call(this,e,ai.IN,n)||this}return l.__extends(e,t),e.prototype.matches=function(t){var e=this.value,n=t.field(this.field);return void 0!==n&&e.contains(n)},e}(si),fi=function(t){function e(e,n){return t.call(this,e,ai.ARRAY_CONTAINS_ANY,n)||this}return l.__extends(e,t),e.prototype.matches=function(t){var e=this.value,n=t.field(this.field);return n instanceof Gn&&n.internalValue.some(function(t){return e.contains(t)})},e}(si),pi=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}(),di=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;e4&&"documents"===t.get(4),"tried to deserialize invalid key "+t.toString()),t.popFirst(5)},t.prototype.isValidResourceName=function(path){return path.length>=4&&"projects"===path.get(0)&&"databases"===path.get(2)},t.prototype.toValue=function(t){if(t instanceof On)return{nullValue:"NULL_VALUE"};if(t instanceof Mn)return{booleanValue:t.value()};if(t instanceof Un)return{integerValue:""+t.value()};if(t instanceof qn){var e=t.value();if(this.options.useProto3Json){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 Fn?{stringValue:t.value()}:t instanceof Kn?{mapValue:this.toMapValue(t)}:t instanceof Gn?{arrayValue:this.toArrayValue(t)}:t instanceof Bn?{timestampValue:this.toTimestamp(t.internalValue)}:t instanceof Wn?{geoPointValue:{latitude:t.value().latitude,longitude:t.value().longitude}}:t instanceof jn?{bytesValue:this.toBytes(t.value())}:t instanceof Qn?{referenceValue:this.toResourceName(t.databaseId,t.key.path)}:T("Unknown FieldValue "+JSON.stringify(t))},t.prototype.fromValue=function(t){var e=this;if("nullValue"in t)return On.INSTANCE;if("booleanValue"in t)return Mn.of(t.booleanValue);if("integerValue"in t)return new Un(Ri(t.integerValue));if("doubleValue"in t){if(this.options.useProto3Json){if("NaN"===t.doubleValue)return qn.NAN;if("Infinity"===t.doubleValue)return qn.POSITIVE_INFINITY;if("-Infinity"===t.doubleValue)return qn.NEGATIVE_INFINITY}return new qn(t.doubleValue)}if("stringValue"in t)return new Fn(t.stringValue);if("mapValue"in t)return this.fromFields(t.mapValue.fields||{});if("arrayValue"in t){Ni(t.arrayValue,"arrayValue");var n=t.arrayValue.values||[];return new Gn(n.map(function(t){return e.fromValue(t)}))}if("timestampValue"in t)return Ni(t.timestampValue,"timestampValue"),new Bn(this.fromTimestamp(t.timestampValue));if("geoPointValue"in t){Ni(t.geoPointValue,"geoPointValue");var r=t.geoPointValue.latitude||0,o=t.geoPointValue.longitude||0;return new Wn(new ri(r,o))}if("bytesValue"in t){Ni(t.bytesValue,"bytesValue");var c=this.fromBlob(t.bytesValue);return new jn(c)}if("referenceValue"in t){Ni(t.referenceValue,"referenceValue");var h=this.fromResourceName(t.referenceValue),l=new mt(h.get(1),h.get(3)),f=new Et(this.extractLocalPathFromResourceName(h));return new Qn(l,f)}return T("Unknown Value proto "+JSON.stringify(t))},t.prototype.toMutationDocument=function(t,e){return{name:this.toName(t),fields:this.toFields(e)}},t.prototype.toDocument=function(t){return I(!t.hasLocalMutations,"Can't serialize documents with mutations."),{name:this.toName(t.key),fields:this.toFields(t.data),updateTime:this.toTimestamp(t.version.toTimestamp())}},t.prototype.fromDocument=function(t,e){return new Ie(this.fromName(t.name),this.fromVersion(t.updateTime),this.fromFields(t.fields||{}),{hasCommittedMutations:!!e})},t.prototype.toFields=function(t){var e=this,n={};return t.forEach(function(t,r){n[t]=e.toValue(r)}),n},t.prototype.fromFields=function(object){var t=this,map=object,e=Kn.EMPTY;return P(map,function(n,r){e=e.set(new wt([n]),t.fromValue(r))}),e},t.prototype.toMapValue=function(map){return{fields:this.toFields(map)}},t.prototype.toArrayValue=function(t){var e=this,n=[];return t.forEach(function(t){n.push(e.toValue(t))}),{values:n}},t.prototype.fromFound=function(t){I(!!t.found,"Tried to deserialize a found document from a missing document."),Ni(t.found.name,"doc.found.name"),Ni(t.found.updateTime,"doc.found.updateTime");var e=this.fromName(t.found.name),n=this.fromVersion(t.found.updateTime),r=this.fromFields(t.found.fields||{});return new Ie(e,n,r,{},t.found)},t.prototype.fromMissing=function(t){I(!!t.missing,"Tried to deserialize a missing document from a found document."),I(!!t.readTime,"Tried to deserialize a missing document without a read time.");var e=this.fromName(t.missing),n=this.fromVersion(t.readTime);return new Ce(e,n)},t.prototype.fromMaybeDocument=function(t){return"found"in t?this.fromFound(t):"missing"in t?this.fromMissing(t):T("invalid batch get response: "+JSON.stringify(t))},t.prototype.toWatchTargetChangeState=function(t){switch(t){case Qr.Added:return"ADD";case Qr.Current:return"CURRENT";case Qr.NoChange:return"NO_CHANGE";case Qr.Removed:return"REMOVE";case Qr.Reset:return"RESET";default:return T("Unknown WatchTargetChangeState: "+t)}},t.prototype.toTestWatchChange=function(t){if(t instanceof Yr)return{filter:{count:t.existenceFilter.count,targetId:t.targetId}};if(t instanceof Hr){if(t.newDoc instanceof Ie){var e=t.newDoc;return{documentChange:{document:{name:this.toName(e.key),fields:this.toFields(e.data),updateTime:this.toVersion(e.version)},targetIds:t.updatedTargetIds,removedTargetIds:t.removedTargetIds}}}if(t.newDoc instanceof Ce){e=t.newDoc;return{documentDelete:{document:this.toName(e.key),readTime:this.toVersion(e.version),removedTargetIds:t.removedTargetIds}}}if(null===t.newDoc)return{documentRemove:{document:this.toName(t.key),removedTargetIds:t.removedTargetIds}}}if(t instanceof Xr){var n=void 0;return t.cause&&(n={code:Fr(t.cause.code),message:t.cause.message}),{targetChange:{targetChangeType:this.toWatchTargetChangeState(t.state),targetIds:t.targetIds,resumeToken:this.unsafeCastProtoByteString(t.resumeToken),cause:n}}}return T("Unrecognized watch change: "+JSON.stringify(t))},t.prototype.fromWatchChange=function(t){var e;if("targetChange"in t){Ni(t.targetChange,"targetChange");var n=this.fromWatchTargetChangeState(t.targetChange.targetChangeType||"NO_CHANGE"),r=t.targetChange.targetIds||[],o=t.targetChange.resumeToken||this.emptyByteString(),c=t.targetChange.cause,h=c&&this.fromRpcStatus(c);e=new Xr(n,r,o,h||null)}else if("documentChange"in t){Ni(t.documentChange,"documentChange"),Ni(t.documentChange.document,"documentChange.name"),Ni(t.documentChange.document.name,"documentChange.document.name"),Ni(t.documentChange.document.updateTime,"documentChange.document.updateTime");var l=t.documentChange,f=this.fromName(l.document.name),d=this.fromVersion(l.document.updateTime),m=this.fromFields(l.document.fields||{}),y=new Ie(f,d,m,{},l.document),v=l.targetIds||[],w=l.removedTargetIds||[];e=new Hr(v,w,y.key,y)}else if("documentDelete"in t){Ni(t.documentDelete,"documentDelete"),Ni(t.documentDelete.document,"documentDelete.document");var E=t.documentDelete;f=this.fromName(E.document),d=E.readTime?this.fromVersion(E.readTime):Pt.forDeletedDoc(),y=new Ce(f,d),w=E.removedTargetIds||[];e=new Hr([],w,y.key,y)}else if("documentRemove"in t){Ni(t.documentRemove,"documentRemove"),Ni(t.documentRemove.document,"documentRemove");var S=t.documentRemove;f=this.fromName(S.document),w=S.removedTargetIds||[];e=new Hr([],w,f,null)}else{if(!("filter"in t))return T("Unknown change type "+JSON.stringify(t));Ni(t.filter,"filter"),Ni(t.filter.targetId,"filter.targetId");var filter=t.filter,_=filter.count||0,I=new Ii(_),C=filter.targetId;e=new Yr(C,I)}return e},t.prototype.fromWatchTargetChangeState=function(t){return"NO_CHANGE"===t?Qr.NoChange:"ADD"===t?Qr.Added:"REMOVE"===t?Qr.Removed:"CURRENT"===t?Qr.Current:"RESET"===t?Qr.Reset:T("Got unexpected TargetChange.state: "+t)},t.prototype.versionFromListenResponse=function(t){if(!("targetChange"in t))return Pt.MIN;var e=t.targetChange;return e.targetIds&&e.targetIds.length?Pt.MIN:e.readTime?this.fromVersion(e.readTime):Pt.MIN},t.prototype.toMutation=function(t){var e,n=this;if(t instanceof $n)e={update:this.toMutationDocument(t.key,t.value)};else if(t instanceof nr)e={delete:this.toName(t.key)};else if(t instanceof Zn)e={update:this.toMutationDocument(t.key,t.data),updateMask:this.toDocumentMask(t.fieldMask)};else{if(!(t instanceof er))return T("Unknown mutation type "+t.type);e={transform:{document:this.toName(t.key),fieldTransforms:t.fieldTransforms.map(function(t){return n.toFieldTransform(t)})}}}return t.precondition.isNone||(e.currentDocument=this.toPrecondition(t.precondition)),e},t.prototype.fromMutation=function(t){var e=this,n=t.currentDocument?this.fromPrecondition(t.currentDocument):Xn.NONE;if(t.update){Ni(t.update.name,"name");var r=this.fromName(t.update.name),o=this.fromFields(t.update.fields||{});if(t.updateMask){var c=this.fromDocumentMask(t.updateMask);return new Zn(r,o,c,n)}return new $n(r,o,n)}if(t.delete){r=this.fromName(t.delete);return new nr(r,n)}if(t.transform){r=this.fromName(t.transform.document);var h=t.transform.fieldTransforms.map(function(t){return e.fromFieldTransform(t)});return I(!0===n.exists,'Transforms only support precondition "exists == true"'),new er(r,h)}return T("unknown mutation proto: "+JSON.stringify(t))},t.prototype.toPrecondition=function(t){return I(!t.isNone,"Can't serialize an empty precondition"),void 0!==t.updateTime?{updateTime:this.toVersion(t.updateTime)}:void 0!==t.exists?{exists:t.exists}:T("Unknown precondition")},t.prototype.fromPrecondition=function(t){return void 0!==t.updateTime?Xn.updateTime(this.fromVersion(t.updateTime)):void 0!==t.exists?Xn.exists(t.exists):Xn.NONE},t.prototype.fromWriteResult=function(t,e){var n=this,r=t.updateTime?this.fromVersion(t.updateTime):this.fromVersion(e),o=null;return t.transformResults&&t.transformResults.length>0&&(o=t.transformResults.map(function(t){return n.fromValue(t)})),new Yn(r,o)},t.prototype.fromWriteResults=function(t,e){var n=this;return t&&t.length>0?(I(void 0!==e,"Received a write result without a commit time"),t.map(function(t){return n.fromWriteResult(t,e)})):[]},t.prototype.toFieldTransform=function(t){var e=this,n=t.transform;if(n instanceof vi)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof bi)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements.map(function(t){return e.toValue(t)})}};if(n instanceof wi)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements.map(function(t){return e.toValue(t)})}};if(n instanceof Ei)return{fieldPath:t.field.canonicalString(),increment:this.toValue(n.operand)};throw T("Unknown transform: "+t.transform)},t.prototype.fromFieldTransform=function(t){var e=this,n=null;if("setToServerValue"in t)I("REQUEST_TIME"===t.setToServerValue,"Unknown server value transform proto: "+JSON.stringify(t)),n=vi.instance;else if("appendMissingElements"in t){var r=t.appendMissingElements.values||[];n=new bi(r.map(function(t){return e.fromValue(t)}))}else if("removeAllFromArray"in t){r=t.removeAllFromArray.values||[];n=new wi(r.map(function(t){return e.fromValue(t)}))}else if("increment"in t){var o=this.fromValue(t.increment);I(o instanceof Pn,"NUMERIC_ADD transform requires a NumberValue"),n=new Ei(o)}else T("Unknown transform proto: "+JSON.stringify(t));var c=wt.fromServerFormat(t.fieldPath);return new Hn(c,n)},t.prototype.toDocumentsTarget=function(t){return{documents:[this.toQueryPath(t.path)]}},t.prototype.fromDocumentsTarget=function(t){var e=t.documents.length;I(1===e,"DocumentsTarget contained other than 1 document: "+e);var n=t.documents[0];return ii.atPath(this.fromQueryPath(n))},t.prototype.toQueryTarget=function(t){var e={structuredQuery:{}},path=t.path;null!==t.collectionGroup?(I(path.length%2==0,"Collection Group queries should be within a document path or root."),e.parent=this.toQueryPath(path),e.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(I(path.length%2!=0,"Document queries with filters are not supported."),e.parent=this.toQueryPath(path.popLast()),e.structuredQuery.from=[{collectionId:path.lastSegment()}]);var n=this.toFilter(t.filters);n&&(e.structuredQuery.where=n);var r=this.toOrder(t.orderBy);r&&(e.structuredQuery.orderBy=r);var o=this.toInt32Value(t.limit);return void 0!==o&&(e.structuredQuery.limit=o),t.startAt&&(e.structuredQuery.startAt=this.toCursor(t.startAt)),t.endAt&&(e.structuredQuery.endAt=this.toCursor(t.endAt)),e},t.prototype.fromQueryTarget=function(t){var path=this.fromQueryPath(t.parent),e=t.structuredQuery,n=e.from?e.from.length:0,r=null;if(n>0){I(1===n,"StructuredQuery.from with more than one collection is not supported.");var o=e.from[0];o.allDescendants?r=o.collectionId:path=path.child(o.collectionId)}var c=[];e.where&&(c=this.fromFilter(e.where));var h=[];e.orderBy&&(h=this.fromOrder(e.orderBy));var l=null;e.limit&&(l=this.fromInt32Value(e.limit));var f=null;e.startAt&&(f=this.fromCursor(e.startAt));var d=null;return e.endAt&&(d=this.fromCursor(e.endAt)),new ii(path,r,h,c,l,f,d)},t.prototype.toListenRequestLabels=function(t){var e=this.toLabel(t.purpose);return null==e?null:{"goog-listen-tags":e}},t.prototype.toLabel=function(t){switch(t){case on.Listen:return null;case on.ExistenceFilterMismatch:return"existence-filter-mismatch";case on.LimboResolution:return"limbo-document";default:return T("Unrecognized query purpose: "+t)}},t.prototype.toTarget=function(t){var e,n=t.query;return(e=n.isDocumentQuery()?{documents:this.toDocumentsTarget(n)}:{query:this.toQueryTarget(n)}).targetId=t.targetId,t.resumeToken.length>0&&(e.resumeToken=this.unsafeCastProtoByteString(t.resumeToken)),e},t.prototype.toFilter=function(t){var e=this;if(0!==t.length){var n=t.map(function(filter){return filter instanceof si?e.toUnaryOrFieldFilter(filter):T("Unrecognized filter: "+JSON.stringify(filter))});return 1===n.length?n[0]:{compositeFilter:{op:"AND",filters:n}}}},t.prototype.fromFilter=function(filter){var t=this;return filter?void 0!==filter.unaryFilter?[this.fromUnaryFilter(filter)]:void 0!==filter.fieldFilter?[this.fromFieldFilter(filter)]:void 0!==filter.compositeFilter?filter.compositeFilter.filters.map(function(e){return t.fromFilter(e)}).reduce(function(t,e){return t.concat(e)}):T("Unknown filter: "+JSON.stringify(filter)):[]},t.prototype.toOrder=function(t){var e=this;if(0!==t.length)return t.map(function(t){return e.toPropertyOrder(t)})},t.prototype.fromOrder=function(t){var e=this;return t.map(function(t){return e.fromPropertyOrder(t)})},t.prototype.toCursor=function(cursor){var t=this;return{before:cursor.before,values:cursor.position.map(function(component){return t.toValue(component)})}},t.prototype.fromCursor=function(cursor){var t=this,e=!!cursor.before,n=cursor.values.map(function(component){return t.fromValue(component)});return new di(n,e)},t.prototype.toDirection=function(t){return Ci[t.name]},t.prototype.fromDirection=function(t){switch(t){case"ASCENDING":return pi.ASCENDING;case"DESCENDING":return pi.DESCENDING;default:return}},t.prototype.toOperatorName=function(t){return Di[t.name]},t.prototype.fromOperatorName=function(t){switch(t){case"EQUAL":return ai.EQUAL;case"GREATER_THAN":return ai.GREATER_THAN;case"GREATER_THAN_OR_EQUAL":return ai.GREATER_THAN_OR_EQUAL;case"LESS_THAN":return ai.LESS_THAN;case"LESS_THAN_OR_EQUAL":return ai.LESS_THAN_OR_EQUAL;case"ARRAY_CONTAINS":return ai.ARRAY_CONTAINS;case"IN":return ai.IN;case"ARRAY_CONTAINS_ANY":return ai.ARRAY_CONTAINS_ANY;case"OPERATOR_UNSPECIFIED":return T("Unspecified operator");default:return T("Unknown operator")}},t.prototype.toFieldPathReference=function(path){return{fieldPath:path.canonicalString()}},t.prototype.fromFieldPathReference=function(t){return wt.fromServerFormat(t.fieldPath)},t.prototype.toPropertyOrder=function(t){return{field:this.toFieldPathReference(t.field),direction:this.toDirection(t.dir)}},t.prototype.fromPropertyOrder=function(t){return new mi(this.fromFieldPathReference(t.field),this.fromDirection(t.direction))},t.prototype.fromFieldFilter=function(filter){return si.create(this.fromFieldPathReference(filter.fieldFilter.field),this.fromOperatorName(filter.fieldFilter.op),this.fromValue(filter.fieldFilter.value))},t.prototype.toUnaryOrFieldFilter=function(filter){if(filter.op===ai.EQUAL){if(filter.value.isEqual(qn.NAN))return{unaryFilter:{field:this.toFieldPathReference(filter.field),op:"IS_NAN"}};if(filter.value.isEqual(On.INSTANCE))return{unaryFilter:{field:this.toFieldPathReference(filter.field),op:"IS_NULL"}}}return{fieldFilter:{field:this.toFieldPathReference(filter.field),op:this.toOperatorName(filter.op),value:this.toValue(filter.value)}}},t.prototype.fromUnaryFilter=function(filter){switch(filter.unaryFilter.op){case"IS_NAN":var t=this.fromFieldPathReference(filter.unaryFilter.field);return si.create(t,ai.EQUAL,qn.NAN);case"IS_NULL":var e=this.fromFieldPathReference(filter.unaryFilter.field);return si.create(e,ai.EQUAL,On.INSTANCE);case"OPERATOR_UNSPECIFIED":return T("Unspecified filter");default:return T("Unknown filter")}},t.prototype.toDocumentMask=function(t){var e=[];return t.fields.forEach(function(t){return e.push(t.canonicalString())}),{fieldPaths:e}},t.prototype.fromDocumentMask=function(t){var e=(t.fieldPaths||[]).map(function(path){return wt.fromServerFormat(path)});return zn.fromArray(e)},t}(),Oi=function(){this.listeners=[]},Mi=function(){function t(t){this.syncEngine=t,this.queries=new Ae(function(q){return q.canonicalId()}),this.onlineState=Ir.Unknown,this.syncEngine.subscribe(this)}return t.prototype.listen=function(t){var e=t.query,n=!1,r=this.queries.get(e);return r||(n=!0,r=new Oi,this.queries.set(e,r)),r.listeners.push(t),t.applyOnlineStateChange(this.onlineState),r.viewSnap&&t.onViewSnapshot(r.viewSnap),n?this.syncEngine.listen(e).then(function(t){return r.targetId=t,t}):Promise.resolve(r.targetId)},t.prototype.unlisten=function(t){return l.__awaiter(this,void 0,void 0,function(){var e,n,r,i;return l.__generator(this,function(o){return e=t.query,n=!1,(r=this.queries.get(e))&&(i=r.listeners.indexOf(t))>=0&&(r.listeners.splice(i,1),n=0===r.listeners.length),n?(this.queries.delete(e),[2,this.syncEngine.unlisten(e)]):[2]})})},t.prototype.onWatchChange=function(t){for(var e=0,n=t;e0||t.syncStateChanged,"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.snap&&this.snap.hasPendingWrites!==t.hasPendingWrites;return!(!t.syncStateChanged&&!e)&&!0===this.options.includeMetadataChanges},t.prototype.raiseInitialEvent=function(t){I(!this.raisedInitialEvent,"Trying to raise initial events for second time"),t=Kr.fromInitialDocuments(t.query,t.docs,t.mutatedKeys,t.fromCache),this.raisedInitialEvent=!0,this.queryObserver.next(t)},t}(),Li=function(){function t(t,e,n){this.targetId=t,this.addedKeys=e,this.removedKeys=n}return t.fromSnapshot=function(e,n){for(var r=Yt(),o=Yt(),c=0,h=n.docChanges;c=0,"Got negative number of retries for transaction.");var r=this.remoteStore.createTransaction();return function(){try{var e=t(r);return!Er(e)&&e.catch&&e.then?e.catch(function(t){return Promise.reject(n.wrapUpdateFunctionError(t))}):Promise.reject(Error("Transaction callback must return a Promise"))}catch(t){return Promise.reject(n.wrapUpdateFunctionError(t))}}().then(function(o){return r.commit().then(function(){return o}).catch(function(r){return 0===e?Promise.reject(r):n.runTransaction(t,e-1)})})},t.prototype.applyRemoteEvent=function(t){var e=this;return this.assertSubscribed("applyRemoteEvent()"),this.localStore.applyRemoteEvent(t).then(function(n){return P(t.targetChanges,function(t,n){var r=e.limboResolutionsByTarget[Number(t)];r&&(I(n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size<=1,"Limbo resolution for single document contains multiple changes."),n.addedDocuments.size>0?r.receivedDocument=!0:n.modifiedDocuments.size>0?I(r.receivedDocument,"Received change for limbo target document without add."):n.removedDocuments.size>0&&(I(r.receivedDocument,"Received remove for limbo target document without add."),r.receivedDocument=!1))}),e.emitNewSnapsAndNotifyLocalStore(n,t)}).catch(_n)},t.prototype.applyOnlineStateChange=function(t,source){if(this.isPrimary&&source===Cr.RemoteStore||!this.isPrimary&&source===Cr.SharedClientState){var e=[];this.queryViewsByQuery.forEach(function(n,r){var o=r.view.applyOnlineStateChange(t);I(0===o.limboChanges.length,"OnlineState should not affect limbo documents."),o.snapshot&&e.push(o.snapshot)}),this.syncEngineListener.onOnlineStateChange(t),this.syncEngineListener.onWatchChange(e),this.onlineState=t,this.isPrimary&&this.sharedClientState.setOnlineState(t)}},t.prototype.rejectListen=function(t,e){return l.__awaiter(this,void 0,void 0,function(){var n,r,o,c,h,f,d=this;return l.__generator(this,function(l){switch(l.label){case 0:return this.assertSubscribed("rejectListens()"),this.sharedClientState.updateQueryState(t,"rejected",e),n=this.limboResolutionsByTarget[t],(r=n&&n.key)?(this.limboTargetsByKey=this.limboTargetsByKey.remove(r),delete this.limboResolutionsByTarget[t],o=(o=new Lt(Et.comparator)).insert(r,new Ce(r,Pt.forDeletedDoc())),c=Yt().add(r),h=new Gr(Pt.MIN,{},new Ft(it),o,c),[2,this.applyRemoteEvent(h)]):[3,1];case 1:return I(!!(f=this.queryViewsByTarget[t]),"Unknown targetId: "+t),[4,this.localStore.releaseQuery(f.query,!1).then(function(){return d.removeAndCleanupQuery(f)}).catch(_n)];case 2:l.sent(),this.syncEngineListener.onWatchError(f.query,e),l.label=3;case 3:return[2]}})})},t.prototype.applyBatchState=function(t,e,n){return l.__awaiter(this,void 0,void 0,function(){var r;return l.__generator(this,function(o){switch(o.label){case 0:return this.assertSubscribed("applyBatchState()"),[4,this.localStore.lookupMutationDocuments(t)];case 1:return null===(r=o.sent())?(E("SyncEngine","Cannot apply mutation batch with id: "+t),[2]):"pending"!==e?[3,3]:[4,this.remoteStore.fillWritePipeline()];case 2:return o.sent(),[3,4];case 3:"acknowledged"===e||"rejected"===e?(this.processUserCallback(t,n||null),this.localStore.removeCachedMutationBatchMetadata(t)):T("Unknown batchState: "+e),o.label=4;case 4:return[4,this.emitNewSnapsAndNotifyLocalStore(r)];case 5:return o.sent(),[2]}})})},t.prototype.applySuccessfulWrite=function(t){var e=this;this.assertSubscribed("applySuccessfulWrite()");var n=t.batch.batchId;return this.processUserCallback(n,null),this.localStore.acknowledgeBatch(t).then(function(t){return e.sharedClientState.updateMutationState(n,"acknowledged"),e.emitNewSnapsAndNotifyLocalStore(t)}).catch(_n)},t.prototype.rejectFailedWrite=function(t,e){var n=this;return this.assertSubscribed("rejectFailedWrite()"),this.processUserCallback(t,e),this.localStore.rejectBatch(t).then(function(r){return n.sharedClientState.updateMutationState(t,"rejected",e),n.emitNewSnapsAndNotifyLocalStore(r)}).catch(_n)},t.prototype.addMutationCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];n||(n=new Lt(it)),n=n.insert(t,e),this.mutationUserCallbacks[this.currentUser.toKey()]=n},t.prototype.processUserCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];if(n){var r=n.get(t);r&&(I(t===n.minKey(),"Mutation callbacks processed out-of-order?"),e?r.reject(e):r.resolve(),n=n.remove(t)),this.mutationUserCallbacks[this.currentUser.toKey()]=n}},t.prototype.removeAndCleanupQuery=function(t){var e=this;if(this.sharedClientState.removeLocalQueryTarget(t.targetId),this.queryViewsByQuery.delete(t.query),delete this.queryViewsByTarget[t.targetId],this.isPrimary){var n=this.limboDocumentRefs.referencesForId(t.targetId);this.limboDocumentRefs.removeReferencesForId(t.targetId),n.forEach(function(t){e.limboDocumentRefs.containsKey(t)||e.removeLimboTarget(t)})}},t.prototype.removeLimboTarget=function(t){var e=this.limboTargetsByKey.get(t);null!==e&&(this.remoteStore.unlisten(e),this.limboTargetsByKey=this.limboTargetsByKey.remove(t),delete this.limboResolutionsByTarget[e])},t.prototype.updateTrackedLimbos=function(t,e){for(var n=0,r=e;n() instead."),To=/^__.*__$/,Io=function(){function t(data,t,e){this.data=data,this.fieldMask=t,this.fieldTransforms=e}return t.prototype.toMutations=function(t,e){var n=[];return null!==this.fieldMask?n.push(new Zn(t,this.data,this.fieldMask,e)):n.push(new $n(t,this.data,e)),this.fieldTransforms.length>0&&n.push(new er(t,this.fieldTransforms)),n},t}(),Co=function(){function t(data,t,e){this.data=data,this.fieldMask=t,this.fieldTransforms=e}return t.prototype.toMutations=function(t,e){var n=[new Zn(t,this.data,this.fieldMask,e)];return this.fieldTransforms.length>0&&n.push(new er(t,this.fieldTransforms)),n},t}();function Do(t){switch(t){case yo.Set:case yo.MergeSet:case yo.Update:return!0;case yo.Argument:return!1;default:throw T("Unexpected case for UserDataSource: "+t)}}!function(t){t[t.Set=0]="Set",t[t.Update=1]="Update",t[t.MergeSet=2]="MergeSet",t[t.Argument=3]="Argument"}(yo||(yo={}));var Ao=function(){function t(t,e,path,n,r,o){this.dataSource=t,this.methodName=e,this.path=path,this.arrayElement=n,void 0===r&&this.validatePath(),this.arrayElement=void 0!==n&&n,this.fieldTransforms=r||[],this.fieldMask=o||[]}return t.prototype.childContextForField=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePathSegment(e),r},t.prototype.childContextForFieldPath=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePath(),r},t.prototype.childContextForArray=function(e){return new t(this.dataSource,this.methodName,null,!0,this.fieldTransforms,this.fieldMask)},t.prototype.createError=function(t){var e=null===this.path||this.path.isEmpty()?"":" (found in field "+this.path.toString()+")";return new N(A.INVALID_ARGUMENT,"Function "+this.methodName+"() called with invalid data. "+t+e)},t.prototype.contains=function(t){return void 0!==this.fieldMask.find(function(e){return t.isPrefixOf(e)})||void 0!==this.fieldTransforms.find(function(e){return t.isPrefixOf(e.field)})},t.prototype.validatePath=function(){if(null!==this.path)for(var i=0;i0&&e.fieldMask.push(e.path):P(t,function(t,o){var c=n.parseData(o,e.childContextForField(t));null!=c&&(r=r.insert(t,c))}),new Kn(r)},t.prototype.parseArray=function(t,e){for(var n=[],r=0,o=0,c=t;o0,"FieldValue.delete() at the top level should have already been handled."),e.createError("FieldValue.delete() can only appear at the top level of your update data")):e.createError("FieldValue.delete() cannot be used with set() unless you pass {merge:true}");e.fieldMask.push(e.path)}else if(t instanceof bo)e.fieldTransforms.push(new Hn(e.path,vi.instance));else if(t instanceof wo){var n=this.parseArrayTransformElements(t._methodName,t._elements),r=new bi(n);e.fieldTransforms.push(new Hn(e.path,r))}else if(t instanceof Eo){n=this.parseArrayTransformElements(t._methodName,t._elements);var o=new wi(n);e.fieldTransforms.push(new Hn(e.path,o))}else if(t instanceof So){var c=this.parseQueryValue("FieldValue.increment",t._operand),h=new Ei(c);e.fieldTransforms.push(new Hn(e.path,h))}else T("Unknown FieldValue type: "+t)},t.prototype.parseScalarValue=function(t,e){if(null===t)return On.INSTANCE;if("number"==typeof t)return Sr(t)?new Un(t):new qn(t);if("boolean"==typeof t)return Mn.of(t);if("string"==typeof t)return new Fn(t);if(t instanceof Date)return new Bn(Mt.fromDate(t));if(t instanceof Mt)return new Bn(new Mt(t.seconds,1e3*Math.floor(t.nanoseconds/1e3)));if(t instanceof ri)return new Wn(t);if(t instanceof ht)return new jn(t);if(t instanceof No)return new Qn(t.databaseId,t.key);throw e.createError("Unsupported field value: "+X(t))},t.prototype.parseArrayTransformElements=function(t,e){var n=this;return e.map(function(element,i){var e=new Ao(yo.Argument,t,wt.EMPTY_PATH);return n.parseData(element,e.childContextForArray(i))})},t}();function ko(input){return!("object"!=typeof input||null===input||input instanceof Array||input instanceof Date||input instanceof Mt||input instanceof ri||input instanceof ht||input instanceof No||input instanceof go)}function Oo(t,e,input){if(!ko(input)||!Y(input)){var n=X(input);throw"an object"===n?e.createError(t+" a custom object"):e.createError(t+" "+n)}}function Mo(t,path){if(path instanceof ao)return path._internalPath;if("string"==typeof path)return Po(t,path);throw new N(A.INVALID_ARGUMENT,"Function "+t+"() called with invalid data. Field path arguments must be of type string or FieldPath.")}function Po(t,path){try{return function(path){if(path.search(so)>=0)throw new N(A.INVALID_ARGUMENT,"Invalid field path ("+path+"). Paths must not contain '~', '*', '/', '[', or ']'");try{return new(ao.bind.apply(ao,[void 0].concat(path.split("."))))}catch(t){throw new N(A.INVALID_ARGUMENT,"Invalid field path ("+path+"). Paths must not be empty, begin with '.', end with '.', or contain '..'")}}(path)._internalPath}catch(n){var e=Lo(n);throw new N(A.INVALID_ARGUMENT,"Function "+t+"() called with invalid data. "+e)}}function Lo(t){return t instanceof Error?t.message:t.toString()}var xo="firestore.googleapis.com",Uo=!0,qo=!0,Fo=!1,Bo=dn.COLLECTION_DISABLED,Vo=function(){function t(t){if(void 0===t.host){if(void 0!==t.ssl)throw new N(A.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=xo,this.ssl=Uo}else Q("settings","non-empty string","host",t.host),this.host=t.host,W("settings","boolean","ssl",t.ssl),this.ssl=O(t.ssl,Uo);if($("settings",t,["host","ssl","credentials","timestampsInSnapshots","cacheSizeBytes","experimentalForceLongPolling"]),W("settings","object","credentials",t.credentials),this.credentials=t.credentials,W("settings","boolean","timestampsInSnapshots",t.timestampsInSnapshots),!0===t.timestampsInSnapshots?S("\n The timestampsInSnapshots setting now defaults to true and you no\n longer need to explicitly set it. In a future release, the setting\n will be removed entirely and so it is recommended that you remove it\n from your firestore.settings() call now."):!1===t.timestampsInSnapshots&&S("\n The timestampsInSnapshots setting will soon be removed. YOU MUST UPDATE\n YOUR CODE.\n\n To hide this warning, stop using the timestampsInSnapshots setting in your\n firestore.settings({ ... }) call.\n\n Once you remove the setting, Timestamps stored in Cloud Firestore will be\n read back as Firebase Timestamp objects instead of as system Date objects.\n So you will also need to update code expecting a Date to instead expect a\n Timestamp. For example:\n\n // Old:\n const date = snapshot.get('created_at');\n // New:\n const timestamp = snapshot.get('created_at'); const date =\n timestamp.toDate();\n\n Please audit all existing usages of Date when you enable the new\n behavior."),this.timestampsInSnapshots=O(t.timestampsInSnapshots,qo),W("settings","number","cacheSizeBytes",t.cacheSizeBytes),void 0===t.cacheSizeBytes)this.cacheSizeBytes=dn.DEFAULT_CACHE_SIZE_BYTES;else{if(t.cacheSizeBytes!==Bo&&t.cacheSizeBytes=0)throw new N(A.INVALID_ARGUMENT,"Invalid collection ID '"+t+"' passed to function Firestore.collectionGroup(). Collection IDs must not contain '/'.");return this.ensureClientConfigured(),new Xo(new ii(vt.EMPTY_PATH,t),this)},t.prototype.runTransaction=function(t){var e=this;return U("Firestore.runTransaction",arguments,1),V("Firestore.runTransaction","function",1,t),this.ensureClientConfigured().transaction(function(n){return t(new Wo(e,n))})},t.prototype.batch=function(){return this.ensureClientConfigured(),new Ko(this)},Object.defineProperty(t,"logLevel",{get:function(){switch(v()){case o.DEBUG:return"debug";case o.ERROR:return"error";case o.SILENT:return"silent";default:return T("Unknown log level: "+v())}},enumerable:!0,configurable:!0}),t.setLogLevel=function(t){switch(U("Firestore.setLogLevel",arguments,1),V("Firestore.setLogLevel","non-empty string",1,t),t){case"debug":w(o.DEBUG);break;case"error":w(o.ERROR);break;case"silent":w(o.SILENT);break;default:throw new N(A.INVALID_ARGUMENT,"Invalid log level: "+t)}},t.prototype._areTimestampsInSnapshotsEnabled=function(){return this._config.settings.timestampsInSnapshots},t}(),Wo=function(){function t(t,e){this._firestore=t,this._transaction=e}return t.prototype.get=function(t){var e=this;U("Transaction.get",arguments,1);var n=na("Transaction.get",t,this._firestore);return this._transaction.lookup([n._key]).then(function(t){if(!t||1!==t.length)return T("Mismatch in docs returned from document lookup.");var r=t[0];if(r instanceof Ce)return new Ho(e._firestore,n._key,null,!1,!1);if(r instanceof Ie)return new Ho(e._firestore,n._key,r,!1,!1);throw T("BatchGetDocumentsRequest returned unexpected document type: "+r.constructor.name)})},t.prototype.set=function(t,e,n){B("Transaction.set",arguments,2,3);var r=na("Transaction.set",t,this._firestore),o=(n=Zo("Transaction.set",n)).merge||n.mergeFields?this._firestore._dataConverter.parseMergeData("Transaction.set",e,n.mergeFields):this._firestore._dataConverter.parseSetData("Transaction.set",e);return this._transaction.set(r._key,o),this},t.prototype.update=function(t,e,n){for(var r,o,c=[],h=3;h0?[2,this._firestore.ensureClientConfigured().write(this._mutations)]:[2]})})},t.prototype.verifyNotCommitted=function(){if(this._committed)throw new N(A.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")},t}(),Go=function(){function t(t,e){this._key=t,this.firestore=e,this._firestoreClient=this.firestore.ensureClientConfigured()}return t.forPath=function(path,e){if(path.length%2!=0)throw new N(A.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but "+path.canonicalString()+" has "+path.length);return new t(new Et(path),e)},Object.defineProperty(t.prototype,"id",{get:function(){return this._key.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return new $o(this._key.path.popLast(),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"path",{get:function(){return this._key.path.canonicalString()},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(U("DocumentReference.collection",arguments,1),V("DocumentReference.collection","non-empty string",1,t),!t)throw new N(A.INVALID_ARGUMENT,"Must provide a non-empty collection name to collection()");var path=vt.fromString(t);return new $o(this._key.path.child(path),this.firestore)},t.prototype.isEqual=function(e){if(!(e instanceof t))throw Z("isEqual","DocumentReference",1,e);return this.firestore===e.firestore&&this._key.isEqual(e._key)},t.prototype.set=function(t,e){B("DocumentReference.set",arguments,1,2);var n=(e=Zo("DocumentReference.set",e)).merge||e.mergeFields?this.firestore._dataConverter.parseMergeData("DocumentReference.set",t,e.mergeFields):this.firestore._dataConverter.parseSetData("DocumentReference.set",t);return this._firestoreClient.write(n.toMutations(this._key,Xn.NONE))},t.prototype.update=function(t,e){for(var n,r=[],o=2;o=",">","array-contains"];z("Query.where",o,2,n)}var c,h=Mo("Query.where",e),l=ai.fromString(n);if(h.isKeyField()){if(l===ai.ARRAY_CONTAINS||l===ai.ARRAY_CONTAINS_ANY||l===ai.IN)throw new N(A.INVALID_ARGUMENT,"Invalid Query. You can't perform '"+l.toString()+"' queries on FieldPath.documentId().");if("string"==typeof r){if(""===r)throw new N(A.INVALID_ARGUMENT,"Function Query.where() requires its third parameter to be a valid document ID if the first parameter is FieldPath.documentId(), but it was an empty string.");if(!this._query.isCollectionGroupQuery()&&-1!==r.indexOf("/"))throw new N(A.INVALID_ARGUMENT,"Invalid third parameter to Query.where(). When querying a collection by FieldPath.documentId(), the value provided must be a plain document ID, but '"+r+"' contains a slash.");var path=this._query.path.child(vt.fromString(r));if(!Et.isDocumentKey(path))throw new N(A.INVALID_ARGUMENT,"Invalid third parameter to Query.where(). When querying a collection group by FieldPath.documentId(), the value provided must result in a valid document path, but '"+path+"' is not because it has an odd number of segments ("+path.length+").");c=new Qn(this.firestore._databaseId,new Et(path))}else{if(!(r instanceof Go))throw new N(A.INVALID_ARGUMENT,"Function Query.where() requires its third parameter to be a string or a DocumentReference if the first parameter is FieldPath.documentId(), but it was: "+X(r)+".");var f=r;c=new Qn(this.firestore._databaseId,f._key)}}else{if(l===ai.IN||l===ai.ARRAY_CONTAINS_ANY){if(!Array.isArray(r)||0===r.length)throw new N(A.INVALID_ARGUMENT,"Invalid Query. A non-empty array is required for '"+l.toString()+"' filters.");if(r.length>10)throw new N(A.INVALID_ARGUMENT,"Invalid Query. '"+l.toString()+"' filters support a maximum of 10 elements in the value array.")}c=this.firestore._dataConverter.parseQueryValue("Query.where",r)}var filter=si.create(h,l,c);return this.validateNewFilter(filter),new t(this._query.addFilter(filter),this.firestore)},t.prototype.orderBy=function(e,n){var r;if(B("Query.orderBy",arguments,1,2),j("Query.orderBy","non-empty string",2,n),void 0===n||"asc"===n)r=pi.ASCENDING;else{if("desc"!==n)throw new N(A.INVALID_ARGUMENT,"Function Query.orderBy() has unknown direction '"+n+"', expected 'asc' or 'desc'.");r=pi.DESCENDING}if(null!==this._query.startAt)throw new N(A.INVALID_ARGUMENT,"Invalid query. You must not call Query.startAt() or Query.startAfter() before calling Query.orderBy().");if(null!==this._query.endAt)throw new N(A.INVALID_ARGUMENT,"Invalid query. You must not call Query.endAt() or Query.endBefore() before calling Query.orderBy().");var o=Mo("Query.orderBy",e),c=new mi(o,r);return this.validateNewOrderBy(c),new t(this._query.addOrderBy(c),this.firestore)},t.prototype.limit=function(e){if(U("Query.limit",arguments,1),V("Query.limit","number",1,e),e<=0)throw new N(A.INVALID_ARGUMENT,"Invalid Query. Query limit ("+e+") is invalid. Limit must be positive.");return new t(this._query.withLimit(e),this.firestore)},t.prototype.startAt=function(e){for(var n=[],r=1;r0)throw new N(A.INVALID_ARGUMENT,"Too many arguments provided to "+t+"().");var o=e;if(!o.exists)throw new N(A.NOT_FOUND,"Can't use a DocumentSnapshot that doesn't exist for "+t+"().");return this.boundFromDocument(t,o._document,r)}var c=[e].concat(n);return this.boundFromFields(t,c,r)},t.prototype.boundFromDocument=function(t,e,n){for(var r=[],o=0,c=this._query.orderBy;or.length)throw new N(A.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 o=[],i=0;i=0,r=e.indexOf(filter.op)>=0;if(filter.isInequality()){var o=this._query.getInequalityFilterField();if(null!==o&&!o.isEqual(filter.field))throw new N(A.INVALID_ARGUMENT,"Invalid query. All where filters with an inequality (<, <=, >, or >=) must be on the same field. But you have inequality filters on '"+o.toString()+"' and '"+filter.field.toString()+"'");var c=this._query.getFirstOrderByField();null!==c&&this.validateOrderByAndInequalityMatch(filter.field,c)}else if(r||n){var h=null;if(r&&(h=this._query.findFilterOperator(e)),null===h&&n&&(h=this._query.findFilterOperator(t)),null!=h)throw h===filter.op?new N(A.INVALID_ARGUMENT,"Invalid query. You cannot use more than one '"+filter.op.toString()+"' filter."):new N(A.INVALID_ARGUMENT,"Invalid query. You cannot use '"+filter.op.toString()+"' filters with '"+h.toString()+"' filters.")}}},t.prototype.validateNewOrderBy=function(t){if(null===this._query.getFirstOrderByField()){var e=this._query.getInequalityFilterField();null!==e&&this.validateOrderByAndInequalityMatch(e,t.field)}},t.prototype.validateOrderByAndInequalityMatch=function(t,e){if(!e.isEqual(t))throw new N(A.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}(),Jo=function(){function t(t,e,n){this._firestore=t,this._originalQuery=e,this._snapshot=n,this._cachedChanges=null,this._cachedChangesIncludeMetadataChanges=null,this.metadata=new zo(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._snapshot.docs.isEmpty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"size",{get:function(){return this._snapshot.docs.size},enumerable:!0,configurable:!0}),t.prototype.forEach=function(t,e){var n=this;B("QuerySnapshot.forEach",arguments,1,2),V("QuerySnapshot.forEach","function",1,t),this._snapshot.docs.forEach(function(r){t.call(e,n.convertToDocumentImpl(r))})},Object.defineProperty(t.prototype,"query",{get:function(){return new Xo(this._originalQuery,this._firestore)},enumerable:!0,configurable:!0}),t.prototype.docChanges=function(t){t&&($("QuerySnapshot.docChanges",t,["includeMetadataChanges"]),W("QuerySnapshot.docChanges","boolean","includeMetadataChanges",t.includeMetadataChanges));var e=!(!t||!t.includeMetadataChanges);if(e&&this._snapshot.excludesMetadataChanges)throw new N(A.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===e||(this._cachedChanges=function(t,e,n){if(n.oldDocs.isEmpty()){var r,o=0;return n.docChanges.map(function(e){var c=new Yo(t,e.doc.key,e.doc,n.fromCache,n.mutatedKeys.has(e.doc.key));return I(e.type===Br.Added,"Invalid event type for first snapshot"),I(!r||n.query.docComparator(r,e.doc)<0,"Got added events in wrong order"),r=e.doc,{type:"added",doc:c,oldIndex:-1,newIndex:o++}})}var c=n.oldDocs;return n.docChanges.filter(function(t){return e||t.type!==Br.Metadata}).map(function(e){var r=new Yo(t,e.doc.key,e.doc,n.fromCache,n.mutatedKeys.has(e.doc.key)),o=-1,h=-1;return e.type!==Br.Added&&(I((o=c.indexOf(e.doc.key))>=0,"Index for document not found"),c=c.delete(e.doc.key)),e.type!==Br.Removed&&(c=c.add(e.doc),h=c.indexOf(e.doc.key)),{type:ra(e.type),doc:r,oldIndex:o,newIndex:h}})}(this._firestore,e,this._snapshot),this._cachedChangesIncludeMetadataChanges=e),this._cachedChanges},t.prototype.isEqual=function(e){if(!(e instanceof t))throw Z("isEqual","QuerySnapshot",1,e);return this._firestore===e._firestore&&this._originalQuery.isEqual(e._originalQuery)&&this._snapshot.isEqual(e._snapshot)},t.prototype.convertToDocumentImpl=function(t){return new Yo(this._firestore,t.key,t,this.metadata.fromCache,this._snapshot.mutatedKeys.has(t.key))},t}();["length","forEach","map"].concat("undefined"!=typeof Symbol?[Symbol.iterator]:[]).forEach(function(t){try{Object.defineProperty(Jo.prototype.docChanges,t,{get:function(){return function(){throw new N(A.INVALID_ARGUMENT,'QuerySnapshot.docChanges has been changed from a property into a method, so usages like "querySnapshot.docChanges" should become "querySnapshot.docChanges()"')}()}})}catch(t){}});var $o=function(t){function e(path,e){var n=t.call(this,ii.atPath(path),e)||this;if(path.length%2!=1)throw new N(A.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but "+path.canonicalString()+" has "+path.length);return n}return l.__extends(e,t),Object.defineProperty(e.prototype,"id",{get:function(){return this._query.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){var t=this._query.path.popLast();return t.isEmpty()?null:new Go(new Et(t),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return this._query.path.canonicalString()},enumerable:!0,configurable:!0}),e.prototype.doc=function(t){if(B("CollectionReference.doc",arguments,0,1),0===arguments.length&&(t=nt.newId()),V("CollectionReference.doc","non-empty string",1,t),""===t)throw new N(A.INVALID_ARGUMENT,"Document path must be a non-empty string");var path=vt.fromString(t);return Go.forPath(this._query.path.child(path),this.firestore)},e.prototype.add=function(t){U("CollectionReference.add",arguments,1),V("CollectionReference.add","object",1,t);var e=this.doc();return e.set(t).then(function(){return e})},e}(Xo);function Zo(t,e){if(void 0===e)return{merge:!1};if($(t,e,["merge","mergeFields"]),W(t,"boolean","merge",e.merge),K(t,"mergeFields","a string or a FieldPath",e.mergeFields,function(element){return"string"==typeof element||element instanceof ao}),void 0!==e.mergeFields&&void 0!==e.merge)throw new N(A.INVALID_ARGUMENT,"Invalid options passed to function "+t+'(): You cannot specify both "merge" and "mergeFields".');return e}function ta(t,e){return void 0===e?{}:($(t,e,["serverTimestamps"]),G(t,0,"serverTimestamps",e.serverTimestamps,["estimate","previous","none"]),e)}function ea(t,e){j(t,"object",1,e),e&&($(t,e,["source"]),G(t,0,"source",e.source,["default","server","cache"]))}function na(t,e,n){if(e instanceof Go){if(e.firestore!==n)throw new N(A.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}throw Z(t,"DocumentReference",1,e)}function ra(t){switch(t){case Br.Added:return"added";case Br.Modified:case Br.Metadata:return"modified";case Br.Removed:return"removed";default:return T("Unknown change type: "+t)}}var ia=R(Qo,"Use firebase.firestore() instead."),oa=R(Wo,"Use firebase.firestore().runTransaction() instead."),aa=R(Ko,"Use firebase.firestore().batch() instead."),sa=R(Go,"Use firebase.firestore().doc() instead."),ua=R(Ho),ca=R(Yo),ha=R(Xo),la=R(Jo),fa=R($o,"Use firebase.firestore().collection() instead."),pa={Firestore:ia,GeoPoint:ri,Timestamp:Mt,Blob:lt,Transaction:oa,WriteBatch:aa,DocumentReference:sa,DocumentSnapshot:ua,Query:ha,QueryDocumentSnapshot:ca,QuerySnapshot:la,CollectionReference:fa,FieldPath:ao,FieldValue:_o,setLogLevel:Qo.setLogLevel,CACHE_SIZE_UNLIMITED:Bo};function da(t){t.INTERNAL.registerService("firestore",function(t){return new Qo(t)},function(t){I(t&&"object"==typeof t,"shallowCopy() expects object parameter.");var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}(pa))}var ma=function(){function t(){}return t.prototype.addCallback=function(t){},t.prototype.shutdown=function(){},t}(),ya=function(){function t(){var t=this;this.networkAvailableListener=function(){return t.onNetworkAvailable()},this.networkUnavailableListener=function(){return t.onNetworkUnavailable()},this.callbacks=[],this.configureNetworkMonitoring()}return t.prototype.addCallback=function(t){this.callbacks.push(t)},t.prototype.shutdown=function(){window.removeEventListener("online",this.networkAvailableListener),window.removeEventListener("offline",this.networkUnavailableListener)},t.prototype.configureNetworkMonitoring=function(){window.addEventListener("online",this.networkAvailableListener),window.addEventListener("offline",this.networkUnavailableListener)},t.prototype.onNetworkAvailable=function(){E("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(var t=0,e=this.callbacks;t0?h(new N(function(t){switch(t){case 200:return A.OK;case 400:return A.INVALID_ARGUMENT;case 401:return A.UNAUTHENTICATED;case 403:return A.PERMISSION_DENIED;case 404:return A.NOT_FOUND;case 409:return A.ABORTED;case 416:return A.OUT_OF_RANGE;case 429:return A.RESOURCE_EXHAUSTED;case 499:return A.CANCELLED;case 500:return A.UNKNOWN;case 501:return A.UNIMPLEMENTED;case 503:return A.UNAVAILABLE;case 504:return A.DEADLINE_EXCEEDED;default:return t>=200&&t<300?A.OK:t>=400&&t<500?A.FAILED_PRECONDITION:t>=500&&t<600?A.INTERNAL:A.UNKNOWN}}(n),"Server responded with status "+l.getStatusText())):(E(va,'RPC "'+t+'" failed'),h(new N(A.UNAVAILABLE,"Connection failed.")));break;default:T('RPC "'+t+'" failed with unanticipated webchannel error '+l.getLastErrorCode()+": "+l.getLastError()+", giving up.")}}finally{E(va,'RPC "'+t+'" completed.')}});var f=JSON.stringify(e);E(va,"XHR sending: ",o+" "+f);var m={"Content-Type":"text/plain"};r.modifyHeadersForRequest(m,n),l.send(o,"POST",f,m,15)})},t.prototype.invokeStreamingRPC=function(t,e,n){return this.invokeRPC(t,e,n)},t.prototype.openStream=function(t,e){var n=[this.baseUrl,"/","google.firestore.v1.Firestore","/",t,"/channel"],r=d.createWebChannelTransport(),o={backgroundChannelTest:!0,httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:"projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling};this.modifyHeadersForRequest(o.initMessageHeaders,e),f.isReactNative()||(o.httpHeadersOverwriteParam="$httpHeaders");var c=n.join("");E(va,"Creating WebChannel: "+c+" "+o);var h=r.createWebChannel(c,o),l=!1,m=!1,y=new ga({sendFn:function(t){m?E(va,"Not sending because WebChannel is closed:",t):(l||(E(va,"Opening WebChannel transport."),h.open(),l=!0),E(va,"WebChannel sending:",t),h.send(t))},closeFn:function(){return h.close()}}),v=function(t,e){h.listen(t,function(param){try{e(param)}catch(t){setTimeout(function(){throw t},0)}})};return v(d.WebChannel.EventType.OPEN,function(){m||E(va,"WebChannel transport opened.")}),v(d.WebChannel.EventType.CLOSE,function(){m||(m=!0,E(va,"WebChannel transport closed"),y.callOnClose())}),v(d.WebChannel.EventType.ERROR,function(t){m||(m=!0,E(va,"WebChannel transport errored:",t),y.callOnClose(new N(A.UNAVAILABLE,"The operation could not be completed")))}),v(d.WebChannel.EventType.MESSAGE,function(t){if(!m){var e=t.data[0];I(!!e,"Got a webchannel message without data.");var n=e,r=n.error||n[0]&&n[0].error;if(r){E(va,"WebChannel received error:",r);var o=r.status,code=function(t){var code=Lr[t];if(void 0!==code)return qr(code)}(o),c=r.message;void 0===code&&(code=A.INTERNAL,c="Unknown error status: "+o+" with message "+r.message),m=!0,y.callOnClose(new N(code,c)),h.close()}else E(va,"WebChannel received:",e),y.callOnMessage(e)}}),setTimeout(function(){y.callOnOpen()},0),y},t.prototype.makeUrl=function(t){var e=ba[t];I(void 0!==e,"Unknown REST mapping for: "+t);var n=[this.baseUrl,"/","v1"];return n.push("/projects/"),n.push(this.databaseId.projectId),n.push("/databases/"),n.push(this.databaseId.database),n.push("/documents"),n.push(":"),n.push(e),n.join("")},t}(),Sa=function(){function t(){this.emptyByteString="",this.base64Available="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.loadConnection=function(t){return Promise.resolve(new Ea(t))},t.prototype.newConnectivityMonitor=function(){return ya.isAvailable()?new ya:new ma},t.prototype.newSerializer=function(t){return new ki(t,{useProto3Json:!0})},t.prototype.formatJSON=function(t){return JSON.stringify(t)},t.prototype.atob=function(t){return atob(t)},t.prototype.btoa=function(t){return btoa(t)},t}();function _a(t){da(t)}C.setPlatform(new Sa),_a(c),e.registerFirestore=_a}).call(this,n(95))},165:function(t,e,n){"use strict";n.r(e),function(t){n.d(e,"ErrorCode",function(){return dr}),n.d(e,"EventType",function(){return mr}),n.d(e,"WebChannel",function(){return yr}),n.d(e,"XhrIo",function(){return gr}),n.d(e,"createWebChannelTransport",function(){return pr});var g,r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==t?t:"undefined"!=typeof self?self:{},o=o||{},c=r;function h(a){return"string"==typeof a}function l(a){return"number"==typeof a}function f(a,b){a=a.split("."),b=b||c;for(var t=0;t>>0),w=0;function E(a,b,t){return a.call.apply(a.bind,arguments)}function S(a,b,t){if(!a)throw Error();if(2b?1:0}t:{var x=c.navigator;if(x){var U=x.userAgent;if(U){O=U;break t}}O=""}function F(a,b,t){for(var e in a)b.call(t,a[e],e,a)}function B(a){var t,b={};for(t in a)b[t]=a[t];return b}var V="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function j(a,b){for(var t,e,n=1;nparseFloat($)){W=String(tt);break t}}W=$}var et,nt={};function it(a){return function(a,b){var t=nt;return Object.prototype.hasOwnProperty.call(t,a)?t[a]:t[a]=b(a)}(a,function(){for(var b=0,t=M(String(W)).split("."),e=M(String(a)).split("."),n=Math.max(t.length,e.length),r=0;0==b&&r=a.keyCode)&&(a.keyCode=-1)}catch(t){}};var ft="closure_listenable_"+(1e6*Math.random()|0),pt=0;function mt(a,b,t,e,n){this.listener=a,this.proxy=null,this.src=b,this.type=t,this.capture=!!e,this.da=n,this.key=++pt,this.X=this.Z=!1}function yt(a){a.X=!0,a.listener=null,a.proxy=null,a.src=null,a.da=null}function gt(a){this.src=a,this.a={},this.b=0}function vt(a,b){var t=b.type;if(t in a.a){var e,n=a.a[t],r=D(n,b);(e=0<=r)&&Array.prototype.splice.call(n,r,1),e&&(yt(b),0==a.a[t].length&&(delete a.a[t],a.b--))}}function bt(a,b,t,e){for(var n=0;n>>0);function Rt(a){return"function"==p(a)?a:(a[Nt]||(a[Nt]=function(b){return a.handleEvent(b)}),a[Nt])}function kt(){C.call(this),this.c=new gt(this),this.J=this,this.B=null}function Ot(a,b,t,e){if(!(b=a.c.a[String(b)]))return!0;b=b.concat();for(var n=!0,r=0;rb.b&&(b.b++,a.next=b.a,b.a=a)}jt=!1}function Kt(a,b){kt.call(this),this.b=a||1,this.a=b||c,this.f=u(this.gb,this),this.g=T()}function Gt(a){a.ba=!1,a.L&&(a.a.clearTimeout(a.L),a.L=null)}function zt(a,b,t){if("function"==p(a))t&&(a=u(a,t));else{if(!a||"function"!=typeof a.handleEvent)throw Error("Invalid listener argument");a=u(a.handleEvent,a)}return 2147483647b.length?Ee:(b=b.substr(e,t),a.A=e+t,b))}function De(a){a.R=T()+a.O,Ae(a,a.O)}function Ae(a,b){if(null!=a.i)throw Error("WatchDog timer not null");a.i=se(u(a.bb,a),b)}function Ne(a){a.i&&(c.clearTimeout(a.i),a.i=null)}function Re(a){a.g.Da()||a.m||a.g.na(a)}function ke(a){Ne(a);var b=a.B;b&&"function"==typeof b.la&&b.la(),a.B=null,Gt(a.P),Zt(a.I),a.a&&(b=a.a,a.a=null,b.abort(),b.la())}function Oe(a,b){try{a.g.Ga(a,b),re(4)}catch(t){}}function Me(a,b){if(a.forEach&&"function"==typeof a.forEach)a.forEach(b,void 0);else if(m(a)||h(a))A(a,b,void 0);else{if(a.K&&"function"==typeof a.K)var t=a.K();else if(a.C&&"function"==typeof a.C)t=void 0;else if(m(a)||h(a)){t=[];for(var e=a.length,n=0;n2*a.c&&xe(a))}function xe(a){if(a.c!=a.a.length){for(var b=0,t=0;bb||3==b&&!H&&!this.a.aa())){this.m||4!=b||7==t||re(8==t||0>=e?3:2),Ne(this);var n=this.a.T();this.o=n;var r=this.a.aa();if(this.b=200==n){if(this.S&&!this.s){e:{if(this.a){var o=Fn(this.a,"X-HTTP-Initial-Response");if(o&&!k(o)){var c=o;break e}}c=null}if(!c){this.b=!1,this.c=3,oe(12),ke(this),Re(this);break t}this.s=!0,Oe(this,c)}this.H?(Ie(this,b,r),H&&this.b&&3==b&&($t(this.I,this.P,"tick",this.cb),this.P.start())):Oe(this,r),4==b&&ke(this),this.b&&!this.m&&(4==b?this.g.na(this):(this.b=!1,De(this)))}else 400==n&&0b)throw Error("Bad port number "+b);a.i=b}else a.i=null}function We(a,b,t){b instanceof nn?(a.c=b,function(a,b){b&&!a.f&&(rn(a),a.c=null,a.a.forEach(function(t,e){var n=e.toLowerCase();e!=n&&(on(this,e),sn(this,n,t))},a)),a.f=b}(a.c,a.h)):(t||(b=Ye(b,tn)),a.c=new nn(b,a.h))}function Ke(a,b,t){a.c.set(b,t)}function Ge(a,b,t){q(t)||(t=[String(t)]),sn(a.c,b,t)}function ze(a){return Ke(a,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^T()).toString(36)),a}function He(a,b){return a?b?decodeURI(a.replace(/%25/g,"%2525")):decodeURIComponent(a):""}function Ye(a,b,t){return h(a)?(a=encodeURI(a).replace(b,Xe),t&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),a):null}function Xe(a){return"%"+((a=a.charCodeAt(0))>>4&15).toString(16)+(15&a).toString(16)}Fe.prototype.toString=function(){var a=[],b=this.f;b&&a.push(Ye(b,Je,!0),":");var t=this.b;return(t||"file"==b)&&(a.push("//"),(b=this.j)&&a.push(Ye(b,Je,!0),"@"),a.push(encodeURIComponent(String(t)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(t=this.i)&&a.push(":",String(t))),(t=this.a)&&(this.b&&"/"!=t.charAt(0)&&a.push("/"),a.push(Ye(t,"/"==t.charAt(0)?Ze:$e,!0))),(t=this.c.toString())&&a.push("?",t),(t=this.g)&&a.push("#",Ye(t,en)),a.join("")},Fe.prototype.resolve=function(a){var b=Be(this),t=!!a.f;t?Ve(b,a.f):t=!!a.j,t?b.j=a.j:t=!!a.b,t?je(b,a.b):t=null!=a.i;var e=a.a;if(t)Qe(b,a.i);else if(t=!!a.a){if("/"!=e.charAt(0))if(this.b&&!this.a)e="/"+e;else{var n=b.a.lastIndexOf("/");-1!=n&&(e=b.a.substr(0,n+1)+e)}if(".."==(n=e)||"."==n)e="";else if(P(n,"./")||P(n,"/.")){e=0==n.lastIndexOf("/",0),n=n.split("/");for(var r=[],o=0;o=a.f}function wn(a){return a.b?1:a.a?a.a.a.c:0}function En(a,b){return a.b?a=a.b==b:a.a?(b=dn(b),a=Ue(a.a.a.b,b)):a=!1,a}function dd(a,b){a.a?a.a.add(b):a.b=b}function Sn(a,b){var t;a.b&&a.b==b?a.b=null:((t=a.a)&&(t=dn(b),t=Ue(a.a.a.b,t)),t&&Le(a.a.a,dn(b)))}function _n(a){if(null!=a.b)return a.c.concat(a.b.j);if(null!=a.a&&0!=a.a.a.c){var b=a.c;return A(a.a.C(),function(t){b=b.concat(t.j)}),b}return R(a.c)}function Tn(){}function In(){this.a=new Tn}function Cn(a,b,t){var e=t||"";try{Me(a,function(t,n){var r=t;y(t)&&(r=Mt(t)),b.push(e+n+"="+encodeURIComponent(r))})}catch(t){throw b.push(e+"type="+encodeURIComponent("_badmap")),t}}function Dn(a,b,t,e,n){try{b.onload=null,b.onerror=null,b.onabort=null,b.ontimeout=null,n(e)}catch(t){}}yn.prototype.cancel=function(){this.c=_n(this),this.b?(this.b.cancel(),this.b=null):this.a&&0!=this.a.a.c&&(A(this.a.C(),function(a){a.cancel()}),function(a){a.b={},a.a.length=0,a.c=0}(this.a.a))},Tn.prototype.stringify=function(a){return c.JSON.stringify(a,void 0)},Tn.prototype.parse=function(a){return c.JSON.parse(a,void 0)};var An=c.JSON.parse;function Nn(a){kt.call(this),this.headers=new Pe,this.H=a||null,this.b=!1,this.s=this.a=null,this.A="",this.h=0,this.f="",this.g=this.w=this.l=this.v=!1,this.o=0,this.m=null,this.I=Rn,this.D=this.F=!1}I(Nn,kt);var Rn="",kn=/^https?$/i,On=["POST","PUT"];function Mn(a){return"content-type"==a.toLowerCase()}function Pn(a,b){a.b=!1,a.a&&(a.g=!0,a.a.abort(),a.g=!1),a.f=b,a.h=5,Ln(a),Un(a)}function Ln(a){a.v||(a.v=!0,a.dispatchEvent("complete"),a.dispatchEvent("error"))}function xn(a){if(a.b&&void 0!==o&&(!a.s[1]||4!=qn(a)||2!=a.T()))if(a.l&&4==qn(a))zt(a.Fa,0,a);else if(a.dispatchEvent("readystatechange"),4==qn(a)){a.b=!1;try{var t,b=a.T();t:switch(b){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var e=!0;break t;default:e=!1}if(!(t=e)){var n;if(n=0===b){var r=String(a.A).match(qe)[1]||null;if(!r&&c.self&&c.self.location){var h=c.self.location.protocol;r=h.substr(0,h.length-1)}n=!kn.test(r?r.toLowerCase():"")}t=n}t?(a.dispatchEvent("complete"),a.dispatchEvent("success")):(a.h=6,a.f=a.za()+" ["+a.T()+"]",Ln(a))}finally{Un(a)}}}function Un(a,b){if(a.a){td(a);var t=a.a,e=a.s[0]?d:null;a.a=null,a.s=null,b||a.dispatchEvent("ready");try{t.onreadystatechange=e}catch(t){}}}function td(a){a.a&&a.D&&(a.a.ontimeout=null),a.m&&(c.clearTimeout(a.m),a.m=null)}function qn(a){return a.a?a.a.readyState:0}function Fn(a,b){return a.a?a.a.getResponseHeader(b):null}function Bn(a,b,t){t:{for(e in t){var e=!1;break t}e=!0}if(e)return a;if(t=function(a){var b="";return F(a,function(t,e){b+=e,b+=":",b+=t,b+="\r\n"}),b}(t),h(a)){if(b=encodeURIComponent(String(b)),b+=t=null!=t?"="+encodeURIComponent(String(t)):""){if(0>(t=a.indexOf("#"))&&(t=a.length),0>(e=a.indexOf("?"))||e>t){e=t;var n=""}else n=a.substring(e+1,t);t=(a=[a.substr(0,e),n,a.substr(t)])[1],a[1]=b?t?t+"&"+b:b:t,a=a[0]+(a[1]?"?"+a[1]:"")+a[2]}return a}return Ke(a,b,t),a}function Vn(a){this.f=[],this.F=new fn,this.ga=this.pa=this.B=this.ha=this.a=this.I=this.j=this.V=this.g=this.J=this.i=null,this.Ra=this.P=0,this.Pa=!!f("internalChannelParams.failFast",a),this.ia=this.w=this.s=this.l=this.h=this.c=null,this.oa=!0,this.m=this.ra=this.O=-1,this.S=this.v=this.A=0,this.Oa=f("internalChannelParams.baseRetryDelayMs",a)||5e3,this.Sa=f("internalChannelParams.retryDelaySeedMs",a)||1e4,this.Qa=f("internalChannelParams.forwardChannelMaxRetries",a)||2,this.qa=f("internalChannelParams.forwardChannelRequestTimeoutMs",a)||2e4,this.La=a&&a.Ab||void 0,this.D=void 0,this.R=a&&a.supportsCrossDomainXhr||!1,this.H="",this.b=new yn(a&&a.concurrentRequestLimit),this.ja=new In,this.o=!a||void 0===a.backgroundChannelTest||a.backgroundChannelTest,(this.W=a&&a.fastHandshake||!1)&&!this.o&&(this.o=!0),a&&a.forceLongPolling&&(this.oa=!1),this.fa=void 0}function jn(a){if(Qn(a),3==a.u){var b=a.P++,t=Be(a.B);Ke(t,"SID",a.H),Ke(t,"RID",b),Ke(t,"TYPE","terminate"),zn(a,t),(b=new ve(a,b,void 0)).F=2,b.f=ze(Be(t)),t=!1,c.navigator&&c.navigator.sendBeacon&&(t=c.navigator.sendBeacon(b.f.toString(),"")),!t&&c.Image&&((new Image).src=b.f,t=!0),t||(b.a=b.g.$(null),b.a.ca(b.f)),b.v=T(),De(b)}nr(a)}function Qn(a){a.w&&(a.w.abort(),a.w=null),a.a&&(a.a.cancel(),a.a=null),a.l&&(c.clearTimeout(a.l),a.l=null),$n(a),a.b.cancel(),a.h&&(l(a.h)&&c.clearTimeout(a.h),a.h=null)}function Wn(a,b){a.f.push(new mn(a.Ra++,b)),3==a.u&&Kn(a)}function Kn(a){bn(a.b)||a.h||(a.h=!0,Vt(a.Ia,a),a.A=0)}function Gn(a,b){var t;t=b?b.W:a.P++;var e=Be(a.B);Ke(e,"SID",a.H),Ke(e,"RID",t),Ke(e,"AID",a.O),zn(a,e),a.g&&a.i&&Bn(e,a.g,a.i),t=new ve(a,t,a.A+1),null===a.g&&(t.h=a.i),b&&(a.f=b.j.concat(a.f)),b=Hn(a,t,1e3),t.setTimeout(Math.round(.5*a.qa)+Math.round(.5*a.qa*Math.random())),dd(a.b,t),Se(t,e,b)}function zn(a,b){a.c&&Me({},function(t,e){Ke(b,e,t)})}function Hn(a,b,t){t=Math.min(a.f.length,t);var e=a.c?u(a.c.Ta,a.c,a):null;t:for(var n=a.f,r=-1;;){var o=["count="+t];-1==r?0(l-=r))r=Math.max(0,n[h].b-100),c=!1;else try{Cn(f,o,"req"+l+"_")}catch(t){e&&e(f)}}if(c){e=o.join("&");break t}}return a=a.f.splice(0,t),b.j=a,e}function Yn(a){a.a||a.l||(a.S=1,Vt(a.Ha,a),a.v=0)}function Xn(a){return!(a.a||a.l||3<=a.v)&&(a.S++,a.l=se(u(a.Ha,a),Zn(a,a.v)),a.v++,!0)}function Jn(a,b,t){var e=b.l;e&&vn(a.b,e),a.ia=a.oa&&t,a.m=b.c,a.B=rr(a,null,a.ha),Kn(a)}function $n(a){null!=a.s&&(c.clearTimeout(a.s),a.s=null)}function Zn(a,b){var t=a.Oa+Math.floor(Math.random()*a.Sa);return a.ma()||(t*=2),t*b}function er(a,b){if(2==b){var t=null;a.c&&(t=null);var e=u(a.fb,a);t||(t=new Fe("//www.google.com/images/cleardot.gif"),c.location&&"http"==c.location.protocol||Ve(t,"https"),ze(t)),function(a,b){var t=new te;if(c.Image){var e=new Image;e.onload=_(Dn,t,e,"TestLoadImage: loaded",!0,b),e.onerror=_(Dn,t,e,"TestLoadImage: error",!1,b),e.onabort=_(Dn,t,e,"TestLoadImage: abort",!1,b),e.ontimeout=_(Dn,t,e,"TestLoadImage: timeout",!1,b),c.setTimeout(function(){e.ontimeout&&e.ontimeout()},1e4),e.src=a}else b(!1)}(t.toString(),e)}else oe(2);a.u=0,a.c&&a.c.ta(b),nr(a),Qn(a)}function nr(a){a.u=0,a.m=-1,a.c&&(0==_n(a.b).length&&0==a.f.length||(a.b.c.length=0,R(a.f),a.f.length=0),a.c.sa())}function rr(a,b,t){var e=function(a){return a instanceof Fe?Be(a):new Fe(a,void 0)}(t);if(""!=e.b)b&&je(e,b+"."+e.b),Qe(e,e.i);else{var n,r=c.location;n=b?b+"."+r.hostname:r.hostname,e=function(a,b,t,e){var n=new Fe(null,void 0);return a&&Ve(n,a),b&&je(n,b),t&&Qe(n,t),e&&(n.a=e),n}(r.protocol,n,+r.port,t)}return a.V&&F(a.V,function(t,n){Ke(e,n,t)}),b=a.j,t=a.I,b&&t&&Ke(e,b,t),Ke(e,"VER",a.wa),zn(a,e),e}function ir(){}function or(){if(G&&!(10<=Number(et)))throw Error("Environmental error: no available transport.")}function ar(a,b){kt.call(this),this.a=new Vn(b),this.g=a,this.m=b&&b.testUrl?b.testUrl:function(a){for(var b=arguments[0],t=1;tb?null:h(a)?a.charAt(b):a[b]}(n.K()),t=c.FormData&&a instanceof c.FormData,!(0<=D(On,b))||e||t||n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),n.forEach(function(t,e){this.a.setRequestHeader(e,t)},this),this.I&&(this.a.responseType=this.I),"withCredentials"in this.a&&this.a.withCredentials!==this.F&&(this.a.withCredentials=this.F);try{td(this),0b[2]&&this.ia&&0==this.v&&!this.s&&(this.s=se(u(this.Za,this),6e3));if(1>=wn(this.b)&&this.fa){try{this.fa()}catch(t){}this.fa=void 0}}else er(this,11)}else if((a.s||this.a==a)&&$n(this),!k(b))for(b=t=this.ja.a.parse(b),t=0;t=a.b.f-(a.h?1:0)||(a.h?(a.f=b.j.concat(a.f),0):1==a.u||2==a.u||a.A>=(a.Pa?0:a.Qa)||(a.h=se(u(a.Ia,a,b),Zn(a,a.A)),a.A++,0)))}(this,a)||2==t&&Xn(this)))switch(b&&0>6,128|63&e);else if(55296==(64512&e))if(i>18,128|e>>12&63,128|e>>6&63,128|63&e);else b.push(239,191,189);else 56320==(64512&e)?b.push(239,191,189):b.push(224|e>>12,128|e>>6&63,128|63&e)}return new Uint8Array(b)}function P(t,e){switch(t){case N.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r)throw D(t,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?");break;case N.BASE64URL:var o=-1!==e.indexOf("+"),c=-1!==e.indexOf("/");if(o||c)throw D(t,"Invalid character '"+(o?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}var h;try{h=atob(e)}catch(e){throw D(t,"Invalid character found")}for(var l=new Uint8Array(h.length),i=0;i][;base64],");var s,n,r=e[1]||null;null!=r&&(this.base64=(n=";base64",(s=r).length>=n.length&&s.substring(s.length-n.length)===n),this.contentType=this.base64?r.substring(0,r.length-";base64".length):r),this.rest=t.substring(t.indexOf(",")+1)};var x,U={STATE_CHANGED:"state_changed"},F={RUNNING:"running",PAUSING:"pausing",PAUSED:"paused",SUCCESS:"success",CANCELING:"canceling",CANCELED:"canceled",ERROR:"error"},B={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function V(t){switch(t){case F.RUNNING:case F.PAUSING:case F.CANCELING:return B.RUNNING;case F.PAUSED:return B.PAUSED;case F.SUCCESS:return B.SUCCESS;case F.CANCELED:return B.CANCELED;case F.ERROR:default:return B.ERROR}}function j(p){return null!=p}function Q(p){return void 0!==p}function W(p){return"function"==typeof p}function K(p){return"object"==typeof p}function G(p){return K(p)&&null!==p}function z(p){return"string"==typeof p||p instanceof String}function H(p){return Y(p)&&Number.isInteger(p)}function Y(p){return"number"==typeof p||p instanceof Number}function X(p){return J()&&p instanceof Blob}function J(){return"undefined"!=typeof Blob}!function(t){t[t.NO_ERROR=0]="NO_ERROR",t[t.NETWORK_ERROR=1]="NETWORK_ERROR",t[t.ABORT=2]="ABORT"}(x||(x={}));var $=function(){function t(){var t=this;this.sent_=!1,this.xhr_=new XMLHttpRequest,this.errorCode_=x.NO_ERROR,this.sendPromise_=new Promise(function(e){t.xhr_.addEventListener("abort",function(){t.errorCode_=x.ABORT,e(t)}),t.xhr_.addEventListener("error",function(){t.errorCode_=x.NETWORK_ERROR,e(t)}),t.xhr_.addEventListener("load",function(){e(t)})})}return t.prototype.send=function(t,e,body,n){if(this.sent_)throw A("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(e,t,!0),j(n))for(var r in n)n.hasOwnProperty(r)&&this.xhr_.setRequestHeader(r,n[r].toString());return j(body)?this.xhr_.send(body):this.xhr_.send(),this.sendPromise_},t.prototype.getErrorCode=function(){if(!this.sent_)throw A("cannot .getErrorCode() before sending");return this.errorCode_},t.prototype.getStatus=function(){if(!this.sent_)throw A("cannot .getStatus() before sending");try{return this.xhr_.status}catch(t){return-1}},t.prototype.getResponseText=function(){if(!this.sent_)throw A("cannot .getResponseText() before sending");return this.xhr_.responseText},t.prototype.abort=function(){this.xhr_.abort()},t.prototype.getResponseHeader=function(header){return this.xhr_.getResponseHeader(header)},t.prototype.addUploadProgressListener=function(t){j(this.xhr_.upload)&&this.xhr_.upload.addEventListener("progress",t)},t.prototype.removeUploadProgressListener=function(t){j(this.xhr_.upload)&&this.xhr_.upload.removeEventListener("progress",t)},t}(),Z=function(){function t(){}return t.prototype.createXhrIo=function(){return new $},t}();function tt(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}function et(){for(var t=[],e=0;e0}).join("/");return 0===path.length?e:path+"/"+e}function st(path){var t=path.lastIndexOf("/",path.length-2);return-1===t?path:path.slice(t+1)}function ut(t){return"https://"+h+"/v0"+t}function ct(t){var e=encodeURIComponent,n="?";for(var r in t){if(t.hasOwnProperty(r))n=n+(e(r)+"="+e(t[r]))+"&"}return n=n.slice(0,-1)}function ht(t,e){return e}var lt=function(t,e,n,r){this.server=t,this.local=e||t,this.writable=!!n,this.xform=r||ht},ft=null;function pt(){if(ft)return ft;var t=[];t.push(new lt("bucket")),t.push(new lt("generation")),t.push(new lt("metageneration")),t.push(new lt("name","fullPath",!0));var e=new lt("name");e.xform=function(t,e){return function(t){return!z(t)||t.length<2?t:st(t)}(e)},t.push(e);var n=new lt("size");return n.xform=function(t,e){return j(e)?Number(e):e},t.push(n),t.push(new lt("timeCreated")),t.push(new lt("updated")),t.push(new lt("md5Hash",null,!0)),t.push(new lt("cacheControl",null,!0)),t.push(new lt("contentDisposition",null,!0)),t.push(new lt("contentEncoding",null,!0)),t.push(new lt("contentLanguage",null,!0)),t.push(new lt("contentType",null,!0)),t.push(new lt("metadata","customMetadata",!0)),ft=t}function mt(t,e,n){for(var r={type:"file"},o=n.length,i=0;i1e3)throw"Expected maxResults to be less than or equal to "+wt+"."}else{if(t!==Et)throw"Unknown option: "+t;if(p[Et]&&!z(p[Et]))throw"Expected pageToken to be string."}}var Ct=function(t,e,n,r){this.url=t,this.method=e,this.handler=n,this.timeout=r,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]};function Dt(t){if(!t)throw E()}function At(t,e){return function(n,text){var r=yt(t,text,e);return Dt(null!==r),r}}function Nt(t){return function(e,text){var n=function(t,e){var n=ot(e);return null===n?null:Tt(t,n)}(t,text);return Dt(null!==n),n}}function Rt(t,e){return function(n,text){var r=yt(t,text,e);return Dt(null!==r),function(t,e){var n=ot(e);if(null===n)return null;if(!z(n.downloadTokens))return null;var r=n.downloadTokens;if(0===r.length)return null;var o=encodeURIComponent;return r.split(",").map(function(e){var n=t.bucket,path=t.fullPath;return ut("/b/"+o(n)+"/o/"+o(path))+ct({alt:"media",token:e})})[0]}(r,text)}}function kt(t){return function(e,n){var r,path,o;return 401===e.getStatus()?r=new y(v.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(o=t.bucket,r=new y(v.QUOTA_EXCEEDED,"Quota for bucket '"+o+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(path=t.path,r=new y(v.UNAUTHORIZED,"User does not have permission to access '"+path+"'.")):r=n,r.setServerResponseProp(n.serverResponseProp()),r}}function Ot(t){var e=kt(t);return function(n,r){var path,o=e(n,r);return 404===n.getStatus()&&(path=t.path,o=new y(v.OBJECT_NOT_FOUND,"Object '"+path+"' does not exist.")),o.setServerResponseProp(r.serverResponseProp()),o}}function Mt(t,e,n){var r=ut(e.fullServerUrl()),o=t.maxOperationRetryTime(),c=new Ct(r,"GET",At(t,n),o);return c.errorHandler=Ot(e),c}function Pt(t,e,n,r,o){var c={};e.isRoot?c.prefix="":c.prefix=e.path+"/",n&&n.length>0&&(c.delimiter=n),r&&(c.pageToken=r),o&&(c.maxResults=o);var h=ut(e.bucketOnlyServerUrl()),l=t.maxOperationRetryTime(),f=new Ct(h,"GET",Nt(t),l);return f.urlParams=c,f.errorHandler=kt(e),f}function Lt(t,e,n){var r=ut(e.fullServerUrl()),o=t.maxOperationRetryTime(),c=new Ct(r,"GET",Rt(t,n),o);return c.errorHandler=Ot(e),c}function xt(t,e,n,r){var o=ut(e.fullServerUrl()),body=gt(n,r),c=t.maxOperationRetryTime(),h=new Ct(o,"PATCH",At(t,r),c);return h.headers={"Content-Type":"application/json; charset=utf-8"},h.body=body,h.errorHandler=Ot(e),h}function Ut(t,e){var n=ut(e.fullServerUrl()),r=t.maxOperationRetryTime();var o=new Ct(n,"DELETE",function(t,e){},r);return o.successCodes=[200,204],o.errorHandler=Ot(e),o}function qt(t,e,n){var r=Object.assign({},n);return r.fullPath=t.path,r.size=e.size(),r.contentType||(r.contentType=function(t,e){return t&&t.contentType||e&&e.type()||"application/octet-stream"}(null,e)),r}var Ft=function(t,e,n,r){this.current=t,this.total=e,this.finalized=!!n,this.metadata=r||null};function Bt(t,e){var n=null;try{n=t.getResponseHeader("X-Goog-Upload-Status")}catch(t){Dt(!1)}return Dt(!!n&&-1!==(e||["active"]).indexOf(n)),n}function Vt(t,e,n,r,o,c,h,l){var f=new Ft(0,0);if(h?(f.current=h.current,f.total=h.total):(f.current=0,f.total=r.size()),r.size()!==f.total)throw new y(v.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.");var d=f.total-f.current,m=d;o>0&&(m=Math.min(m,o));var w=f.current,E=w+m,S={"X-Goog-Upload-Command":m===d?"upload, finalize":"upload","X-Goog-Upload-Offset":f.current},body=r.slice(w,E);if(null===body)throw _();var T=e.maxUploadRetryTime(),I=new Ct(n,"POST",function(t,text){var n,o=Bt(t,["active","final"]),h=f.current+m,l=r.size();return n="final"===o?At(e,c)(t,text):null,new Ft(h,l,"final"===o,n)},T);return I.headers=S,I.body=body.uploadData(),I.progressCallback=l||null,I.errorHandler=kt(t),I}var jt=function(t,e,n){if(W(t)||j(e)||j(n))this.next=t,this.error=e||null,this.complete=n||null;else{var r=t;this.next=r.next||null,this.error=r.error||null,this.complete=r.complete||null}},Qt=function(t,e,n,r,o,c){this.bytesTransferred=t,this.totalBytes=e,this.state=n,this.metadata=r,this.task=o,this.ref=c};function Wt(t,e,n){for(var r=e.length,o=e.length,i=0;i=0))throw"Expected a number 0 or greater."})}function Jt(t,e){return new Kt(function(p){if(!(null===p||j(p)&&p instanceof Object))throw"Expected an Object.";null!=t&&t(p)},e)}function $t(t){return new Kt(function(p){if(null!==p&&!W(p))throw"Expected a Function."},t)}function Zt(t){return function(){for(var e=[],n=0;n262144},t.prototype.start_=function(){this.state_===F.RUNNING&&null===this.request_&&(this.resumable_?null===this.uploadUrl_?this.createResumable_():this.needToFetchStatus_?this.fetchStatus_():this.needToFetchMetadata_?this.fetchMetadata_():this.continueUpload_():this.oneShotUpload_())},t.prototype.resolveToken_=function(t){var e=this;this.authWrapper_.getAuthToken().then(function(n){switch(e.state_){case F.RUNNING:t(n);break;case F.CANCELING:e.transition_(F.CANCELED);break;case F.PAUSING:e.transition_(F.PAUSED)}})},t.prototype.createResumable_=function(){var t=this;this.resolveToken_(function(e){var n=function(t,e,n,r,o){var c=e.bucketOnlyServerUrl(),h=qt(e,r,o),l={name:h.fullPath},f=ut(c),d={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":r.size(),"X-Goog-Upload-Header-Content-Type":h.contentType,"Content-Type":"application/json; charset=utf-8"},body=gt(h,n),m=t.maxUploadRetryTime(),y=new Ct(f,"POST",function(t){var e;Bt(t);try{e=t.getResponseHeader("X-Goog-Upload-URL")}catch(t){Dt(!1)}return Dt(z(e)),e},m);return y.urlParams=l,y.headers=d,y.body=body,y.errorHandler=kt(e),y}(t.authWrapper_,t.location_,t.mappings_,t.blob_,t.metadata_),r=t.authWrapper_.makeRequest(n,e);t.request_=r,r.getPromise().then(function(e){t.request_=null,t.uploadUrl_=e,t.needToFetchStatus_=!1,t.completeTransitions_()},t.errorHandler_)})},t.prototype.fetchStatus_=function(){var t=this,e=this.uploadUrl_;this.resolveToken_(function(n){var r=function(t,e,n,r){var o=t.maxUploadRetryTime(),c=new Ct(n,"POST",function(t){var e=Bt(t,["active","final"]),n=null;try{n=t.getResponseHeader("X-Goog-Upload-Size-Received")}catch(t){Dt(!1)}n||Dt(!1);var o=Number(n);return Dt(!isNaN(o)),new Ft(o,r.size(),"final"===e)},o);return c.headers={"X-Goog-Upload-Command":"query"},c.errorHandler=kt(e),c}(t.authWrapper_,t.location_,e,t.blob_),o=t.authWrapper_.makeRequest(r,n);t.request_=o,o.getPromise().then(function(e){e=e,t.request_=null,t.updateProgress_(e.current),t.needToFetchStatus_=!1,e.finalized&&(t.needToFetchMetadata_=!0),t.completeTransitions_()},t.errorHandler_)})},t.prototype.continueUpload_=function(){var t=this,e=262144*this.chunkMultiplier_,n=new Ft(this.transferred_,this.blob_.size()),r=this.uploadUrl_;this.resolveToken_(function(o){var c;try{c=Vt(t.location_,t.authWrapper_,r,t.blob_,e,t.mappings_,n,t.makeProgressCallback_())}catch(e){return t.error_=e,void t.transition_(F.ERROR)}var h=t.authWrapper_.makeRequest(c,o);t.request_=h,h.getPromise().then(function(e){t.increaseMultiplier_(),t.request_=null,t.updateProgress_(e.current),e.finalized?(t.metadata_=e.metadata,t.transition_(F.SUCCESS)):t.completeTransitions_()},t.errorHandler_)})},t.prototype.increaseMultiplier_=function(){262144*this.chunkMultiplier_<33554432&&(this.chunkMultiplier_*=2)},t.prototype.fetchMetadata_=function(){var t=this;this.resolveToken_(function(e){var n=Mt(t.authWrapper_,t.location_,t.mappings_),r=t.authWrapper_.makeRequest(n,e);t.request_=r,r.getPromise().then(function(e){t.request_=null,t.metadata_=e,t.transition_(F.SUCCESS)},t.metadataErrorHandler_)})},t.prototype.oneShotUpload_=function(){var t=this;this.resolveToken_(function(e){var n=function(t,e,n,r,o){var c=e.bucketOnlyServerUrl(),h={"X-Goog-Upload-Protocol":"multipart"},l=function(){for(var t="",i=0;i<2;i++)t+=Math.random().toString().slice(2);return t}();h["Content-Type"]="multipart/related; boundary="+l;var f=qt(e,r,o),d="--"+l+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+gt(f,n)+"\r\n--"+l+"\r\nContent-Type: "+f.contentType+"\r\n\r\n",m="\r\n--"+l+"--",body=nt.getBlob(d,r,m);if(null===body)throw _();var y={name:f.fullPath},v=ut(c),w=t.maxUploadRetryTime(),E=new Ct(v,"POST",At(t,n),w);return E.urlParams=y,E.headers=h,E.body=body.uploadData(),E.errorHandler=kt(e),E}(t.authWrapper_,t.location_,t.mappings_,t.blob_,t.metadata_),r=t.authWrapper_.makeRequest(n,e);t.request_=r,r.getPromise().then(function(e){t.request_=null,t.metadata_=e,t.updateProgress_(t.blob_.size()),t.transition_(F.SUCCESS)},t.errorHandler_)})},t.prototype.updateProgress_=function(t){var e=this.transferred_;this.transferred_=t,this.transferred_!==e&&this.notifyObservers_()},t.prototype.transition_=function(t){if(this.state_!==t)switch(t){case F.CANCELING:case F.PAUSING:this.state_=t,null!==this.request_&&this.request_.cancel();break;case F.RUNNING:var e=this.state_===F.PAUSED;this.state_=t,e&&(this.notifyObservers_(),this.start_());break;case F.PAUSED:this.state_=t,this.notifyObservers_();break;case F.CANCELED:this.error_=S(),this.state_=t,this.notifyObservers_();break;case F.ERROR:case F.SUCCESS:this.state_=t,this.notifyObservers_()}},t.prototype.completeTransitions_=function(){switch(this.state_){case F.PAUSING:this.transition_(F.PAUSED);break;case F.CANCELING:this.transition_(F.CANCELED);break;case F.RUNNING:this.start_()}},Object.defineProperty(t.prototype,"snapshot",{get:function(){var t=V(this.state_);return new Qt(this.transferred_,this.blob_.size(),t,this.metadata_,this,this.ref_)},enumerable:!0,configurable:!0}),t.prototype.on=function(t,e,n,r){function o(){if(t!==U.STATE_CHANGED)throw"Expected one of the event types: ["+U.STATE_CHANGED+"]."}var c="Expected a function or an Object with one of `next`, `error`, `complete` properties.",h=$t(!0).validator,l=Jt(null,!0).validator;function f(p){try{return void h(p)}catch(t){}try{if(l(p),!(Q(p.next)||Q(p.error)||Q(p.complete)))throw"";return}catch(t){throw c}}var d=[Gt(o),Jt(f,!0),$t(!0),$t(!0)];Wt("on",d,arguments);var m=this;function y(t){return function(e,n,o){null!==t&&Wt("on",t,arguments);var c=new jt(e,n,r);return m.addObserver_(c),function(){m.removeObserver_(c)}}}function v(p){if(null===p)throw c;f(p)}var w=[Jt(v),$t(!0),$t(!0)],E=!(Q(e)||Q(n)||Q(r));return E?y(w):y(null)(e,n,r)},t.prototype.then=function(t,e){return this.promise_.then(t,e)},t.prototype.catch=function(t){return this.then(null,t)},t.prototype.addObserver_=function(t){this.observers_.push(t),this.notifyObserver_(t)},t.prototype.removeObserver_=function(t){var i=this.observers_.indexOf(t);-1!==i&&this.observers_.splice(i,1)},t.prototype.notifyObservers_=function(){var t=this;this.finishPromise_(),this.observers_.slice().forEach(function(e){t.notifyObserver_(e)})},t.prototype.finishPromise_=function(){if(null!==this.resolve_){var t=!0;switch(V(this.state_)){case B.SUCCESS:Zt(this.resolve_.bind(null,this.snapshot))();break;case B.CANCELED:case B.ERROR:Zt(this.reject_.bind(null,this.error_))();break;default:t=!1}t&&(this.resolve_=null,this.reject_=null)}},t.prototype.notifyObserver_=function(t){switch(V(this.state_)){case B.RUNNING:case B.PAUSED:t.next&&Zt(t.next.bind(t,this.snapshot))();break;case B.SUCCESS:t.complete&&Zt(t.complete.bind(t))();break;case B.CANCELED:case B.ERROR:t.error&&Zt(t.error.bind(t,this.error_))();break;default:t.error&&Zt(t.error.bind(t,this.error_))()}},t.prototype.resume=function(){Wt("resume",[],arguments);var t=this.state_===F.PAUSED||this.state_===F.PAUSING;return t&&this.transition_(F.RUNNING),t},t.prototype.pause=function(){Wt("pause",[],arguments);var t=this.state_===F.RUNNING;return t&&this.transition_(F.PAUSING),t},t.prototype.cancel=function(){Wt("cancel",[],arguments);var t=this.state_===F.RUNNING||this.state_===F.PAUSING;return t&&this.transition_(F.CANCELING),t},t}(),ee=function(){function t(t,e){this.authWrapper=t,this.location=e instanceof it?e:it.makeFromUrl(e)}return t.prototype.toString=function(){return Wt("toString",[],arguments),"gs://"+this.location.bucket+"/"+this.location.path},t.prototype.newRef=function(e,n){return new t(e,n)},t.prototype.mappings=function(){return pt()},t.prototype.child=function(t){Wt("child",[Gt()],arguments);var e=at(this.location.path,t),n=new it(this.location.bucket,e);return this.newRef(this.authWrapper,n)},Object.defineProperty(t.prototype,"parent",{get:function(){var t=function(path){if(0===path.length)return null;var t=path.lastIndexOf("/");return-1===t?"":path.slice(0,t)}(this.location.path);if(null===t)return null;var e=new it(this.location.bucket,t);return this.newRef(this.authWrapper,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"root",{get:function(){var t=new it(this.location.bucket,"");return this.newRef(this.authWrapper,t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bucket",{get:function(){return this.location.bucket},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fullPath",{get:function(){return this.location.path},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return st(this.location.path)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"storage",{get:function(){return this.authWrapper.service()},enumerable:!0,configurable:!0}),t.prototype.put=function(data,t){return void 0===t&&(t=null),Wt("put",[zt(),Ht(!0)],arguments),this.throwIfRoot_("put"),new te(this,this.authWrapper,this.location,this.mappings(),new nt(data),t)},t.prototype.putString=function(t,e,n){void 0===e&&(e=N.RAW),Wt("putString",[Gt(),Gt(R,!0),Ht(!0)],arguments),this.throwIfRoot_("putString");var data=O(e,t),r=Object.assign({},n);return!j(r.contentType)&&j(data.contentType)&&(r.contentType=data.contentType),new te(this,this.authWrapper,this.location,this.mappings(),new nt(data.data,!0),r)},t.prototype.delete=function(){var t=this;return Wt("delete",[],arguments),this.throwIfRoot_("delete"),this.authWrapper.getAuthToken().then(function(e){var n=Ut(t.authWrapper,t.location);return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.listAll=function(){Wt("listAll",[],arguments);var t={prefixes:[],items:[]};return this.listAllHelper(t).then(function(){return t})},t.prototype.listAllHelper=function(t,e){return Object(c.__awaiter)(this,void 0,void 0,function(){var n,r,o,h;return Object(c.__generator)(this,function(c){switch(c.label){case 0:return o={pageToken:e},[4,this.list(o)];case 1:return h=c.sent(),(n=t.prefixes).push.apply(n,h.prefixes),(r=t.items).push.apply(r,h.items),null==h.nextPageToken?[3,3]:[4,this.listAllHelper(t,h.nextPageToken)];case 2:c.sent(),c.label=3;case 3:return[2]}})})},t.prototype.list=function(t){Wt("list",[Yt(!0)],arguments);var e=this;return this.authWrapper.getAuthToken().then(function(n){var r=t||{},o=Pt(e.authWrapper,e.location,"/",r.pageToken,r.maxResults);return e.authWrapper.makeRequest(o,n).getPromise()})},t.prototype.getMetadata=function(){var t=this;return Wt("getMetadata",[],arguments),this.throwIfRoot_("getMetadata"),this.authWrapper.getAuthToken().then(function(e){var n=Mt(t.authWrapper,t.location,t.mappings());return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.updateMetadata=function(t){var e=this;return Wt("updateMetadata",[Ht()],arguments),this.throwIfRoot_("updateMetadata"),this.authWrapper.getAuthToken().then(function(n){var r=xt(e.authWrapper,e.location,t,e.mappings());return e.authWrapper.makeRequest(r,n).getPromise()})},t.prototype.getDownloadURL=function(){var t=this;return Wt("getDownloadURL",[],arguments),this.throwIfRoot_("getDownloadURL"),this.authWrapper.getAuthToken().then(function(e){var n=Lt(t.authWrapper,t.location,t.mappings());return t.authWrapper.makeRequest(n,e).getPromise().then(function(t){if(null===t)throw T();return t})})},t.prototype.throwIfRoot_=function(t){if(""===this.location.path)throw function(t){return new y(v.INVALID_ROOT_OPERATION,"The operation '"+t+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}(t)},t}(),ne=function(){function t(t){this.promise_=Promise.reject(t)}return t.prototype.getPromise=function(){return this.promise_},t.prototype.cancel=function(t){void 0===t&&(t=!1)},t}(),re=function(){function t(){this.map_=new Map,this.id_=m}return t.prototype.addRequest=function(t){var e=this,n=this.id_;this.id_++,this.map_.set(n,t),t.getPromise().then(function(){return e.map_.delete(n)},function(){return e.map_.delete(n)})},t.prototype.clear=function(){this.map_.forEach(function(t){t&&t.cancel(!0)}),this.map_.clear()},t}(),ie=function(){function t(e,n,r,o,c){if(this.bucket_=null,this.deleted_=!1,this.app_=e,null!==this.app_){var h=this.app_.options;j(h)&&(this.bucket_=t.extractBucket_(h))}this.storageRefMaker_=n,this.requestMaker_=r,this.pool_=c,this.service_=o,this.maxOperationRetryTime_=f,this.maxUploadRetryTime_=d,this.requestMap_=new re}return t.extractBucket_=function(t){var e=t[l]||null;return null==e?null:it.makeFromBucketSpec(e).bucket},t.prototype.getAuthToken=function(){return null!==this.app_&&j(this.app_.INTERNAL)&&j(this.app_.INTERNAL.getToken)?this.app_.INTERNAL.getToken().then(function(t){return null!==t?t.accessToken:null},function(){return null}):Promise.resolve(null)},t.prototype.bucket=function(){if(this.deleted_)throw C();return this.bucket_},t.prototype.service=function(){return this.service_},t.prototype.makeStorageReference=function(t){return this.storageRefMaker_(this,t)},t.prototype.makeRequest=function(t,e){if(this.deleted_)return new ne(C());var n=this.requestMaker_(t,e,this.pool_);return this.requestMap_.addRequest(n),n},t.prototype.deleteApp=function(){this.deleted_=!0,this.app_=null,this.requestMap_.clear()},t.prototype.maxUploadRetryTime=function(){return this.maxUploadRetryTime_},t.prototype.setMaxUploadRetryTime=function(time){this.maxUploadRetryTime_=time},t.prototype.maxOperationRetryTime=function(){return this.maxOperationRetryTime_},t.prototype.setMaxOperationRetryTime=function(time){this.maxOperationRetryTime_=time},t}();var oe=function(){function t(t,e,n,body,r,o,c,h,l,f,d){var m=this;this.pendingXhr_=null,this.backoffId_=null,this.resolve_=null,this.reject_=null,this.canceled_=!1,this.appDelete_=!1,this.url_=t,this.method_=e,this.headers_=n,this.body_=body,this.successCodes_=r.slice(),this.additionalRetryCodes_=o.slice(),this.callback_=c,this.errorCallback_=h,this.progressCallback_=f,this.timeout_=l,this.pool_=d,this.promise_=new Promise(function(t,e){m.resolve_=t,m.reject_=e,m.start_()})}return t.prototype.start_=function(){var t=this;function e(e,n){var r,o=t.resolve_,c=t.reject_,h=n.xhr;if(n.wasSuccessCode)try{var l=t.callback_(h,h.getResponseText());Q(l)?o(l):o()}catch(t){c(t)}else null!==h?((r=E()).setServerResponseProp(h.getResponseText()),t.errorCallback_?c(t.errorCallback_(h,r)):c(r)):n.canceled?c(r=t.appDelete_?C():S()):c(r=new y(v.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again."))}this.canceled_?e(0,new ae(!1,null,!0)):this.backoffId_=function(t,e,n){var r=1,o=null,c=!1,h=0;function l(){return 2===h}var f=!1;function d(){f||(f=!0,e.apply(null,arguments))}function m(e){o=setTimeout(function(){o=null,t(y,l())},e)}function y(t){var e;f||(t?d.apply(null,arguments):l()||c?d.apply(null,arguments):(r<64&&(r*=2),1===h?(h=2,e=0):e=1e3*(r+Math.random()),m(e)))}var v=!1;function w(t){v||(v=!0,f||(null!==o?(t||(h=2),clearTimeout(o),m(0)):t||(h=1)))}return m(0),setTimeout(function(){c=!0,w(!0)},n),w}(function(e,n){if(n)e(!1,new ae(!1,null,!0));else{var r=t.pool_.createXhrIo();t.pendingXhr_=r,null!==t.progressCallback_&&r.addUploadProgressListener(o),r.send(t.url_,t.method_,t.body_,t.headers_).then(function(n){null!==t.progressCallback_&&n.removeUploadProgressListener(o),t.pendingXhr_=null;var r=(n=n).getErrorCode()===x.NO_ERROR,c=n.getStatus();if(r&&!t.isRetryStatusCode_(c)){var h=-1!==t.successCodes_.indexOf(c);e(!0,new ae(h,n))}else{var l=n.getErrorCode()===x.ABORT;e(!1,new ae(!1,null,l))}})}function o(e){var n=e.loaded,r=e.lengthComputable?e.total:-1;null!==t.progressCallback_&&t.progressCallback_(n,r)}},e,this.timeout_)},t.prototype.getPromise=function(){return this.promise_},t.prototype.cancel=function(t){this.canceled_=!0,this.appDelete_=t||!1,null!==this.backoffId_&&(0,this.backoffId_)(!1),null!==this.pendingXhr_&&this.pendingXhr_.abort()},t.prototype.isRetryStatusCode_=function(t){var e=t>=500&&t<600,n=-1!==[408,429].indexOf(t),r=-1!==this.additionalRetryCodes_.indexOf(t);return e||n||r},t}(),ae=function(t,e,n){this.wasSuccessCode=t,this.xhr=e,this.canceled=!!n};function se(t,e,n){var r=ct(t.urlParams),c=t.url+r,h=Object.assign({},t.headers);return function(t,e){null!==e&&e.length>0&&(t.Authorization="Firebase "+e)}(h,e),function(t){var e=void 0!==o.a?o.a.SDK_VERSION:"AppManager";t["X-Firebase-Storage-Version"]="webjs/"+e}(h),new oe(c,t.method,h,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,n)}var ue,ce,he=function(){function t(t,e,n){if(this.bucket_=null,this.authWrapper_=new ie(t,function(t,e){return new ee(t,e)},se,this,e),this.app_=t,null!=n)this.bucket_=it.makeFromBucketSpec(n);else{var r=this.authWrapper_.bucket();null!=r&&(this.bucket_=new it(r,""))}this.internals_=new le(this)}return t.prototype.ref=function(path){function t(path){if(/^[A-Za-z]+:\/\//.test(path))throw"Expected child path but got a URL, use refFromURL instead."}if(Wt("ref",[Gt(t,!0)],arguments),null==this.bucket_)throw new Error("No Storage Bucket defined in Firebase Options.");var e=new ee(this.authWrapper_,this.bucket_);return null!=path?e.child(path):e},t.prototype.refFromURL=function(t){function e(p){if(!/^[A-Za-z]+:\/\//.test(p))throw"Expected full URL but got a child path, use ref instead.";try{it.makeFromUrl(p)}catch(t){throw"Expected valid full URL but got an invalid one."}}return Wt("refFromURL",[Gt(e,!1)],arguments),new ee(this.authWrapper_,t)},Object.defineProperty(t.prototype,"maxUploadRetryTime",{get:function(){return this.authWrapper_.maxUploadRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxUploadRetryTime=function(time){Wt("setMaxUploadRetryTime",[Xt()],arguments),this.authWrapper_.setMaxUploadRetryTime(time)},t.prototype.setMaxOperationRetryTime=function(time){Wt("setMaxOperationRetryTime",[Xt()],arguments),this.authWrapper_.setMaxOperationRetryTime(time)},Object.defineProperty(t.prototype,"app",{get:function(){return this.app_},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"INTERNAL",{get:function(){return this.internals_},enumerable:!0,configurable:!0}),t}(),le=function(){function t(t){this.service_=t}return t.prototype.delete=function(){return this.service_.authWrapper_.deleteApp(),Promise.resolve()},t}(),fe="storage";function pe(t,e,n){return new he(t,new Z,n)}ue=o.a,ce={TaskState:B,TaskEvent:U,StringFormat:N,Storage:he,Reference:ee},ue.INTERNAL.registerService(fe,pe,ce,void 0,!0)},2:function(t,e,n){"use strict";function r(t,e,n,r,o,c,h){try{var l=t[c](h),f=l.value}catch(t){return void n(t)}l.done?e(f):Promise.resolve(f).then(r,o)}function o(t){return function(){var e=this,n=arguments;return new Promise(function(o,c){var h=t.apply(e,n);function l(t){r(h,o,c,l,f,"next",t)}function f(t){r(h,o,c,l,f,"throw",t)}l(void 0)})}}n.d(e,"a",function(){return o})},21:function(t,e,n){"use strict";function r(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}n.d(e,"a",function(){return r})},27:function(t,e,n){"use strict";n.r(e),n.d(e,"__extends",function(){return o}),n.d(e,"__assign",function(){return c}),n.d(e,"__rest",function(){return h}),n.d(e,"__decorate",function(){return l}),n.d(e,"__param",function(){return f}),n.d(e,"__metadata",function(){return d}),n.d(e,"__awaiter",function(){return m}),n.d(e,"__generator",function(){return y}),n.d(e,"__exportStar",function(){return v}),n.d(e,"__values",function(){return w}),n.d(e,"__read",function(){return E}),n.d(e,"__spread",function(){return S}),n.d(e,"__await",function(){return _}),n.d(e,"__asyncGenerator",function(){return T}),n.d(e,"__asyncDelegator",function(){return I}),n.d(e,"__asyncValues",function(){return C}),n.d(e,"__makeTemplateObject",function(){return D}),n.d(e,"__importStar",function(){return A}),n.d(e,"__importDefault",function(){return N});var r=function(t,b){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,b){t.__proto__=b}||function(t,b){for(var p in b)b.hasOwnProperty(p)&&(t[p]=b[p])})(t,b)};function o(t,b){function e(){this.constructor=t}r(t,b),t.prototype=null===b?Object.create(b):(e.prototype=b.prototype,new e)}var c=function(){return(c=Object.assign||function(t){for(var s,i=1,e=arguments.length;i=0;i--)(r=t[i])&&(c=(o<3?r(c):o>3?r(e,n,c):r(e,n))||c);return o>3&&c&&Object.defineProperty(e,n,c),c}function f(t,e){return function(n,r){e(n,r,t)}}function d(t,e){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,e)}function m(t,e,n,r){return new(n||(n=Promise))(function(o,c){function h(t){try{f(r.next(t))}catch(t){c(t)}}function l(t){try{f(r.throw(t))}catch(t){c(t)}}function f(t){t.done?o(t.value):new n(function(e){e(t.value)}).then(h,l)}f((r=r.apply(t,e||[])).next())})}function y(t,body){var e,n,r,g,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return g={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(g[Symbol.iterator]=function(){return this}),g;function c(c){return function(h){return function(c){if(e)throw new TypeError("Generator is already executing.");for(;o;)try{if(e=1,n&&(r=2&c[0]?n.return:c[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,c[1])).done)return r;switch(n=0,r&&(c=[2&c[0],r.value]),c[0]){case 0:case 1:r=c;break;case 4:return o.label++,{value:c[1],done:!1};case 5:o.label++,n=c[1],c=[0];continue;case 7:c=o.ops.pop(),o.trys.pop();continue;default:if(!(r=(r=o.trys).length>0&&r[r.length-1])&&(6===c[0]||2===c[0])){o=0;continue}if(3===c[0]&&(!r||c[1]>r[0]&&c[1]=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}}}function E(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),c=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)c.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return c}function S(){for(var t=[],i=0;i1||o(t,e)})})}function o(t,e){try{(n=g[t](e)).value instanceof _?Promise.resolve(n.value.v).then(c,h):l(q[0][2],n)}catch(t){l(q[0][3],t)}var n}function c(t){o("next",t)}function h(t){o("throw",t)}function l(t,e){t(e),q.shift(),q.length&&o(q[0][0],q[0][1])}}function I(t){var i,p;return i={},e("next"),e("throw",function(t){throw t}),e("return"),i[Symbol.iterator]=function(){return this},i;function e(e,n){i[e]=t[e]?function(r){return(p=!p)?{value:_(t[e](r)),done:"return"===e}:n?n(r):r}:n}}function C(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,e=t[Symbol.asyncIterator];return e?e.call(t):(t=w(t),i={},n("next"),n("throw"),n("return"),i[Symbol.asyncIterator]=function(){return this},i);function n(e){i[e]=t[e]&&function(n){return new Promise(function(r,o){(function(t,e,n,r){Promise.resolve(r).then(function(e){t({value:e,done:n})},e)})(r,o,(n=t[e](n)).done,n.value)})}}}function D(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function A(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function N(t){return t&&t.__esModule?t:{default:t}}},28:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,o=n(27),c=n(96),h=n(97),l=((r={})["no-app"]="No Firebase App '{$name}' has been created - call Firebase App.initializeApp()",r["bad-app-name"]="Illegal App name: '{$name}",r["duplicate-app"]="Firebase App named '{$name}' already exists",r["app-deleted"]="Firebase App named '{$name}' already deleted",r["duplicate-service"]="Firebase service named '{$name}' already registered",r["invalid-app-argument"]="firebase.{$name}() takes either no argument or a Firebase App instance.",r),f=new c.ErrorFactory("app","Firebase",l),d="[DEFAULT]",m=[],y=function(){function t(t,e,n){this.firebase_=n,this.isDeleted_=!1,this.services_={},this.name_=e.name,this.automaticDataCollectionEnabled_=e.automaticDataCollectionEnabled||!1,this.options_=c.deepCopy(t),this.INTERNAL={getUid:function(){return null},getToken:function(){return Promise.resolve(null)},addAuthTokenListener:function(t){m.push(t),setTimeout(function(){return t(null)},0)},removeAuthTokenListener:function(t){m=m.filter(function(e){return e!==t})}}}return Object.defineProperty(t.prototype,"automaticDataCollectionEnabled",{get:function(){return this.checkDestroyed_(),this.automaticDataCollectionEnabled_},set:function(t){this.checkDestroyed_(),this.automaticDataCollectionEnabled_=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return this.checkDestroyed_(),this.name_},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"options",{get:function(){return this.checkDestroyed_(),this.options_},enumerable:!0,configurable:!0}),t.prototype.delete=function(){var t=this;return new Promise(function(e){t.checkDestroyed_(),e()}).then(function(){t.firebase_.INTERNAL.removeApp(t.name_);for(var e=[],n=0,r=Object.keys(t.services_);n=0&&w.warn("\n Warning: You are trying to load Firebase while using Firebase Performance standalone script.\n You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.\n ")}var S=function t(){var e=function(t){var e={},n={},r={},o={__esModule:!0,initializeApp:function(n,r){if(void 0===r&&(r={}),"object"!=typeof r||null===r){var h=r;r={name:h}}var l=r;void 0===l.name&&(l.name=d);var y=l.name;if("string"!=typeof y||!y)throw f.create("bad-app-name",{name:String(y)});if(c.contains(e,y))throw f.create("duplicate-app",{name:y});var v=new t(n,l,o);return e[y]=v,m(v,"create"),v},app:h,apps:null,SDK_VERSION:v,INTERNAL:{registerService:function(e,d,m,y,v){if(void 0===v&&(v=!1),n[e])throw f.create("duplicate-service",{name:e});function w(t){if(void 0===t&&(t=h()),"function"!=typeof t[e])throw f.create("invalid-app-argument",{name:e});return t[e]()}return n[e]=d,y&&(r[e]=y,l().forEach(function(t){y("create",t)})),void 0!==m&&c.deepExtend(w,m),o[e]=w,t.prototype[e]=function(){for(var t=[],n=0;ne.parts.length&&(n.parts.length=e.parts.length)}else{var o=[];for(r=0;r>6|192,e[p++]=63&n|128):55296==(64512&n)&&i+1>18|240,e[p++]=n>>12&63|128,e[p++]=n>>6&63|128,e[p++]=63&n|128):(e[p++]=n>>12|224,e[p++]=n>>6&63|128,e[p++]=63&n|128)}return e},f={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray:function(input,t){if(!Array.isArray(input))throw Error("encodeByteArray takes an array as a parameter");this.init_();for(var e=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,output=[],i=0;i>2,f=(3&n)<<4|o>>4,d=(15&o)<<2|h>>6,m=63&h;c||(m=64,r||(d=64)),output.push(e[l],e[f],e[d],e[m])}return output.join("")},encodeString:function(input,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(input):this.encodeByteArray(l(input),t)},decodeString:function(input,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(input):function(t){for(var e=[],n=0,r=0;n191&&o<224){var c=t[n++];e[r++]=String.fromCharCode((31&o)<<6|63&c)}else if(o>239&&o<365){var u=((7&o)<<18|(63&(c=t[n++]))<<12|(63&(h=t[n++]))<<6|63&t[n++])-65536;e[r++]=String.fromCharCode(55296+(u>>10)),e[r++]=String.fromCharCode(56320+(1023&u))}else{c=t[n++];var h=t[n++];e[r++]=String.fromCharCode((15&o)<<12|(63&c)<<6|63&h)}}return e.join("")}(this.decodeStringToByteArray(input,t))},decodeStringToByteArray:function(input,t){this.init_();for(var e=t?this.charToByteMapWebSafe_:this.charToByteMap_,output=[],i=0;i>4;if(output.push(h),64!==o){var l=r<<4&240|o>>2;if(output.push(l),64!==c){var f=o<<6&192|c;output.push(f)}}}return output},init_:function(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(var i=0;i=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)]=i,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)]=i)}}},d=function(t){try{return f.decodeString(t,!0)}catch(t){console.error("base64Decode failed: ",t)}return null};function m(t,source){if(!(source instanceof Object))return source;switch(source.constructor){case Date:return new Date(source.getTime());case Object:void 0===t&&(t={});break;case Array:t=[];break;default:return source}for(var e in source)source.hasOwnProperty(e)&&(t[e]=m(t[e],source[e]));return t}var y=function(){function t(){var t=this;this.promise=new Promise(function(e,n){t.resolve=e,t.reject=n})}return t.prototype.wrapCallback=function(t){var e=this;return function(n,r){n?e.reject(n):e.resolve(r),"function"==typeof t&&(e.promise.catch(function(){}),1===t.length?t(n):t(n,r))}},t}();function v(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}var w="FirebaseError",E=function(t){function e(code,n){var r=t.call(this,n)||this;return r.code=code,r.name=w,Object.setPrototypeOf(r,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(r,S.prototype.create),r}return r.__extends(e,t),e}(Error),S=function(){function t(t,e,n){this.service=t,this.serviceName=e,this.errors=n}return t.prototype.create=function(code){for(var data=[],t=1;t"})}var T=/\{\$([^}]+)}/g;function I(t){return JSON.parse(t)}var C=function(t){var header={},e={},data={},n="";try{var r=t.split(".");header=I(d(r[0])||""),e=I(d(r[1])||""),n=r[2],data=e.d||{},delete e.d}catch(t){}return{header:header,claims:e,data:data,signature:n}},D=function(t,e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e(n,t[n])},A=function(t,e){return D(e,function(e,n){t[e]=n}),t},N=function(t,e,n){for(var r in t)if(e.call(n,t[r],r,t))return r},R=function(){function t(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(var i=1;i>>31)}var o,c,a=this.chain_[0],b=this.chain_[1],h=this.chain_[2],l=this.chain_[3],f=this.chain_[4];for(i=0;i<80;i++){i<40?i<20?(o=l^b&(h^l),c=1518500249):(o=b^h^l,c=1859775393):i<60?(o=b&h|l&(b|h),c=2400959708):(o=b^h^l,c=3395469782);r=(a<<5|a>>>27)+o+f+c+n[i]&4294967295;f=l,l=h,h=4294967295&(b<<30|b>>>2),b=a,a=r}this.chain_[0]=this.chain_[0]+a&4294967295,this.chain_[1]=this.chain_[1]+b&4294967295,this.chain_[2]=this.chain_[2]+h&4294967295,this.chain_[3]=this.chain_[3]+l&4294967295,this.chain_[4]=this.chain_[4]+f&4294967295},t.prototype.update=function(t,e){if(null!=t){void 0===e&&(e=t.length);for(var n=e-this.blockSize,r=0,o=this.buf_,c=this.inbuf_;r=56;i--)this.buf_[i]=255&e,e/=256;this.compress_(this.buf_);var n=0;for(i=0;i<5;i++)for(var r=24;r>=0;r-=8)t[n]=this.chain_[i]>>r&255,++n;return t},t}();var k=function(){function t(t,e){var n=this;this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=e,this.task.then(function(){t(n)}).catch(function(t){n.error(t)})}return t.prototype.next=function(t){this.forEachObserver(function(e){e.next(t)})},t.prototype.error=function(t){this.forEachObserver(function(e){e.error(t)}),this.close(t)},t.prototype.complete=function(){this.forEachObserver(function(t){t.complete()}),this.close()},t.prototype.subscribe=function(t,e,n){var r,o=this;if(void 0===t&&void 0===e&&void 0===n)throw new Error("Missing Observer.");void 0===(r=function(t,e){if("object"!=typeof t||null===t)return!1;for(var n=0,r=e;n 4. Need to update it?")}var o=t+" failed: ";return o+=r+" argument "}e.CONSTANTS=o,e.Deferred=y,e.ErrorFactory=S,e.FirebaseError=E,e.Sha1=R,e.assert=c,e.assertionError=h,e.async=function(t,e){return function(){for(var n=[],r=0;r=r&&n<=o},e.issuedAtTime=function(t){var e=C(t).claims;return"object"==typeof e&&e.hasOwnProperty("iat")?e.iat:null},e.jsonEval=I,e.map=function(t,e,n){var r={};for(var o in t)r[o]=e.call(n,t[o],o,t);return r},e.querystring=function(t){var e=[];return D(t,function(t,n){Array.isArray(n)?n.forEach(function(n){e.push(encodeURIComponent(t)+"="+encodeURIComponent(n))}):e.push(encodeURIComponent(t)+"="+encodeURIComponent(n))}),e.length?"&"+e.join("&"):""},e.querystringDecode=function(t){var e={};return t.replace(/^\?/,"").split("&").forEach(function(t){if(t){var n=t.split("=");e[n[0]]=n[1]}}),e},e.safeGet=function(t,e){if(Object.prototype.hasOwnProperty.call(t,e))return t[e]},e.stringLength=function(t){for(var p=0,i=0;i=55296&&e<=56319?(p+=4,i++):p+=3}return p},e.stringToByteArray=function(t){for(var e=[],p=0,i=0;i=55296&&n<=56319){var r=n-55296;c(++i>6|192,e[p++]=63&n|128):n<65536?(e[p++]=n>>12|224,e[p++]=n>>6&63|128,e[p++]=63&n|128):(e[p++]=n>>18|240,e[p++]=n>>12&63|128,e[p++]=n>>6&63|128,e[p++]=63&n|128)}return e},e.stringify=function(data){return JSON.stringify(data)},e.validateArgCount=function(t,e,n,r){var o;if(rn&&(o=0===n?"none":"no more than "+n),o)throw new Error(t+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+o+".")},e.validateCallback=function(t,e,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(M(t,e,r)+"must be a valid function.")},e.validateContextObject=function(t,e,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(M(t,e,r)+"must be a valid context object.")},e.validateNamespace=function(t,e,n,r){if((!r||n)&&"string"!=typeof n)throw new Error(M(t,e,r)+"must be a valid firebase namespace.")}}).call(this,n(13))},97:function(t,e,n){"use strict";n.r(e),n.d(e,"LogLevel",function(){return r}),n.d(e,"Logger",function(){return l}),n.d(e,"setLogLevel",function(){return f});var r,o=[];!function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"}(r||(r={}));var c=r.INFO,h=function(t,e){for(var n=[],o=2;o