/*! * @license Firebase v4.8.1 * Build: rev-d8c20f0 * Terms: https://firebase.google.com/terms/ */ try{webpackJsonpFirebase([1],{113:function(t,e,n){n(114)},114:function(t,e,n){"use strict";function r(){return Kt}function o(t){Kt=t}function i(t,e){for(var n=[],r=2;rr)throw new zt(Ht.INVALID_ARGUMENT,"Function "+t+"() requires between "+n+" and "+r+" arguments, but was called with "+P(e.length,"argument")+".")}function I(t,e,n,r){if(!(e instanceof Array)||e.length20&&(t=t.substring(0,20)+"..."),JSON.stringify(t);if("number"==typeof t||"boolean"==typeof t)return""+t;if("object"==typeof t){if(t instanceof Array)return"an array";var e=A(t);return e?"a custom "+e+" object":"an object"}return"function"==typeof t?"a function":u("Unknown wrong type: "+typeof t)}function A(t){if(t.constructor){var e=/function\s+([^\s(]+)\s*\(/,n=e.exec(""+t.constructor);if(n&&n.length>1)return n[1]}return null}function R(t,e,n){if(void 0===n)throw new zt(Ht.INVALID_ARGUMENT,"Function "+t+"() requires a valid "+_(e)+" argument, but it was undefined.")}function O(t,e,n){y(e,function(e,r){if(n.indexOf(e)<0)throw new zt(Ht.INVALID_ARGUMENT,"Unknown option '"+e+"' passed to function "+t+"(). Available options: "+n.join(", "))})}function M(t,e,n,r){var o=N(r);return new zt(Ht.INVALID_ARGUMENT,"Function "+t+"() requires its "+_(n)+" argument to be a "+e+", but it was: "+o)}function _(t){switch(t){case 1:return"first";case 2:return"second";case 3:return"third";default:return t+"th"}}function P(t,e){return t+" "+e+(1===t?"":"s")}function L(t,e){return te?1:0}function x(t,e){return null!==t&&void 0!==t?!(!e||!t.equals(e)):t===e}function B(t,e){if(t.length!==e.length)return!1;for(var n=0;ne?1:t===e?0:isNaN(t)?isNaN(e)?0:-1:1}function Q(t,e){return t===e?0!==t||1/t==1/e:t!==t&&e!==e}function K(t){return null===t||void 0===t}function W(t){return Pe(t)&&t<=_e&&t>=Me}function G(t,e,n){if(n.equals(ve.INSTANCE)){if(e!==xe.EQUAL)throw new zt(Ht.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on null.");return new Ue(t)}if(n.equals(Te.NAN)){if(e!==xe.EQUAL)throw new zt(Ht.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on NaN.");return new Fe(t)}return new Be(t,e,n)}function H(t){switch(t){case Ht.OK:return u("Treated status OK as error");case Ht.CANCELLED:case Ht.UNKNOWN:case Ht.DEADLINE_EXCEEDED:case Ht.RESOURCE_EXHAUSTED:case Ht.INTERNAL:case Ht.UNAVAILABLE:case Ht.UNAUTHENTICATED:return!1;case Ht.INVALID_ARGUMENT:case Ht.NOT_FOUND:case Ht.ALREADY_EXISTS:case Ht.PERMISSION_DENIED:case Ht.FAILED_PRECONDITION:case Ht.ABORTED:case Ht.OUT_OF_RANGE:case Ht.UNIMPLEMENTED:case Ht.DATA_LOSS:return!0;default:return u("Unknown status code: "+t)}}function z(t){var e=en[t];if(void 0!==e)return X(e)}function X(t){if(void 0===t)return a("GRPC error has no .code"),Ht.UNKNOWN;switch(t){case en.OK:return Ht.OK;case en.CANCELLED:return Ht.CANCELLED;case en.UNKNOWN:return Ht.UNKNOWN;case en.DEADLINE_EXCEEDED:return Ht.DEADLINE_EXCEEDED;case en.RESOURCE_EXHAUSTED:return Ht.RESOURCE_EXHAUSTED;case en.INTERNAL:return Ht.INTERNAL;case en.UNAVAILABLE:return Ht.UNAVAILABLE;case en.UNAUTHENTICATED:return Ht.UNAUTHENTICATED;case en.INVALID_ARGUMENT:return Ht.INVALID_ARGUMENT;case en.NOT_FOUND:return Ht.NOT_FOUND;case en.ALREADY_EXISTS:return Ht.ALREADY_EXISTS;case en.PERMISSION_DENIED:return Ht.PERMISSION_DENIED;case en.FAILED_PRECONDITION:return Ht.FAILED_PRECONDITION;case en.ABORTED:return Ht.ABORTED;case en.OUT_OF_RANGE:return Ht.OUT_OF_RANGE;case en.UNIMPLEMENTED:return Ht.UNIMPLEMENTED;case en.DATA_LOSS:return Ht.DATA_LOSS;default:return u("Unknown status code: "+t)}}function Y(t){if(void 0===t)return en.OK;switch(t){case Ht.OK:return en.OK;case Ht.CANCELLED:return en.CANCELLED;case Ht.UNKNOWN:return en.UNKNOWN;case Ht.DEADLINE_EXCEEDED:return en.DEADLINE_EXCEEDED;case Ht.RESOURCE_EXHAUSTED:return en.RESOURCE_EXHAUSTED;case Ht.INTERNAL:return en.INTERNAL;case Ht.UNAVAILABLE:return en.UNAVAILABLE;case Ht.UNAUTHENTICATED:return en.UNAUTHENTICATED;case Ht.INVALID_ARGUMENT:return en.INVALID_ARGUMENT;case Ht.NOT_FOUND:return en.NOT_FOUND;case Ht.ALREADY_EXISTS:return en.ALREADY_EXISTS;case Ht.PERMISSION_DENIED:return en.PERMISSION_DENIED;case Ht.FAILED_PRECONDITION:return en.FAILED_PRECONDITION;case Ht.ABORTED:return en.ABORTED;case Ht.OUT_OF_RANGE:return en.OUT_OF_RANGE;case Ht.UNIMPLEMENTED:return en.UNIMPLEMENTED;case Ht.DATA_LOSS:return en.DATA_LOSS;default:return u("Unknown status code: "+t)}}function J(t){switch(t){case 200:return Ht.OK;case 400:return Ht.INVALID_ARGUMENT;case 401:return Ht.UNAUTHENTICATED;case 403:return Ht.PERMISSION_DENIED;case 404:return Ht.NOT_FOUND;case 409:return Ht.ABORTED;case 416:return Ht.OUT_OF_RANGE;case 429:return Ht.RESOURCE_EXHAUSTED;case 499:return Ht.CANCELLED;case 500:return Ht.UNKNOWN;case 501:return Ht.UNIMPLEMENTED;case 503:return Ht.UNAVAILABLE;case 504:return Ht.DEADLINE_EXCEEDED;default:return t>=200&&t<300?Ht.OK:t>=400&&t<500?Ht.FAILED_PRECONDITION:t>=500&&t<600?Ht.INTERNAL:Ht.UNKNOWN}}function $(){return fn}function Z(){return dn}function tt(){return pn}function et(){return yn}function nt(t,e){e.length>0&&(t.resumeToken=e)}function rt(t,e){c(!K(t),e+" is missing")}function ot(t){return"number"==typeof t?t:"string"==typeof t?parseInt(t,10):u("can't parse "+t)}function it(t,e,n){return e===n||!e&&n in t}function at(t){if(t.search(Bn)>=0)throw new zt(Ht.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not contain '~', '*', '/', '[', or ']'");try{return new(xn.bind.apply(xn,[void 0].concat(t.split("."))))}catch(e){throw new zt(Ht.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'")}}function st(t,e){var n=function(t){switch(t){case Un.Added:return 1;case Un.Modified:case Un.Metadata:return 2;case Un.Removed:return 0;default:return u("Unknown ChangeType: "+t)}};return n(t)-n(e)}function ut(t){for(var e="",n=0;n0&&(e=ht(e)),e=ct(t.get(n),e);return ht(e)}function ct(t,e){for(var n=e,r=t.length,o=0;o=2,"Invalid path "+t),2===e)return c(t.charAt(0)===cr&&t.charAt(1)===hr,"Non-empty path "+t+" had length 2"),oe.EMPTY_PATH;for(var n=e-2,r=[],o="",i=0;in)&&u('Invalid encoded resource path: "'+t+'"'),t.charAt(a+1)){case hr:var s=t.substring(i,a),h=void 0;0===o.length?h=s:(o+=s,h=o,o=""),r.push(h);break;case lr:o+=t.substring(i,a),o+="\0";break;case fr:o+=t.substring(i,a+1);break;default:u('Invalid encoded resource path: "'+t+'"')}i=a+2}return new oe(r)}function ft(t,e){c(0===e,"Unexpected upgrade from version "+e),t.createObjectStore(yr.store,{keyPath:yr.keyPath}),t.createObjectStore(mr.store,{keyPath:mr.keyPath}),t.createObjectStore(Ir.store,{keyPath:Ir.keyPath}).createIndex(Ir.documentTargetsIndex,Ir.documentTargetsKeyPath,{unique:!0}),t.createObjectStore(wr.store,{keyPath:wr.keyPath}).createIndex(wr.queryTargetsIndexName,wr.queryTargetsKeyPath,{unique:!0}),t.createObjectStore(gr.store),t.createObjectStore(br.store),t.createObjectStore(pr.store),t.createObjectStore(Tr.store)}function dt(t){return new Hn(function(e,n){t.onsuccess=function(t){var n=t.target.result;e(n)},t.onerror=function(t){n(t.target.error)}})}function pt(t){return c("string"==typeof t,"Persisting non-string stream token not supported."),t}function yt(t){return vt(t,mr.store)}function mt(t){return vt(t,gr.store)}function gt(t){return vt(t,yr.store)}function vt(t,e){return t instanceof Dr?t.store(e):u("Invalid transaction object provided!")}function bt(t){return Tt(t,wr.store)}function wt(t){return Tt(t,Tr.store)}function It(t){return Tt(t,Ir.store)}function Tt(t,e){return t instanceof Dr?t.store(e):u("Invalid transaction object provided!")}function Et(t){return t instanceof Dr?t.store(br.store):u("Invalid transaction object provided!")}function St(t){return t.path.toArray()}function Ct(t){return void 0!==t.documents}function Dt(t){if(!t)return new so;switch(t.type){case"gapi":return new ho(t.client,t.sessionIndex||"0");case"provider":return t.client;default:throw new zt(Ht.INVALID_ARGUMENT,"makeCredentialsProvider failed due to invalid credential type")}}function kt(t){return Nt(t,["next","error","complete"])}function Nt(t,e){if("object"!=typeof t||null===t)return!1;for(var n=t,r=0,o=e;r=0,"Index for document not found"),o=o.delete(n.doc.key)),n.type!==Un.Removed&&(o=o.add(n.doc),a=o.indexOf(n.doc.key)),{type:Ut(n.type),doc:r,oldIndex:i,newIndex:a}})}function Ut(t){switch(t){case Un.Added:return"added";case Un.Modified:case Un.Metadata:return"modified";case Un.Removed:return"removed";default:return u("Unknown change type: "+t)}}function Ft(t){t.INTERNAL.registerService("firestore",function(t){return new No(t)},g(Ko))}function Vt(t){Ft(t)}Object.defineProperty(e,"__esModule",{value:!0});var qt,jt=n(6),Qt=jt.default.SDK_VERSION;!function(t){t[t.DEBUG=0]="DEBUG",t[t.ERROR=1]="ERROR",t[t.SILENT=2]="SILENT"}(qt||(qt={}));var Kt=qt.ERROR,Wt=function(){function t(){}return t.setPlatform=function(e){t.platform&&u("Platform already defined"),t.platform=e},t.getPlatform=function(){return t.platform||u("Platform not set"),t.platform},t}(),Gt=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Ht={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"},zt=function(t){function e(e,n){var r=t.call(this,n)||this;return r.code=e,r.message=n,r.name="FirebaseError",r.toString=function(){return r.name+": [code="+r.code+"]: "+r.message},r}return Gt(e,t),e}(Error),Xt=function(){function t(){}return t.newId=function(){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e="",n=0;n<20;n++)e+=t.charAt(Math.floor(Math.random()*t.length));return c(20===e.length,"Invalid auto ID: "+e),e},t}(),Yt=function(){function t(t){q(),this.e=t}return t.fromBase64String=function(e){v("Blob.fromBase64String",arguments,1),T("Blob.fromBase64String","string",1,e),q();try{return new t(Wt.getPlatform().atob(e))}catch(t){throw new zt(Ht.INVALID_ARGUMENT,"Failed to construct Blob from Base64 string: "+t)}},t.fromUint8Array=function(e){if(v("Blob.fromUint8Array",arguments,1),V(),!(e instanceof Uint8Array))throw M("Blob.fromUint8Array","Uint8Array",1,e);return new t(Array.prototype.map.call(e,function(t){return String.fromCharCode(t)}).join(""))},t.prototype.toBase64=function(){return v("Blob.toBase64",arguments,0),q(),Wt.getPlatform().btoa(this.e)},t.prototype.toUint8Array=function(){v("Blob.toUint8Array",arguments,0),V();for(var t=new Uint8Array(this.e.length),e=0;e90)throw new zt(Ht.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||e>180)throw new zt(Ht.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this._lat=t,this.d=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.d},enumerable:!0,configurable:!0}),t.prototype.n=function(t){return this._lat===t._lat&&this.d===t.d},t.prototype.r=function(t){return L(this._lat,t._lat)||L(this.d,t.d)},t}(),Zt=function(){function t(t,e,n,r){this.databaseId=t,this.persistenceKey=e,this.host=n,this.ssl=r}return t}(),te="(default)",ee=function(){function t(t,e){this.projectId=t,this.database=e||te}return Object.defineProperty(t.prototype,"isDefaultDatabase",{get:function(){return this.database===te},enumerable:!0,configurable:!0}),t.prototype.equals=function(e){return e instanceof t&&e.projectId===this.projectId&&e.database===this.database},t.prototype.compareTo=function(t){return L(this.projectId,t.projectId)||L(this.database,t.database)},t}(),ne=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),re=function(){function t(t,e,n){this.init(t,e,n)}return t.prototype.init=function(t,e,n){void 0===e?e=0:e>t.length&&u("offset "+e+" out of range "+t.length),void 0===n?n=t.length-e:n>t.length-e&&u("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 r=Object.create(Object.getPrototypeOf(this));return r.init(t,e,n),r},Object.defineProperty(t.prototype,"length",{get:function(){return this.len},enumerable:!0,configurable:!0}),t.prototype.equals=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):u("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,c(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 c(!this.isEmpty(),"Can't call popLast() on empty path"),this.construct(this.segments,this.offset,this.length-1)},t.prototype.firstSegment=function(){return c(!this.isEmpty(),"Can't call firstSegment() on empty path"),this.segments[this.offset]},t.prototype.lastSegment=function(){return c(!this.isEmpty(),"Can't call lastSegment() on empty path"),this.segments[this.limit()-1]},t.prototype.get=function(t){return c(ti)return 1}return t.lengthe.length?1:0},t}(),oe=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ne(e,t),e.prototype.canonicalString=function(){return this.toArray().join("/")},e.prototype.toString=function(){return this.canonicalString()},e.fromString=function(t){if(t.indexOf("//")>=0)throw new zt(Ht.INVALID_ARGUMENT,"Invalid path ("+t+"). Paths must not contain // in them.");return new e(t.split("/").filter(function(t){return t.length>0}))},e.EMPTY_PATH=new e([]),e}(re),ie=/^[_a-zA-Z][_a-zA-Z0-9]*$/,ae=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ne(e,t),e.isValidIdentifier=function(t){return ie.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(t){for(var n=[],r="",o=0,i=function(){if(0===r.length)throw new zt(Ht.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'");n.push(r),r=""},a=!1;o0&&(e=e.right)}return null},t.prototype.getPredecessorKey=function(t){for(var e=this.root,n=null;!e.isEmpty();){var r=this.comparator(t,e.key);if(0===r){if(e.left.isEmpty())return n?n.key:null;for(e=e.left;!e.right.isEmpty();)e=e.right;return e.key}r<0?e=e.left:r>0&&(n=e,e=e.right)}throw u("Attempted to find predecessor key for a nonexistent key. What gives?")},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.reverseTraversal=function(t){return this.root.reverseTraversal(t)},t.prototype.getIterator=function(t){return new le(this.root,null,this.comparator,!1,t)},t.prototype.getIteratorFrom=function(t,e){return new le(this.root,t,this.comparator,!1,e)},t.prototype.getReverseIterator=function(t){return new le(this.root,null,this.comparator,!0,t)},t.prototype.getReverseIteratorFrom=function(t,e){return new le(this.root,t,this.comparator,!0,e)},t}(),le=function(){function t(t,e,n,r,o){this.resultGenerator=o||null,this.isReverse=r,this.nodeStack=[];for(var i=1;!t.isEmpty();)if(i=e?n(t.key,e):1,r&&(i*=-1),i<0)t=this.isReverse?t.left:t.right;else{if(0===i){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}return t.prototype.getNext=function(){c(this.nodeStack.length>0,"getNext() called on iterator when hasNext() is false.");var t,e=this.nodeStack.pop();if(t=this.resultGenerator?this.resultGenerator(e.key,e.value):{key:e.key,value:e.value},this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t},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 this.resultGenerator?this.resultGenerator(t.key,t.value):{key:t.key,value:t.value}},t}(),fe=function(){function t(e,n,r,o,i){this.key=e,this.value=n,this.color=null!=r?r:t.RED,this.left=null!=o?o:t.EMPTY,this.right=null!=i?i:t.EMPTY,this.size=this.left.size+1+this.right.size}return t.prototype.copy=function(e,n,r,o,i){return new t(null!=e?e:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=o?o:this.left,null!=i?i: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)),r.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),e.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.copy(null,null,null,null,t.right.rotateRight()),t=t.rotateLeft(),t=t.colorFlip()),t},t.prototype.moveRedRight=function(){var t=this.colorFlip();return t.left.left.isRed()&&(t=t.rotateRight(),t=t.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 u("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed())throw u("Right child of ("+this.key+","+this.value+") is red");var t=this.left.check();if(t!==this.right.check())throw u("Black depths differ");return t+(this.isRed()?0:1)},t.EMPTY=null,t.RED=!0,t.BLACK=!1,t}(),de=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 fe(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}();fe.EMPTY=new de;var pe,ye=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!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"}(pe||(pe={}));var me,ge=function(){function t(){}return t.prototype.toString=function(){var t=this.value();return null===t?"null":""+t},t.prototype.defaultCompareTo=function(t){return c(this.typeOrder!==t.typeOrder,"Default compareTo should not be used for values of same type."),L(this.typeOrder,t.typeOrder)},t}(),ve=function(t){function e(){var e=t.call(this)||this;return e.typeOrder=pe.NullValue,e.internalValue=null,e}return ye(e,t),e.prototype.value=function(){return null},e.prototype.equals=function(t){return t instanceof e},e.prototype.compareTo=function(t){return t instanceof e?0:this.defaultCompareTo(t)},e.INSTANCE=new e,e}(ge),be=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.BooleanValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?L(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}(ge),we=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.NumberValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.compareTo=function(t){return t instanceof e?j(this.internalValue,t.internalValue):this.defaultCompareTo(t)},e}(ge),Ie=function(t){function e(e){return t.call(this,e)||this}return ye(e,t),e.prototype.equals=function(t){return t instanceof e&&Q(this.internalValue,t.internalValue)},e}(we),Te=function(t){function e(e){var n=t.call(this,e)||this;return n.internalValue=e,n}return ye(e,t),e.prototype.equals=function(t){return t instanceof e&&Q(this.internalValue,t.internalValue)},e.NAN=new e(NaN),e.POSITIVE_INFINITY=new e(1/0),e.NEGATIVE_INFINITY=new e(-1/0),e}(we),Ee=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.StringValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?L(this.internalValue,t.internalValue):this.defaultCompareTo(t)},e}(ge),Se=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.TimestampValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue.toDate()},e.prototype.equals=function(t){return t instanceof e&&this.internalValue.equals(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue.compareTo(t.internalValue):t instanceof Ce?-1:this.defaultCompareTo(t)},e}(ge),Ce=function(t){function e(e){var n=t.call(this)||this;return n.localWriteTime=e,n.typeOrder=pe.TimestampValue,n}return ye(e,t),e.prototype.value=function(){return null},e.prototype.equals=function(t){return t instanceof e&&this.localWriteTime.equals(t.localWriteTime)},e.prototype.compareTo=function(t){return t instanceof e?this.localWriteTime.compareTo(t.localWriteTime):t instanceof Se?1:this.defaultCompareTo(t)},e.prototype.toString=function(){return""},e}(ge),De=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.BlobValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue.n(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue.r(t.internalValue):this.defaultCompareTo(t)},e}(ge),ke=function(t){function e(e,n){var r=t.call(this)||this;return r.databaseId=e,r.key=n,r.typeOrder=pe.RefValue,r}return ye(e,t),e.prototype.value=function(){return this.key},e.prototype.equals=function(t){return t instanceof e&&this.key.equals(t.key)&&this.databaseId.equals(t.databaseId)},e.prototype.compareTo=function(t){if(t instanceof e){var n=this.databaseId.compareTo(t.databaseId);return 0!==n?n:se.comparator(this.key,t.key)}return this.defaultCompareTo(t)},e}(ge),Ne=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.GeoPointValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue.n(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue.r(t.internalValue):this.defaultCompareTo(t)},e}(ge),Ae=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.ObjectValue,n}return ye(e,t),e.prototype.value=function(){var t={};return this.internalValue.inorderTraversal(function(e,n){t[e]=n.value()}),t},e.prototype.forEach=function(t){this.internalValue.inorderTraversal(t)},e.prototype.equals=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var o=n.getNext(),i=r.getNext();if(o.key!==i.key||!o.value.equals(i.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(),i=r.getNext(),a=L(o.key,i.key)||o.value.compareTo(i.value);if(a)return a}return L(n.hasNext(),r.hasNext())}return this.defaultCompareTo(t)},e.prototype.set=function(t,n){if(c(!t.isEmpty(),"Cannot set field for empty path on ObjectValue"),1===t.length)return this.setChild(t.firstSegment(),n);var r=this.child(t.firstSegment());r instanceof e||(r=e.EMPTY);var o=r.set(t.popFirst(),n);return this.setChild(t.firstSegment(),o)},e.prototype.delete=function(t){if(c(!t.isEmpty(),"Cannot delete field for empty path on ObjectValue"),1===t.length)return new e(this.internalValue.remove(t.firstSegment()));var n=this.child(t.firstSegment());if(n instanceof e){var r=n.delete(t.popFirst());return new e(this.internalValue.insert(t.firstSegment(),r))}return this},e.prototype.contains=function(t){return void 0!==this.field(t)},e.prototype.field=function(t){c(!t.isEmpty(),"Can't get field of empty path");var n=this;return t.forEach(function(t){n=n instanceof e?n.internalValue.get(t)||void 0:void 0}),n},e.prototype.toString=function(){return JSON.stringify(this.value())},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 he(L)),e}(ge),Re=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.ArrayValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue.map(function(t){return t.value()})},e.prototype.forEach=function(t){this.internalValue.forEach(t)},e.prototype.equals=function(t){if(t instanceof e){if(this.internalValue.length!==t.internalValue.length)return!1;for(var n=0;n0?this.explicitOrderBy[this.explicitOrderBy.length-1].dir:Ve.ASCENDING;this.memoizedOrderBy.push(a===Ve.ASCENDING?Qe:Ke)}}}return this.memoizedOrderBy},enumerable:!0,configurable:!0}),t.prototype.addFilter=function(e){c(null==this.getInequalityFilterField()||!(e instanceof Be)||!e.isInequality()||e.field.equals(this.getInequalityFilterField()),"Query must only have one inequality field."),c(!se.isDocumentKey(this.path),"No filtering allowed for document query");var n=this.filters.concat([e]);return new t(this.path,this.explicitOrderBy.slice(),n,this.limit,this.startAt,this.endAt)},t.prototype.addOrderBy=function(e){c(!se.isDocumentKey(this.path),"No ordering allowed for document query"),c(!this.startAt&&!this.endAt,"Bounds must be set after orderBy");var n=this.explicitOrderBy.concat([e]);return new t(this.path,n,this.filters.slice(),this.limit,this.startAt,this.endAt)},t.prototype.withLimit=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),e,this.startAt,this.endAt)},t.prototype.withStartAt=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,e,this.endAt)},t.prototype.withEndAt=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,e)},t.prototype.canonicalId=function(){if(null===this.memoizedCanonicalId){var t=this.path.canonicalString();t+="|f:";for(var e=0,n=this.filters;e0&&(t+=", filters: ["+this.filters.join(", ")+"]"),K(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.equals=function(t){if(this.limit!==t.limit)return!1;if(this.orderBy.length!==t.orderBy.length)return!1;for(var e=0;e0?this.explicitOrderBy[0].field:null},t.prototype.getInequalityFilterField=function(){for(var t=0,e=this.filters;t=":return t.GREATER_THAN_OR_EQUAL;case">":return t.GREATER_THAN;default:return u("Unknown relation: "+e)}},t.prototype.toString=function(){return this.name},t.prototype.equals=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}(),Be=function(){function t(t,e,n){this.field=t,this.op=e,this.value=n}return t.prototype.matches=function(t){if(this.field.isKeyField()){c(this.value instanceof ke,"Comparing on key, but filter value not a RefValue");var e=this.value,n=se.comparator(t.key,e.key);return this.matchesComparison(n)}var r=t.field(this.field);return void 0!==r&&this.matchesValue(r)},t.prototype.matchesValue=function(t){return this.value.typeOrder===t.typeOrder&&this.matchesComparison(t.compareTo(this.value))},t.prototype.matchesComparison=function(t){switch(this.op){case xe.LESS_THAN:return t<0;case xe.LESS_THAN_OR_EQUAL:return t<=0;case xe.EQUAL:return 0===t;case xe.GREATER_THAN:return t>0;case xe.GREATER_THAN_OR_EQUAL:return t>=0;default:return u("Unknown relation op"+this.op)}},t.prototype.isInequality=function(){return this.op!==xe.EQUAL},t.prototype.canonicalId=function(){return this.field.canonicalString()+""+this.op+this.value},t.prototype.equals=function(e){return e instanceof t&&this.op.equals(e.op)&&this.field.equals(e.field)&&this.value.equals(e.value)},t.prototype.toString=function(){return this.field.canonicalString()+" "+this.op+" "+this.value.value()},t}(),Ue=function(){function t(t){this.field=t}return t.prototype.matches=function(t){var e=t.field(this.field);return void 0!==e&&null===e.value()},t.prototype.canonicalId=function(){return this.field.canonicalString()+" IS null"},t.prototype.toString=function(){return this.field.canonicalString()+" IS null"},t.prototype.equals=function(e){return e instanceof t&&this.field.equals(e.field)},t}(),Fe=function(){function t(t){this.field=t}return t.prototype.matches=function(t){var e=t.field(this.field).value();return"number"==typeof e&&isNaN(e)},t.prototype.canonicalId=function(){return this.field.canonicalString()+" IS NaN"},t.prototype.toString=function(){return this.field.canonicalString()+" IS NaN"},t.prototype.equals=function(e){return e instanceof t&&this.field.equals(e.field)},t}(),Ve=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}(),qe=function(){function t(t,e){this.position=t,this.before=e}return t.prototype.canonicalId=function(){for(var t=this.before?"b:":"a:",e=0,n=this.position;e=0,"timestamp nanoseconds out of range: "+e),c(e<1e9,"timestamp nanoseconds out of range"+e),c(t>=-62135596800,"timestamp seconds out of range: "+t),c(t<253402300800,"timestamp seconds out of range"+t)}return t.now=function(){return t.fromEpochMilliseconds(Date.now())},t.fromDate=function(e){return t.fromEpochMilliseconds(e.getTime())},t.fromEpochMilliseconds=function(e){var n=Math.floor(e/1e3);return new t(n,1e6*(e-1e3*n))},t.fromISOString=function(e){var n=0,r=We.exec(e);if(c(!!r,"invalid timestamp: "+e),r[1]){var o=r[1];o=(o+"000000000").substr(0,9),n=parseInt(o,10)}var i=new Date(e);return new t(Math.floor(i.getTime()/1e3),n)},t.prototype.toDate=function(){return new Date(this.toEpochMilliseconds())},t.prototype.toEpochMilliseconds=function(){return 1e3*this.seconds+this.nanos/1e6},t.prototype.compareTo=function(t){return this.seconds===t.seconds?L(this.nanos,t.nanos):L(this.seconds,t.seconds)},t.prototype.equals=function(t){return t.seconds===this.seconds&&t.nanos===this.nanos},t.prototype.toString=function(){return"Timestamp(seconds="+this.seconds+", nanos="+this.nanos+")"},t}(),He=function(){function t(t){this.timestamp=t}return t.fromMicroseconds=function(e){var n=Math.floor(e/1e6);return new t(new Ge(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.equals=function(t){return this.timestamp.equals(t.timestamp)},t.prototype.toMicroseconds=function(){return 1e6*this.timestamp.seconds+this.timestamp.nanos/1e3},t.prototype.toString=function(){return"SnapshotVersion("+this.timestamp+")"},t.prototype.toTimestamp=function(){return this.timestamp},t.MIN=new t(new Ge(0,0)),t}();!function(t){t[t.Listen=0]="Listen",t[t.ExistenceFilterMismatch=1]="ExistenceFilterMismatch",t[t.LimboResolution=2]="LimboResolution"}(me||(me={}));var ze,Xe=function(){function t(t,e,n,r,o){void 0===r&&(r=He.MIN),void 0===o&&(o=h()),this.query=t,this.targetId=e,this.purpose=n,this.snapshotVersion=r,this.resumeToken=o}return t.prototype.update=function(e){return new t(this.query,this.targetId,this.purpose,e.snapshotVersion,e.resumeToken)},t.prototype.equals=function(t){return this.targetId===t.targetId&&this.purpose===t.purpose&&this.snapshotVersion.equals(t.snapshotVersion)&&this.resumeToken===t.resumeToken&&this.query.equals(t.query)},t}(),Ye=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Je=function(){function t(t){this.fields=t}return t.prototype.equals=function(t){return B(this.fields,t.fields)},t}(),$e=function(){function t(){}return t.prototype.equals=function(e){return e instanceof t},t.instance=new t,t}(),Ze=function(){function t(t,e){this.field=t,this.transform=e}return t.prototype.equals=function(t){return this.field.equals(t.field)&&this.transform.equals(t.transform)},t}(),tn=function(){function t(t,e){this.version=t,this.transformResults=e}return t}();!function(t){t[t.Set=0]="Set",t[t.Patch=1]="Patch",t[t.Transform=2]="Transform",t[t.Delete=3]="Delete"}(ze||(ze={}));var en,nn=function(){function t(t,e){this.updateTime=t,this.exists=e,c(void 0===t||void 0===e,'Precondition can specify "exists" or "updateTime" but not both')}return t.exists=function(e){return new t(void 0,e)},t.updateTime=function(e){return new t(e)},Object.defineProperty(t.prototype,"isNone",{get:function(){return void 0===this.updateTime&&void 0===this.exists},enumerable:!0,configurable:!0}),t.prototype.isValidFor=function(t){return void 0!==this.updateTime?t instanceof ue&&t.version.equals(this.updateTime):void 0!==this.exists?this.exists?t instanceof ue:null===t||t instanceof ce:(c(this.isNone,"Precondition should be empty"),!0)},t.prototype.equals=function(t){return x(this.updateTime,t.updateTime)&&this.exists===t.exists},t.NONE=new t,t}(),rn=function(){function t(){}return t.prototype.verifyKeyMatches=function(t){null!=t&&c(t.key.equals(this.key),"Can only apply a mutation to a document with the same key")},t.getPostMutationVersion=function(t){return t instanceof ue?t.version:He.MIN},t}(),on=function(t){function e(e,n,r){var o=t.call(this)||this;return o.key=e,o.value=n,o.precondition=r,o.type=ze.Set,o}return Ye(e,t),e.prototype.applyToRemoteDocument=function(t,e){this.verifyKeyMatches(t),c(null==e.transformResults,"Transform results received by SetMutation.");var n=rn.getPostMutationVersion(t);return new ue(this.key,n,this.value,{hasLocalMutations:!1})},e.prototype.applyToLocalView=function(t,e){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var n=rn.getPostMutationVersion(t);return new ue(this.key,n,this.value,{hasLocalMutations:!0})},e.prototype.equals=function(t){return t instanceof e&&this.key.equals(t.key)&&this.value.equals(t.value)&&this.precondition.equals(t.precondition)},e}(rn),an=function(t){function e(e,n,r,o){var i=t.call(this)||this;return i.key=e,i.data=n,i.fieldMask=r,i.precondition=o,i.type=ze.Patch,i}return Ye(e,t),e.prototype.applyToRemoteDocument=function(t,e){if(this.verifyKeyMatches(t),c(null==e.transformResults,"Transform results received by PatchMutation."),!this.precondition.isValidFor(t))return t;var n=rn.getPostMutationVersion(t),r=this.patchDocument(t);return new ue(this.key,n,r,{hasLocalMutations:!1})},e.prototype.applyToLocalView=function(t,e){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var n=rn.getPostMutationVersion(t),r=this.patchDocument(t);return new ue(this.key,n,r,{hasLocalMutations:!0})},e.prototype.equals=function(t){return t instanceof e&&this.key.equals(t.key)&&this.fieldMask.equals(t.fieldMask)&&this.precondition.equals(t.precondition)},e.prototype.patchDocument=function(t){var e;return e=t instanceof ue?t.data:Ae.EMPTY,this.patchObject(e)},e.prototype.patchObject=function(t){for(var e=0,n=this.fieldMask.fields;e=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.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.equals=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,i=r.getNext().key;if(0!==this.comparator(o,i))return!1}return!0},t.prototype.toString=function(){var t=[];return this.forEach(function(e){return t.push(e)}),"SortedSet("+t+")"},t.prototype.copy=function(e){var n=new t(this.comparator);return n.data=e,n},t}(),fn=new he(se.comparator),dn=new he(se.comparator),pn=new he(se.comparator),yn=new ln(se.comparator),mn=function(){function t(t,e,n){this.snapshotVersion=t,this.targetChanges=e,this.documentUpdates=n}return t.prototype.addDocumentUpdate=function(t){this.documentUpdates=this.documentUpdates.insert(t.key,t)},t.prototype.handleExistenceFilterMismatch=function(t){this.targetChanges[t]={mapping:new bn,snapshotVersion:He.MIN,currentStatusUpdate:hn.MarkNotCurrent,resumeToken:h()}},t}();!function(t){t[t.None=0]="None",t[t.MarkNotCurrent=1]="MarkNotCurrent",t[t.MarkCurrent=2]="MarkCurrent"}(hn||(hn={}));var gn,vn=et(),bn=function(){function t(){this.docs=vn}return Object.defineProperty(t.prototype,"documents",{get:function(){return this.docs},enumerable:!0,configurable:!0}),t.prototype.add=function(t){this.docs=this.docs.add(t)},t.prototype.delete=function(t){this.docs=this.docs.delete(t)},t.prototype.equals=function(t){return null!==t&&this.docs.equals(t.docs)},t}(),wn=function(){function t(){this.addedDocuments=vn,this.removedDocuments=vn}return t.prototype.applyToKeySet=function(t){var e=t;return this.addedDocuments.forEach(function(t){return e=e.add(t)}),this.removedDocuments.forEach(function(t){return e=e.delete(t)}),e},t.prototype.add=function(t){this.addedDocuments=this.addedDocuments.add(t),this.removedDocuments=this.removedDocuments.delete(t)},t.prototype.delete=function(t){this.addedDocuments=this.addedDocuments.delete(t),this.removedDocuments=this.removedDocuments.add(t)},t.prototype.equals=function(t){return null!==t&&this.addedDocuments.equals(t.addedDocuments)&&this.removedDocuments.equals(t.removedDocuments)},t}(),In=function(){function t(t,e,n,r){this.updatedTargetIds=t,this.removedTargetIds=e,this.key=n,this.newDoc=r}return t}(),Tn=function(){function t(t,e){this.targetId=t,this.existenceFilter=e}return t}();!function(t){t[t.NoChange=0]="NoChange",t[t.Added=1]="Added",t[t.Removed=2]="Removed",t[t.Current=3]="Current",t[t.Reset=4]="Reset"}(gn||(gn={}));var En=function(){function t(t,e,n,r){void 0===n&&(n=h()),void 0===r&&(r=null),this.state=t,this.targetIds=e,this.resumeToken=n,this.cause=r}return t}(),Sn=function(){function t(t,e,n){this.snapshotVersion=t,this.listenTargets=e,this.existenceFilters={},this.targetChanges={},this.documentUpdates=$(),this.frozen=!1,this.pendingTargetResponses=g(n)}return t.prototype.add=function(t){c(!this.frozen,"Trying to modify frozen WatchChangeAggregator."),t instanceof In?this.addDocumentChange(t):t instanceof En?this.addTargetChange(t):t instanceof Tn?this.addExistenceFilterChange(t):u("Unknown watch change: "+t)},t.prototype.addChanges=function(t){var e=this;c(!this.frozen,"Trying to modify frozen WatchChangeAggregator."),t.forEach(function(t){return e.add(t)})},t.prototype.createRemoteEvent=function(){var t=this,e=this.targetChanges;return p(this.targetChanges,function(n){t.isActiveTarget(n)||delete e[n]}),this.frozen=!0,new mn(this.snapshotVersion,e,this.documentUpdates)},t.prototype.ensureTargetChange=function(t){var e=this.targetChanges[t];return e||(e={currentStatusUpdate:hn.None,snapshotVersion:this.snapshotVersion,mapping:new wn,resumeToken:h()},this.targetChanges[t]=e),e},t.prototype.isActiveTarget=function(t){return!f(this.pendingTargetResponses,t)&&f(this.listenTargets,t)},t.prototype.addDocumentChange=function(t){for(var e=!1,n=0,r=t.updatedTargetIds;n4&&"documents"===t.get(4),"tried to deserialize invalid key "+t),t.popFirst(5)},t.prototype.isValidResourceName=function(t){return t.length>=4&&"projects"===t.get(0)&&"databases"===t.get(2)},t.prototype.toValue=function(t){if(t instanceof ve)return{nullValue:"NULL_VALUE"};if(t instanceof be)return{booleanValue:t.value()};if(t instanceof Ie)return{integerValue:""+t.value()};if(t instanceof Te){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 Ee?{stringValue:t.value()}:t instanceof Ae?{mapValue:this.toMapValue(t)}:t instanceof Re?{arrayValue:this.toArrayValue(t)}:t instanceof Se?{timestampValue:this.toTimestamp(t.internalValue)}:t instanceof Ne?{geoPointValue:{latitude:t.value().latitude,longitude:t.value().longitude}}:t instanceof De?{bytesValue:this.toBytes(t.value())}:t instanceof ke?{referenceValue:this.toResourceName(t.databaseId,t.key.path)}:u("Unknown FieldValue "+JSON.stringify(t))},t.prototype.fromValue=function(t){var e=this,n=t.value_type;if(it(t,n,"nullValue"))return ve.INSTANCE;if(it(t,n,"booleanValue"))return be.of(t.booleanValue);if(it(t,n,"integerValue"))return new Ie(ot(t.integerValue));if(it(t,n,"doubleValue")){if(this.options.useProto3Json){if("NaN"===t.doubleValue)return Te.NAN;if("Infinity"===t.doubleValue)return Te.POSITIVE_INFINITY;if("-Infinity"===t.doubleValue)return Te.NEGATIVE_INFINITY}return new Te(t.doubleValue)}if(it(t,n,"stringValue"))return new Ee(t.stringValue);if(it(t,n,"mapValue"))return this.fromFields(t.mapValue.fields||{});if(it(t,n,"arrayValue")){rt(t.arrayValue,"arrayValue");var r=t.arrayValue.values||[];return new Re(r.map(function(t){return e.fromValue(t)}))}if(it(t,n,"timestampValue"))return rt(t.timestampValue,"timestampValue"),new Se(this.fromTimestamp(t.timestampValue));if(it(t,n,"geoPointValue")){rt(t.geoPointValue,"geoPointValue");var o=t.geoPointValue.latitude||0,i=t.geoPointValue.longitude||0;return new Ne(new $t(o,i))}if(it(t,n,"bytesValue")){rt(t.bytesValue,"bytesValue");var a=this.fromBlob(t.bytesValue);return new De(a)}if(it(t,n,"referenceValue")){rt(t.referenceValue,"referenceValue");var s=this.fromResourceName(t.referenceValue),c=new ee(s.get(1),s.get(3)),h=new se(this.extractLocalPathFromResourceName(s));return new ke(c,h)}return u("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 c(!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){return new ue(this.fromName(t.name),this.fromVersion(t.updateTime),this.fromFields(t.fields||{}),{hasLocalMutations:!1})},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(t){var e=this,n=t,r=Ae.EMPTY;return y(n,function(t,n){r=r.set(new ae([t]),e.fromValue(n))}),r},t.prototype.toMapValue=function(t){return{fields:this.toFields(t)}},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){c(!!t.found,"Tried to deserialize a found document from a missing document."),rt(t.found.name,"doc.found.name"),rt(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 ue(e,n,r,{hasLocalMutations:!1})},t.prototype.fromMissing=function(t){c(!!t.missing,"Tried to deserialize a missing document from a found document."),c(!!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){var e=t.result;return it(t,e,"found")?this.fromFound(t):it(t,e,"missing")?this.fromMissing(t):u("invalid batch get response: "+JSON.stringify(t))},t.prototype.toWatchTargetChangeState=function(t){switch(t){case gn.Added:return"ADD";case gn.Current:return"CURRENT";case gn.NoChange:return"NO_CHANGE";case gn.Removed:return"REMOVE";case gn.Reset:return"RESET";default:return u("Unknown WatchTargetChangeState: "+t)}},t.prototype.toTestWatchChange=function(t){if(t instanceof Tn)return{filter:{count:t.existenceFilter.count,targetId:t.targetId}};if(t instanceof In){if(t.newDoc instanceof ue){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){var 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 En){var n=void 0;return t.cause&&(n={code:Y(t.cause.code),message:t.cause.message}),{targetChange:{targetChangeType:this.toWatchTargetChangeState(t.state),targetIds:t.targetIds,resumeToken:this.unsafeCastProtoByteString(t.resumeToken),cause:n}}}return u("Unrecognized watch change: "+JSON.stringify(t))},t.prototype.fromWatchChange=function(t){var e,n=t.response_type;if(it(t,n,"targetChange")){rt(t.targetChange,"targetChange");var r=this.fromWatchTargetChangeState(t.targetChange.targetChangeType||"NO_CHANGE"),o=t.targetChange.targetIds||[],i=t.targetChange.resumeToken||this.emptyByteString(),a=t.targetChange.cause,s=a&&this.fromRpcStatus(a);e=new En(r,o,i,s||null)}else if(it(t,n,"documentChange")){rt(t.documentChange,"documentChange"),rt(t.documentChange.document,"documentChange.name"),rt(t.documentChange.document.name,"documentChange.document.name"),rt(t.documentChange.document.updateTime,"documentChange.document.updateTime");var c=t.documentChange,h=this.fromName(c.document.name),l=this.fromVersion(c.document.updateTime),f=this.fromFields(c.document.fields||{}),d=new ue(h,l,f,{hasLocalMutations:!1}),p=c.targetIds||[],y=c.removedTargetIds||[];e=new In(p,y,d.key,d)}else if(it(t,n,"documentDelete")){rt(t.documentDelete,"documentDelete"),rt(t.documentDelete.document,"documentDelete.document");var m=t.documentDelete,h=this.fromName(m.document),l=m.readTime?this.fromVersion(m.readTime):He.forDeletedDoc(),d=new ce(h,l),y=m.removedTargetIds||[];e=new In([],y,d.key,d)}else if(it(t,n,"documentRemove")){rt(t.documentRemove,"documentRemove"),rt(t.documentRemove.document,"documentRemove");var g=t.documentRemove,h=this.fromName(g.document),y=g.removedTargetIds||[];e=new In([],y,h,null)}else{if(!it(t,n,"filter"))return u("Unknown change type "+JSON.stringify(t));rt(t.filter,"filter"),rt(t.filter.targetId,"filter.targetId");var v=t.filter,b=v.count||0,w=new cn(b),I=v.targetId;e=new Tn(I,w)}return e},t.prototype.fromWatchTargetChangeState=function(t){return"NO_CHANGE"===t?gn.NoChange:"ADD"===t?gn.Added:"REMOVE"===t?gn.Removed:"CURRENT"===t?gn.Current:"RESET"===t?gn.Reset:u("Got unexpected TargetChange.state: "+t)},t.prototype.versionFromListenResponse=function(t){if(!it(t,t.response_type,"targetChange"))return He.MIN;var e=t.targetChange;return e.targetIds&&e.targetIds.length?He.MIN:e.readTime?this.fromVersion(e.readTime):He.MIN},t.prototype.toMutation=function(t){var e,n=this;if(t instanceof on)e={update:this.toMutationDocument(t.key,t.value)};else if(t instanceof un)e={delete:this.toName(t.key)};else if(t instanceof an)e={update:this.toMutationDocument(t.key,t.data),updateMask:this.toDocumentMask(t.fieldMask)};else{if(!(t instanceof sn))return u("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):nn.NONE;if(t.update){rt(t.update.name,"name");var r=this.fromName(t.update.name),o=this.fromFields(t.update.fields||{});if(t.updateMask){var i=this.fromDocumentMask(t.updateMask);return new an(r,o,i,n)}return new on(r,o,n)}if(t.delete){var r=this.fromName(t.delete);return new un(r,n)}if(t.transform){var r=this.fromName(t.transform.document),a=t.transform.fieldTransforms.map(function(t){return e.fromFieldTransform(t)});return c(!0===n.exists,'Transforms only support precondition "exists == true"'),new sn(r,a)}return u("unknown mutation proto: "+JSON.stringify(t))},t.prototype.toPrecondition=function(t){return c(!t.isNone,"Can't serialize an empty precondition"),void 0!==t.updateTime?{updateTime:this.toVersion(t.updateTime)}:void 0!==t.exists?{exists:t.exists}:u("Unknown precondition")},t.prototype.fromPrecondition=function(t){return void 0!==t.updateTime?nn.updateTime(this.fromVersion(t.updateTime)):void 0!==t.exists?nn.exists(t.exists):nn.NONE},t.prototype.fromWriteResult=function(t){var e=this,n=t.updateTime?this.fromVersion(t.updateTime):null,r=null;return t.transformResults&&t.transformResults.length>0&&(r=t.transformResults.map(function(t){return e.fromValue(t)})),new tn(n,r)},t.prototype.fromWriteResults=function(t){var e=this;return(t||[]).map(function(t){return e.fromWriteResult(t)})},t.prototype.toFieldTransform=function(t){return c(t.transform instanceof $e,"Unknown transform: "+t.transform),{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"}},t.prototype.fromFieldTransform=function(t){c("REQUEST_TIME"===t.setToServerValue,"Unknown transform proto: "+JSON.stringify(t));var e=ae.fromServerFormat(t.fieldPath);return new Ze(e,$e.instance)},t.prototype.toDocumentsTarget=function(t){return{documents:[this.toQueryPath(t.path)]}},t.prototype.fromDocumentsTarget=function(t){var e=t.documents.length;c(1===e,"DocumentsTarget contained other than 1 document: "+e);var n=t.documents[0];return Le.atPath(this.fromQueryPath(n))},t.prototype.toQueryTarget=function(t){var e={structuredQuery:{}};if(t.path.isEmpty())e.parent=this.toQueryPath(oe.EMPTY_PATH);else{var n=t.path;c(n.length%2!=0,"Document queries with filters are not supported."),e.parent=this.toQueryPath(n.popLast()),e.structuredQuery.from=[{collectionId:n.lastSegment()}]}var r=this.toFilter(t.filters);r&&(e.structuredQuery.where=r);var o=this.toOrder(t.orderBy);o&&(e.structuredQuery.orderBy=o);var i=this.toInt32Value(t.limit);return void 0!==i&&(e.structuredQuery.limit=i),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 e=this.fromQueryPath(t.parent),n=t.structuredQuery,r=n.from?n.from.length:0;if(r>0){c(1===r,"StructuredQuery.from with more than one collection is not supported.");var o=n.from[0];e=e.child(o.collectionId)}var i=[];n.where&&(i=this.fromFilter(n.where));var a=[];n.orderBy&&(a=this.fromOrder(n.orderBy));var s=null;n.limit&&(s=this.fromInt32Value(n.limit));var u=null;n.startAt&&(u=this.fromCursor(n.startAt));var h=null;return n.endAt&&(h=this.fromCursor(n.endAt)),new Le(e,a,i,s,u,h)},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 me.Listen:return null;case me.ExistenceFilterMismatch:return"existence-filter-mismatch";case me.LimboResolution:return"limbo-document";default:return u("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)},e.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(t){return t instanceof Be?e.toRelationFilter(t):e.toUnaryFilter(t)});return 1===n.length?n[0]:{compositeFilter:{op:"AND",filters:n}}}},t.prototype.fromFilter=function(t){var e=this;return t?void 0!==t.unaryFilter?[this.fromUnaryFilter(t)]:void 0!==t.fieldFilter?[this.fromRelationFilter(t)]:void 0!==t.compositeFilter?t.compositeFilter.filters.map(function(t){return e.fromFilter(t)}).reduce(function(t,e){return t.concat(e)}):u("Unknown filter: "+JSON.stringify(t)):[]},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(t){var e=this;return{before:t.before,values:t.position.map(function(t){return e.toValue(t)})}},t.prototype.fromCursor=function(t){var e=this,n=!!t.before,r=t.values.map(function(t){return e.fromValue(t)});return new qe(r,n)},t.prototype.toDirection=function(t){return Cn[t.name]},t.prototype.fromDirection=function(t){switch(t){case"ASCENDING":return Ve.ASCENDING;case"DESCENDING":return Ve.DESCENDING;default:return}},t.prototype.toOperatorName=function(t){return Dn[t.name]},t.prototype.fromOperatorName=function(t){switch(t){case"EQUAL":return xe.EQUAL;case"GREATER_THAN":return xe.GREATER_THAN;case"GREATER_THAN_OR_EQUAL":return xe.GREATER_THAN_OR_EQUAL;case"LESS_THAN":return xe.LESS_THAN;case"LESS_THAN_OR_EQUAL":return xe.LESS_THAN_OR_EQUAL;case"OPERATOR_UNSPECIFIED":return u("Unspecified relation");default:return u("Unknown relation")}},t.prototype.toFieldPathReference=function(t){return{fieldPath:t.canonicalString()}},t.prototype.fromFieldPathReference=function(t){return ae.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 je(this.fromFieldPathReference(t.field),this.fromDirection(t.direction))},t.prototype.toRelationFilter=function(t){return t instanceof Be?{fieldFilter:{field:this.toFieldPathReference(t.field),op:this.toOperatorName(t.op),value:this.toValue(t.value)}}:u("Unrecognized filter: "+JSON.stringify(t))},t.prototype.fromRelationFilter=function(t){return new Be(this.fromFieldPathReference(t.fieldFilter.field),this.fromOperatorName(t.fieldFilter.op),this.fromValue(t.fieldFilter.value))},t.prototype.toUnaryFilter=function(t){return t instanceof Fe?{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NAN"}}:t instanceof Ue?{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NULL"}}:u("Unrecognized filter: "+JSON.stringify(t))},t.prototype.fromUnaryFilter=function(t){switch(t.unaryFilter.op){case"IS_NAN":var e=this.fromFieldPathReference(t.unaryFilter.field);return new Fe(e);case"IS_NULL":var n=this.fromFieldPathReference(t.unaryFilter.field);return new Ue(n);case"OPERATOR_UNSPECIFIED":return u("Unspecified filter");default:return u("Unknown filter")}},t.prototype.toDocumentMask=function(t){return{fieldPaths:t.fields.map(function(t){return t.canonicalString()})}},t.prototype.fromDocumentMask=function(t){var e=t.fieldPaths||[],n=e.map(function(t){return ae.fromServerFormat(t)});return new Je(n)},t}(),Nn=n(115),An=function(){function t(t){this.wrappedOnOpen=null,this.wrappedOnClose=null,this.wrappedOnMessage=null,this.sendFn=t.sendFn,this.closeFn=t.closeFn}return t.prototype.onOpen=function(t){c(!this.wrappedOnOpen,"Called onOpen on stream twice!"),this.wrappedOnOpen=t},t.prototype.onClose=function(t){c(!this.wrappedOnClose,"Called onClose on stream twice!"),this.wrappedOnClose=t},t.prototype.onMessage=function(t){c(!this.wrappedOnMessage,"Called onMessage on stream twice!"),this.wrappedOnMessage=t},t.prototype.close=function(){this.closeFn()},t.prototype.send=function(t){this.sendFn(t)},t.prototype.callOnOpen=function(){c(null!==this.wrappedOnOpen,"Cannot call onOpen because no callback was set"),this.wrappedOnOpen()},t.prototype.callOnClose=function(t){c(null!==this.wrappedOnClose,"Cannot call onClose because no callback was set"),this.wrappedOnClose(t)},t.prototype.callOnMessage=function(t){c(null!==this.wrappedOnMessage,"Cannot call onMessage because no callback was set"),this.wrappedOnMessage(t)},t}(),Rn="Connection",On={BatchGetDocuments:"batchGet",Commit:"commit"},Mn="gl-js/ fire/"+Qt,_n=function(){function t(t){this.databaseId=t.databaseId,this.pool=new Nn.XhrIoPool;var e=t.ssl?"https":"http";this.baseUrl=e+"://"+t.host}return t.prototype.modifyHeadersForRequest=function(t,e){if(e)for(var n in e.authHeaders)e.authHeaders.hasOwnProperty(n)&&(t[n]=e.authHeaders[n]);t["X-Goog-Api-Client"]=Mn,t["google-cloud-resource-prefix"]="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database},t.prototype.invokeRPC=function(t,e,n){var r=this,o=this.makeUrl(t);return new Promise(function(a,s){r.pool.getObject(function(c){c.listenOnce(Nn.EventType.COMPLETE,function(){try{switch(c.getLastErrorCode()){case Nn.ErrorCode.NO_ERROR:var e=c.getResponseJson();i(Rn,"XHR received:",JSON.stringify(e)),a(e);break;case Nn.ErrorCode.TIMEOUT:i(Rn,'RPC "'+t+'" timed out'),s(new zt(Ht.DEADLINE_EXCEEDED,"Request time out"));break;case Nn.ErrorCode.HTTP_ERROR:var n=c.getStatus();i(Rn,'RPC "'+t+'" failed with status:',n,"response text:",c.getResponseText()),n>0?s(new zt(J(n),"Server responded with status "+c.getStatusText())):(i(Rn,'RPC "'+t+'" failed'),s(new zt(Ht.UNAVAILABLE,"Connection failed.")));break;default:u('RPC "'+t+'" failed with unanticipated webchannel error '+c.getLastErrorCode()+": "+c.getLastError()+", giving up.")}}finally{i(Rn,'RPC "'+t+'" completed.'),r.pool.releaseObject(c)}});var h=JSON.stringify(e);i(Rn,"XHR sending: ",o+" "+h);var l={"Content-Type":"text/plain"};r.modifyHeadersForRequest(l,n),c.send(o,"POST",h,l,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.v1beta1.Firestore","/",t,"/channel"],r=Object(Nn.createWebChannelTransport)(),o={backgroundChannelTest:!0,httpSessionIdParam:"gsessionid",initMessageHeaders:{},httpHeadersOverwriteParam:"$httpHeaders",sendRawJson:!0,supportsCrossDomainXhr:!0};this.modifyHeadersForRequest(o.initMessageHeaders,e);var a=n.join("");i(Rn,"Creating WebChannel: "+a+" "+o);var s=r.createWebChannel(a,o),u=!1,h=!1,l=new An({sendFn:function(t){h?i(Rn,"Not sending because WebChannel is closed:",t):(u||(i(Rn,"Opening WebChannel transport."),s.open(),u=!0),i(Rn,"WebChannel sending:",t),s.send(t))},closeFn:function(){return s.close()}}),f=function(t,e){s.listen(t,function(t){try{e(t)}catch(t){setTimeout(function(){throw t},0)}})};return f(Nn.WebChannel.EventType.OPEN,function(){h||i(Rn,"WebChannel transport opened.")}),f(Nn.WebChannel.EventType.CLOSE,function(){h||(h=!0,i(Rn,"WebChannel transport closed"),l.callOnClose())}),f(Nn.WebChannel.EventType.ERROR,function(t){h||(h=!0,i(Rn,"WebChannel transport errored:",t),l.callOnClose(new zt(Ht.UNAVAILABLE,"The operation could not be completed")))}),f(Nn.WebChannel.EventType.MESSAGE,function(t){if(!h){var e=t.data[0];c(!!e,"Got a webchannel message without data.");var n=e.error||e[0]&&e[0].error;if(n){i(Rn,"WebChannel received error:",n);var r=n.status,o=z(r),a=n.message;void 0===o&&(o=Ht.INTERNAL,a="Unknown error status: "+r+" with message "+n.message),h=!0,l.callOnClose(new zt(o,a)),s.close()}else i(Rn,"WebChannel received:",e),l.callOnMessage(e)}}),setTimeout(function(){l.callOnOpen()},0),l},t.prototype.makeUrl=function(t){var e=On[t];c(void 0!==e,"Unknown REST mapping for: "+t);var n=[this.baseUrl,"/","v1beta1"];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}(),Pn=function(){function t(){this.emptyByteString="",this.base64Available="undefined"!=typeof atob}return t.prototype.loadConnection=function(t){return Promise.resolve(new _n(t))},t.prototype.newSerializer=function(t){return new kn(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}();Wt.setPlatform(new Pn);var Ln,xn=function(){function t(){for(var t=[],e=0;e=0&&(r.listeners.splice(o,1),n=0===r.listeners.length)}return n?(this.queries.delete(e),this.syncEngine.unlisten(e)):Promise.resolve()},t.prototype.onChange=function(t){for(var e=0,n=t;e0||t.syncStateChanged,"We got a new snapshot with no changes?"),!this.options.includeDocumentMetadataChanges){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.includeQueryMetadataChanges},t.prototype.raiseInitialEvent=function(e){c(!this.raisedInitialEvent,"Trying to raise initial events for second time"),e={query:e.query,docs:e.docs,oldDocs:jn.emptySet(e.docs),docChanges:t.getInitialViewChanges(e),fromCache:e.fromCache,hasPendingWrites:e.hasPendingWrites,syncStateChanged:!0},this.raisedInitialEvent=!0,this.queryObserver.next(e)},t.getInitialViewChanges=function(t){var e=[];return t.docs.forEach(function(t){e.push({type:Un.Added,doc:t})}),e},t}(),Hn=function(){function t(t){var e=this;this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=null,this.isDone=!1,this.callbackAttached=!1,t(function(t){e.isDone=!0,e.result=t,e.nextCallback&&e.nextCallback(t)},function(t){e.isDone=!0,e.error=t,e.catchCallback&&e.catchCallback(t)})}return t.prototype.catch=function(t){return this.next(void 0,t)},t.prototype.next=function(e,n){var r=this;return this.callbackAttached&&u("Called next() or catch() twice for PersistencePromise"),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(n,this.error):this.wrapSuccess(e,this.result):new t(function(t,o){r.nextCallback=function(n){r.wrapSuccess(e,n).next(t,o)},r.catchCallback=function(e){r.wrapFailure(n,e).next(t,o)}})},t.prototype.toPromise=function(){var t=this;return new Promise(function(e,n){t.next(e,n)})},t.prototype.wrapUserFunction=function(e){try{var n=e();return n instanceof t?n:t.resolve(n)}catch(e){return t.reject(e)}},t.prototype.wrapSuccess=function(e,n){return e?this.wrapUserFunction(function(){return e(n)}):t.resolve(n)},t.prototype.wrapFailure=function(e,n){return e?this.wrapUserFunction(function(){return e(n)}):t.reject(n)},t.resolve=function(e){return new t(function(t,n){t(e)})},t.reject=function(e){return new t(function(t,n){n(e)})},t.waitFor=function(e){return e.reduce(function(t,e,n){return t.next(function(){return e})},t.resolve())},t.map=function(e){var n=[],r=!0,o=t.resolve(null);return e.reduce(function(t,e){return t.next(function(t){return r||n.push(t),r=!1,e})},o).next(function(t){return n.push(t),n})},t}(),zn=function(){function t(){this.isEager=!0,this.sources=[],this.potentialGarbage=et()}return t.prototype.addGarbageSource=function(t){this.sources.push(t),t.setGarbageCollector(this)},t.prototype.removeGarbageSource=function(t){this.sources.splice(this.sources.indexOf(t),1),t.setGarbageCollector(null)},t.prototype.addPotentialGarbageKey=function(t){this.potentialGarbage=this.potentialGarbage.add(t)},t.prototype.collectGarbage=function(t){var e=this,n=[],r=et();return this.potentialGarbage.forEach(function(o){var i=e.documentHasAnyReferences(t,o);n.push(i.next(function(t){return t||(r=r.add(o)),Hn.resolve()}))}),this.potentialGarbage=et(),Hn.waitFor(n).next(function(){return r})},t.prototype.documentHasAnyReferences=function(t,e){var n=Hn.resolve(!1);return this.sources.map(function(n){return function(){return n.containsKey(t,e)}}).reduce(function(t,e){return t.next(function(t){return t?Hn.resolve(!0):e()})},n)},t}(),Xn=function(){function t(t,e,n){this.query=t,this.addedKeys=e,this.removedKeys=n}return t.fromSnapshot=function(e){for(var n=et(),r=et(),o=0,i=e.docChanges;o>$n<<$n,r=e-n;this.previousId=r>=t?n|this.generatorId:(n|this.generatorId)-(1<<$n)}return t.prototype.next=function(){return this.previousId+=1<<$n,this.previousId},t.forLocalStore=function(e){return void 0===e&&(e=0),new t(Vn.LocalStore,e)},t.forSyncEngine=function(){return new t(Vn.SyncEngine)},t}(),er=function(){function t(t){this.key=t}return t}(),nr=function(){function t(t){this.key=t}return t}(),rr=function(){function t(t,e){this.query=t,this.syncedDocuments=e,this.syncState=null,this.current=!1,this.limboDocuments=et(),this.mutatedKeys=et(),this.documentSet=new jn(t.docComparator.bind(t))}return t.prototype.computeDocChanges=function(t,e){var n=this,r=e?e.changeSet:new qn,o=e?e.documentSet:this.documentSet,i=e?e.mutatedKeys:this.mutatedKeys,a=o,s=!1,u=this.query.hasLimit()&&o.size===this.query.limit?o.last():null;if(t.inorderTraversal(function(t,e){var h=o.get(t),l=e instanceof ue?e:null;if(l&&(c(t.equals(l.key),"Mismatching keys found in document changes: "+t+" != "+l.key),l=n.query.matches(l)?l:null),l?(a=a.add(l),i=l.hasLocalMutations?i.add(t):i.delete(t)):(a=a.delete(t),i=i.delete(t)),h&&l){var f=h.data.equals(l.data);f&&h.hasLocalMutations===l.hasLocalMutations||(f?r.track({type:Un.Metadata,doc:l}):r.track({type:Un.Modified,doc:l}),u&&n.query.docComparator(l,u)>0&&(s=!0))}else!h&&l?r.track({type:Un.Added,doc:l}):h&&!l&&(r.track({type:Un.Removed,doc:h}),u&&(s=!0))}),this.query.hasLimit())for(;a.size>this.query.limit;){var h=a.last();a=a.delete(h.key),r.track({type:Un.Removed,doc:h})}return c(!s||!e,"View was refilled using docs that themselves needed refilling."),{documentSet:a,changeSet:r,needsRefill:s,mutatedKeys:i}},t.prototype.applyChanges=function(t,e){var n=this;c(!t.needsRefill,"Cannot apply changes that need a refill");var r=this.documentSet;this.documentSet=t.documentSet,this.mutatedKeys=t.mutatedKeys;var o=t.changeSet.getChanges();o.sort(function(t,e){return st(t.type,e.type)||n.query.docComparator(t.doc,e.doc)});var i=this.applyTargetChange(e),a=0===this.limboDocuments.size&&this.current,s=a?Fn.Synced:Fn.Local,u=s!==this.syncState;return this.syncState=s,0!==o.length||u?{snapshot:{query:this.query,docs:t.documentSet,oldDocs:r,docChanges:o,fromCache:s===Fn.Local,syncStateChanged:u,hasPendingWrites:!t.mutatedKeys.isEmpty()},limboChanges:i}:{limboChanges:i}},t.prototype.shouldBeInLimbo=function(t){return!this.syncedDocuments.has(t)&&!!this.documentSet.has(t)&&!this.documentSet.get(t).hasLocalMutations},t.prototype.applyTargetChange=function(t){var e=this;if(t){var n=t.mapping;switch(n instanceof bn?this.syncedDocuments=n.documents:n instanceof wn&&(this.syncedDocuments=n.applyToKeySet(this.syncedDocuments)),t.currentStatusUpdate){case hn.MarkCurrent:this.current=!0;break;case hn.MarkNotCurrent:this.current=!1;break;case hn.None:break;default:u("Unknown current status update: "+t.currentStatusUpdate)}}var r=this.limboDocuments;this.limboDocuments=et(),this.current&&this.documentSet.forEach(function(t){e.shouldBeInLimbo(t.key)&&(e.limboDocuments=e.limboDocuments.add(t.key))});var o=[];return r.forEach(function(t){e.limboDocuments.has(t)||o.push(new nr(t))}),this.limboDocuments.forEach(function(t){r.has(t)||o.push(new er(t))}),o},t}(),or=function(){function t(t,e,n,r){this.query=t,this.targetId=e,this.resumeToken=n,this.view=r}return t}(),ir=function(){function t(t,e,n){this.localStore=t,this.remoteStore=e,this.currentUser=n,this.viewHandler=null,this.errorHandler=null,this.queryViewsByQuery=new Qn(function(t){return t.canonicalId()}),this.queryViewsByTarget={},this.limboTargetsByKey=new he(se.comparator),this.limboKeysByTarget={},this.limboDocumentRefs=new Yn,this.limboCollector=new zn,this.mutationUserCallbacks={},this.targetIdGenerator=tr.forSyncEngine()}return t.prototype.subscribe=function(t,e){c(null!==t&&null!==e,"View and error handlers cannot be null"),c(null===this.viewHandler&&null===this.errorHandler,"SyncEngine already has a subscriber."),this.viewHandler=t,this.errorHandler=e,this.limboCollector.addGarbageSource(this.limboDocumentRefs)},t.prototype.listen=function(t){var e=this;return this.assertSubscribed("listen()"),c(!this.queryViewsByQuery.has(t),"We already listen to the query: "+t),this.localStore.allocateQuery(t).then(function(n){return e.localStore.executeQuery(t).then(function(r){return e.localStore.remoteDocumentKeys(n.targetId).then(function(o){var i=new rr(t,o),a=i.computeDocChanges(r),s=i.applyChanges(a);c(0===s.limboChanges.length,"View returned limbo docs before target ack from the server."),c(!!s.snapshot,"applyChanges for new view should always return a snapshot");var u=new or(t,n.targetId,n.resumeToken,i);e.queryViewsByQuery.set(t,u),e.queryViewsByTarget[n.targetId]=u,e.viewHandler([s.snapshot]),e.remoteStore.listen(n)})}).then(function(){return n.targetId})})},t.prototype.unlisten=function(t){var e=this;this.assertSubscribed("unlisten()");var n=this.queryViewsByQuery.get(t);return c(!!n,"Trying to unlisten on query not found:"+t),this.localStore.releaseQuery(t).then(function(){return e.remoteStore.unlisten(n.targetId),e.removeAndCleanupQuery(n).then(function(){return e.localStore.collectGarbage()})})},t.prototype.write=function(t,e){var n=this;return this.assertSubscribed("write()"),this.localStore.localWrite(t).then(function(t){return n.addMutationCallback(t.batchId,e),n.emitNewSnapsAndNotifyLocalStore(t.changes)}).then(function(){return n.remoteStore.fillWritePipeline()})},t.prototype.wrapUpdateFunctionError=function(t){return t},t.prototype.runTransaction=function(t,e){var n=this;void 0===e&&(e=5),c(e>=0,"Got negative number of retries for transaction.");var r=this.remoteStore.createTransaction();return function(){try{var e=t(r);return!K(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()"),p(t.targetChanges,function(n,r){var o=e.limboKeysByTarget[n];o&&r.currentStatusUpdate===hn.MarkCurrent&&!t.documentUpdates.get(o)&&t.addDocumentUpdate(new ce(o,t.snapshotVersion))}),this.localStore.applyRemoteEvent(t).then(function(n){return e.emitNewSnapsAndNotifyLocalStore(n,t)})},t.prototype.rejectListen=function(t,e){var n=this;this.assertSubscribed("rejectListens()");var r=this.limboKeysByTarget[t];if(r){this.limboTargetsByKey=this.limboTargetsByKey.remove(r),delete this.limboKeysByTarget[t];var o=new he(se.comparator);o=o.insert(r,new ce(r,He.forDeletedDoc()));var i=new mn(He.MIN,{},o);return this.applyRemoteEvent(i)}var a=this.queryViewsByTarget[t];return c(!!a,"Unknown targetId: "+t),this.localStore.releaseQuery(a.query).then(function(){return n.removeAndCleanupQuery(a).then(function(){n.errorHandler(a.query,e)})})},t.prototype.applySuccessfulWrite=function(t){var e=this;return this.assertSubscribed("applySuccessfulWrite()"),this.processUserCallback(t.batch.batchId,null),this.localStore.acknowledgeBatch(t).then(function(t){return e.emitNewSnapsAndNotifyLocalStore(t)})},t.prototype.rejectFailedWrite=function(t,e){var n=this;return this.assertSubscribed("rejectFailedWrite()"),this.processUserCallback(t,e),this.localStore.rejectBatch(t).then(function(t){return n.emitNewSnapsAndNotifyLocalStore(t)})},t.prototype.addMutationCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];n||(n=new he(L)),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&&(c(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){return this.queryViewsByQuery.delete(t.query),delete this.queryViewsByTarget[t.targetId],this.limboDocumentRefs.removeReferencesForId(t.targetId),this.gcLimboDocuments()},t.prototype.updateTrackedLimbos=function(t,e){for(var n=0,r=e;n0||t.indexOf("Trident/")>0||t.indexOf("Edge/")>0)},t.prototype.runTransaction=function(t,e,n){var r=new Dr(this.db,t,e),o=n(r).catch(function(t){return r.abort(),Hn.reject(t)}).toPromise();return r.completionPromise.then(function(){return o})},t.prototype.close=function(){this.db.close()},t}(),Cr=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 dt(this.dbCursor.delete())},t}(),Dr=function(){function t(t,e,n){var r=this;this.aborted=!1,this.transaction=t.transaction(n,e),this.completionPromise=new Promise(function(t,e){r.transaction.onabort=r.transaction.oncomplete=function(e){t()},r.transaction.onerror=function(t){e(t.target.error)}})}return t.prototype.abort=function(){this.aborted||(i("SimpleDb","Aborting transaction."),this.aborted=!0,this.transaction.abort())},t.prototype.store=function(t){var e=this.transaction.objectStore(t);return c(!!e,"Object store not part of transaction: "+t),new kr(e)},t}(),kr=function(){function t(t){this.store=t}return t.prototype.put=function(t,e){var n;return void 0!==e?(i("SimpleDb","PUT",this.store.name,t,e),n=this.store.put(e,t)):(i("SimpleDb","PUT",this.store.name,"",t),n=this.store.put(t)),dt(n)},t.prototype.get=function(t){var e=this;return dt(this.store.get(t)).next(function(n){return void 0===n&&(n=null),i("SimpleDb","GET",e.store.name,t,n),n})},t.prototype.delete=function(t){return i("SimpleDb","DELETE",this.store.name,t),dt(this.store.delete(t))},t.prototype.loadAll=function(t,e){var n=this.cursor(this.options(t,e)),r=[];return this.iterateCursor(n,function(t,e){r.push(e)}).next(function(){return r})},t.prototype.deleteAll=function(t,e){i("SimpleDb","DELETE ALL",this.store.name);var n=this.options(t,e);n.keysOnly=!1;var r=this.cursor(n);return this.iterateCursor(r,function(t,e,n){return n.delete()})},t.prototype.iterate=function(t,e){var n;e?n=t:(n={},e=t);var r=this.cursor(n);return this.iterateCursor(r,e)},t.prototype.iterateCursor=function(t,e){var n=[];return new Hn(function(r,o){t.onerror=function(t){o(t.target.error)},t.onsuccess=function(t){var o=t.target.result;if(!o)return void r();var i=new Cr(o),a=e(o.primaryKey,o.value,i);a instanceof Hn&&n.push(a),i.isDone?r():null===i.skipToKey?o.continue():o.continue(i.skipToKey)}}).next(function(){return Hn.waitFor(n)})},t.prototype.options=function(t,e){var n=void 0;return void 0!==t&&("string"==typeof t?n=t:(c(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}(),Nr=function(){function t(t,e){this.userId=t,this.serializer=e,this.garbageCollector=null}return t.forUser=function(e,n){return c(""!==e.uid,"UserID must not be an empty string."),new t(e.isUnauthenticated()?"":e.uid,n)},t.prototype.start=function(e){var n=this;return t.loadNextBatchIdFromDb(e).next(function(t){return n.nextBatchId=t,gt(e).get(n.userId)}).next(function(t){return t||(t=new yr(n.userId,ar,"")),n.metadata=t,n.metadata.lastAcknowledgedBatchId>=n.nextBatchId?n.checkEmpty(e).next(function(t){return c(t,"Reset nextBatchID is only possible when the queue is empty"),n.metadata.lastAcknowledgedBatchId=ar,gt(e).put(n.metadata)}):Hn.resolve()})},t.loadNextBatchIdFromDb=function(t){var e=ar;return yt(t).iterate({reverse:!0},function(t,n,r){var o=t[0];if(t[1]>e&&(e=n.batchId),""===o)r.done();else{var i=U(o);r.skip([i])}}).next(function(){return e+1})},t.prototype.checkEmpty=function(t){var e=!0,n=IDBKeyRange.bound(this.keyForBatchId(Number.NEGATIVE_INFINITY),this.keyForBatchId(Number.POSITIVE_INFINITY));return yt(t).iterate({range:n},function(t,n,r){e=!1,r.done()}).next(function(){return e})},t.prototype.getNextBatchId=function(t){return Hn.resolve(this.nextBatchId)},t.prototype.getHighestAcknowledgedBatchId=function(t){return Hn.resolve(this.metadata.lastAcknowledgedBatchId)},t.prototype.acknowledgeBatch=function(t,e,n){var r=e.batchId;return c(r>this.metadata.lastAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order"),this.metadata.lastAcknowledgedBatchId=r,this.metadata.lastStreamToken=pt(n),gt(t).put(this.metadata)},t.prototype.getLastStreamToken=function(t){return Hn.resolve(this.metadata.lastStreamToken)},t.prototype.setLastStreamToken=function(t,e){return this.metadata.lastStreamToken=pt(e),gt(t).put(this.metadata)},t.prototype.addMutationBatch=function(t,e,n){var r=this,o=this.nextBatchId;this.nextBatchId++;var i=new sr(o,e,n),a=this.serializer.toDbMutationBatch(this.userId,i);return yt(t).put(a).next(function(){for(var e=[],i=0,a=n;ie,"Should have found mutation after "+e),o=n.serializer.fromDbMutationBatch(r)),i.done()}).next(function(){return o})},t.prototype.getAllMutationBatches=function(t){var e=this,n=IDBKeyRange.bound(this.keyForBatchId(ar),this.keyForBatchId(Number.POSITIVE_INFINITY));return yt(t).loadAll(n).next(function(t){return t.map(function(t){return e.serializer.fromDbMutationBatch(t)})})},t.prototype.getAllMutationBatchesThroughBatchId=function(t,e){var n=this,r=IDBKeyRange.bound(this.keyForBatchId(ar),this.keyForBatchId(e));return yt(t).loadAll(r).next(function(t){return t.map(function(t){return n.serializer.fromDbMutationBatch(t)})})},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=gr.prefixForPath(this.userId,e.path),o=IDBKeyRange.lowerBound(r),i=[];return mt(t).iterate({range:o},function(r,o,a){var s=r[0],c=r[1],h=r[2],l=lt(c);if(s!==n.userId||!e.path.equals(l))return void a.done();var f=n.keyForBatchId(h);return yt(t).get(f).next(function(t){null===t&&u("Dangling document-mutation reference found: "+r+" which points to "+f),i.push(n.serializer.fromDbMutationBatch(t))})}).next(function(){return i})},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=this;c(!e.isDocumentQuery(),"Document queries shouldn't go down this path");var r=e.path,o=r.length+1,i=gr.prefixForPath(this.userId,r),a=(i[1],IDBKeyRange.lowerBound(i)),s=new ln(L);return mt(t).iterate({range:a},function(t,e,i){var a=t[0],u=t[1],c=t[2],h=lt(u);if(a!==n.userId||!r.isPrefixOf(h))return void i.done();h.length===o&&(s=s.add(c))}).next(function(){var e=[],r=[];return s.forEach(function(o){var i=n.keyForBatchId(o);r.push(yt(t).get(i).next(function(t){null===t&&u("Dangling document-mutation reference found, which points to "+i),e.push(n.serializer.fromDbMutationBatch(t))}))}),Hn.waitFor(r).next(function(){return e})})},t.prototype.removeMutationBatches=function(t,e){for(var n=yt(t),r=mt(t),o=[],i=this,a=0,s=e;athis.metadata.highestTargetId?(this.metadata.highestTargetId=r,o.next(function(){return wt(t).put(Tr.key,n.metadata)})):o},t.prototype.removeQueryData=function(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(function(){bt(t).delete(e.targetId)})},t.prototype.getQueryData=function(t,e){var n=this,r=e.canonicalId(),o=IDBKeyRange.bound([r,Number.NEGATIVE_INFINITY],[r,Number.POSITIVE_INFINITY]),i=null;return bt(t).iterate({range:o,index:wr.queryTargetsIndexName},function(t,r,o){var a=n.serializer.fromDbTarget(r);e.equals(a.query)&&(i=a,o.done())}).next(function(){return i})},t.prototype.addMatchingKeys=function(t,e,n){var r=[],o=It(t);return e.forEach(function(t){var e=ut(t.path);r.push(o.put(new Ir(n,e)))}),Hn.waitFor(r)},t.prototype.removeMatchingKeys=function(t,e,n){var r=this,o=[],i=It(t);return e.forEach(function(t){var e=ut(t.path);o.push(i.delete([n,e])),null!==r.garbageCollector&&r.garbageCollector.addPotentialGarbageKey(t)}),Hn.waitFor(o)},t.prototype.removeMatchingKeysForTargetId=function(t,e){var n=It(t),r=IDBKeyRange.bound([e],[e+1],!1,!0);return this.notifyGCForRemovedKeys(t,r).next(function(){return n.delete(r)})},t.prototype.notifyGCForRemovedKeys=function(t,e){var n=this,r=It(t);return null!==this.garbageCollector&&this.garbageCollector.isEager?r.iterate({range:e,keysOnly:!0},function(t,e,r){var o=lt(t[1]),i=new se(o);c(null!==n.garbageCollector,"GarbageCollector for query cache set to null during key removal."),n.garbageCollector.addPotentialGarbageKey(i)}):Hn.resolve()},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=IDBKeyRange.bound([e],[e+1],!1,!0),r=It(t),o=et();return r.iterate({range:n,keysOnly:!0},function(t,e,n){var r=lt(t[1]),i=new se(r);o=o.add(i)}).next(function(){return o})},t.prototype.setGarbageCollector=function(t){this.garbageCollector=t},t.prototype.containsKey=function(t,e){c(null!==t,"Persistence Transaction cannot be null for query cache containsKey");var n=ut(e.path),r=IDBKeyRange.bound([n],[F(n)],!1,!0),o=0;return It(t).iterate({index:Ir.documentTargetsIndex,keysOnly:!0,range:r},function(t,e,n){o++,n.done()}).next(function(){return o>0})},t}(),Rr=function(){function t(t){this.serializer=t}return t.prototype.addEntry=function(t,e){return Et(t).put(St(e.key),this.serializer.toDbRemoteDocument(e))},t.prototype.removeEntry=function(t,e){return Et(t).delete(St(e))},t.prototype.getEntry=function(t,e){var n=this;return Et(t).get(St(e)).next(function(t){return t?n.serializer.fromDbRemoteDocument(t):null})},t.prototype.getDocumentsMatchingQuery=function(t,e){var n=this,r=Z(),o=e.path.toArray(),i=IDBKeyRange.lowerBound(o);return Et(t).iterate({range:i},function(t,o,i){var a=n.serializer.fromDbRemoteDocument(o);e.path.isPrefixOf(a.key.path)?a instanceof ue&&e.matches(a)&&(r=r.insert(a.key,a)):i.done()}).next(function(){return r})},t}(),Or=function(){function t(t){this.remoteSerializer=t}return t.prototype.fromDbRemoteDocument=function(t){if(t.document)return this.remoteSerializer.fromDocument(t.document);if(t.noDocument){var e=se.fromSegments(t.noDocument.path),n=t.noDocument.readTime,r=new Ge(n.seconds,n.nanos);return new ce(e,He.fromTimestamp(r))}return u("Unexpected DbRemoteDocument")},t.prototype.toDbRemoteDocument=function(t){if(t instanceof ue){var e=this.remoteSerializer.toDocument(t);return new br(null,e)}var n=t.key.path.toArray(),r=t.version.toTimestamp(),o=new dr(r.seconds,r.nanos);return new br(new vr(n,o),null)},t.prototype.toDbMutationBatch=function(t,e){var n=this,r=e.mutations.map(function(t){return n.remoteSerializer.toMutation(t)});return new mr(t,e.batchId,e.localWriteTime.toEpochMilliseconds(),r)},t.prototype.fromDbMutationBatch=function(t){var e=this,n=t.mutations.map(function(t){return e.remoteSerializer.fromMutation(t)}),r=Ge.fromEpochMilliseconds(t.localWriteTimeMs);return new sr(t.batchId,r,n)},t.prototype.fromDbTarget=function(t){var e,n=new Ge(t.readTime.seconds,t.readTime.nanos),r=He.fromTimestamp(n);return e=Ct(t.query)?this.remoteSerializer.fromDocumentsTarget(t.query):this.remoteSerializer.fromQueryTarget(t.query),new Xe(e,t.targetId,me.Listen,r,t.resumeToken)},t.prototype.toDbTarget=function(t){c(me.Listen===t.purpose,"Only queries with purpose "+me.Listen+" may be stored, got "+t.purpose);var e,n=t.snapshotVersion.toTimestamp(),r=new dr(n.seconds,n.nanos);e=t.query.isDocumentQuery()?this.remoteSerializer.toDocumentsTarget(t.query):this.remoteSerializer.toQueryTarget(t.query),c("string"==typeof t.resumeToken,"Persisting non-string resume token not supported.");var o=t.resumeToken;return new wr(t.targetId,t.query.canonicalId(),r,o,0,e)},t}(),Mr="There is another tab open with offline persistence enabled. Only one such tab is allowed at a time. The other tab must be closed or persistence must be disabled.",_r=function(){function t(e,n){this.ownerId=this.generateOwnerId(),this.dbName=e+t.MAIN_DATABASE,this.serializer=new Or(n),this.localStoragePrefix=e}return t.prototype.start=function(){var e=this;return t.isAvailable()?(c(!this.started,"IndexedDbPersistence double-started!"),this.started=!0,Sr.openOrCreate(this.dbName,1,ft).then(function(t){e.simpleDb=t}).then(function(){return e.tryAcquireOwnerLease()}).then(function(){e.scheduleOwnerLeaseRefreshes(),e.attachWindowUnloadHook()})):(this.persistenceError=new zt(Ht.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled."),Promise.reject(this.persistenceError))},t.prototype.shutdown=function(){var t=this;return c(this.started,"IndexedDbPersistence shutdown without start!"),this.started=!1,this.detachWindowUnloadHook(),this.stopOwnerLeaseRefreshes(),this.releaseOwnerLease().then(function(){t.simpleDb.close()})},t.prototype.getMutationQueue=function(t){return Nr.forUser(t,this.serializer)},t.prototype.getQueryCache=function(){return new Ar(this.serializer)},t.prototype.getRemoteDocumentCache=function(){return new Rr(this.serializer)},t.prototype.runTransaction=function(t,e){var n=this;return this.persistenceError?Promise.reject(this.persistenceError):(i("IndexedDbPersistence","Starting transaction:",t),this.simpleDb.runTransaction("readwrite",Er,function(t){return n.ensureOwnerLease(t).next(function(){return e(t)})}))},t.isAvailable=function(){return Sr.isAvailable()},t.buildStoragePrefix=function(t){var e=t.databaseId.projectId;return t.databaseId.isDefaultDatabase||(e+="."+t.databaseId.database),"firestore/"+t.persistenceKey+"/"+e+"/"},t.prototype.tryAcquireOwnerLease=function(){var t=this;return this.simpleDb.runTransaction("readwrite",[pr.store],function(e){var n=e.store(pr.store);return n.get("owner").next(function(e){if(t.validOwner(e))return i("IndexedDbPersistence","Valid owner already. Failing. Current owner:",e),t.persistenceError=new zt(Ht.FAILED_PRECONDITION,Mr),Hn.reject(t.persistenceError);var r=new pr(t.ownerId,Date.now());return i("IndexedDbPersistence","No valid owner. Acquiring owner lease. Current owner:",e,"New owner:",r),n.put("owner",r)})})},t.prototype.releaseOwnerLease=function(){var t=this;return this.simpleDb.runTransaction("readwrite",[pr.store],function(e){var n=e.store(pr.store);return n.get("owner").next(function(e){return null!==e&&e.ownerId===t.ownerId?(i("IndexedDbPersistence","Releasing owner lease."),n.delete("owner")):Hn.resolve()})})},t.prototype.ensureOwnerLease=function(t){var e=this;return t.store(pr.store).get("owner").next(function(t){return null===t||t.ownerId!==e.ownerId?(e.persistenceError=new zt(Ht.FAILED_PRECONDITION,Mr),Hn.reject(e.persistenceError)):Hn.resolve()})},t.prototype.validOwner=function(t){var e=Date.now(),n=e-5e3,r=e;return!(null===t||t.leaseTimestampMsr?(a("Persistence owner-lease is in the future. Discarding.",t),1):t.ownerId===this.getZombiedOwnerId()))},t.prototype.scheduleOwnerLeaseRefreshes=function(){var t=this;this.ownerLeaseRefreshHandle=setInterval(function(){t.runTransaction("Refresh owner timestamp",function(e){return e.store(pr.store).put("owner",new pr(t.ownerId,Date.now()))}).catch(function(e){a(e),t.stopOwnerLeaseRefreshes()})},4e3)},t.prototype.stopOwnerLeaseRefreshes=function(){this.ownerLeaseRefreshHandle&&(clearInterval(this.ownerLeaseRefreshHandle),this.ownerLeaseRefreshHandle=null)},t.prototype.attachWindowUnloadHook=function(){var t=this;this.windowUnloadHandler=function(){t.setZombiedOwnerId(t.ownerId),t.shutdown()},window.addEventListener("unload",this.windowUnloadHandler)},t.prototype.detachWindowUnloadHook=function(){this.windowUnloadHandler&&(window.removeEventListener("unload",this.windowUnloadHandler),this.windowUnloadHandler=null)},t.prototype.getZombiedOwnerId=function(){try{var t=window.localStorage.getItem(this.zombiedOwnerLocalStorageKey());return i("IndexedDbPersistence","Zombied ownerID from LocalStorage:",t),t}catch(t){return a("Failed to get zombie owner id.",t),null}},t.prototype.setZombiedOwnerId=function(t){try{null===t?window.localStorage.removeItem(this.zombiedOwnerLocalStorageKey()):window.localStorage.setItem(this.zombiedOwnerLocalStorageKey(),t)}catch(t){a("Failed to set zombie owner id.",t)}},t.prototype.zombiedOwnerLocalStorageKey=function(){return this.localStoragePrefix+"zombiedOwnerId"},t.prototype.generateOwnerId=function(){return Xt.newId()},t.MAIN_DATABASE="main",t}(),Pr=function(){function t(t,e){this.remoteDocumentCache=t,this.mutationQueue=e}return t.prototype.getDocument=function(t,e){var n=this;return this.remoteDocumentCache.getEntry(t,e).next(function(r){return n.computeLocalDocument(t,e,r)})},t.prototype.getDocuments=function(t,e){var n=this,r=[],o=$();return e.forEach(function(e){r.push(n.getDocument(t,e).next(function(t){t||(t=new ce(e,He.forDeletedDoc())),o=o.insert(e,t)}))}),Hn.waitFor(r).next(function(){return o})},t.prototype.getDocumentsMatchingQuery=function(t,e){return se.isDocumentKey(e.path)?this.getDocumentsMatchingDocumentQuery(t,e.path):this.getDocumentsMatchingCollectionQuery(t,e)},t.prototype.getDocumentsMatchingDocumentQuery=function(t,e){return this.getDocument(t,new se(e)).next(function(t){var e=Z();return t instanceof ue&&(e=e.insert(t.key,t)),e})},t.prototype.getDocumentsMatchingCollectionQuery=function(t,e){var n,r=this;return this.remoteDocumentCache.getDocumentsMatchingQuery(t,e).next(function(e){return r.computeLocalDocuments(t,e)}).next(function(o){return n=o,r.mutationQueue.getAllMutationBatchesAffectingQuery(t,e)}).next(function(e){for(var o=et(),i=0,a=e;i0?e.mutationQueue.removeMutationBatches(t,n):Hn.resolve()})},t.prototype.localWrite=function(t){var e=this;return this.persistence.runTransaction("Locally write mutations",function(n){var r,o=Ge.now();return e.mutationQueue.addMutationBatch(n,o,t).next(function(t){r=t;var o=r.keys();return e.localDocuments.getDocuments(n,o)}).next(function(t){return{batchId:r.batchId,changes:t}})})},t.prototype.acknowledgeBatch=function(t){var e=this;return this.persistence.runTransaction("Acknowledge batch",function(n){var r;return e.mutationQueue.acknowledgeBatch(n,t.batch,t.streamToken).next(function(){if(e.shouldHoldBatchResult(t.commitVersion))return e.heldBatchResults.push(t),r=et(),Hn.resolve();var o=new Lr(e.remoteDocuments);return e.releaseBatchResults(n,[t],o).next(function(t){return r=t,o.apply(n)})}).next(function(){return e.mutationQueue.performConsistencyCheck(n)}).next(function(){return e.localDocuments.getDocuments(n,r)})})},t.prototype.rejectBatch=function(t){var e=this;return this.persistence.runTransaction("Reject batch",function(n){var r,o;return e.mutationQueue.lookupMutationBatch(n,t).next(function(o){return c(null!=o,"Attempt to reject nonexistent batch!"),r=o,e.mutationQueue.getHighestAcknowledgedBatchId(n).next(function(e){return c(t>e,"Acknowledged batches can't be rejected."),r})}).next(function(){return e.removeMutationBatch(n,r)}).next(function(t){return o=t,e.mutationQueue.performConsistencyCheck(n)}).next(function(){return e.localDocuments.getDocuments(n,o)})})},t.prototype.getLastStreamToken=function(){var t=this;return this.persistence.runTransaction("Get last stream token",function(e){return t.mutationQueue.getLastStreamToken(e)})},t.prototype.setLastStreamToken=function(t){var e=this;return this.persistence.runTransaction("Set last stream token",function(n){return e.mutationQueue.setLastStreamToken(n,t)})},t.prototype.getLastRemoteSnapshotVersion=function(){return this.queryCache.getLastRemoteSnapshotVersion()},t.prototype.applyRemoteEvent=function(t){var e=this,n=new Lr(this.remoteDocuments);return this.persistence.runTransaction("Apply remote event",function(r){var o=[];p(t.targetChanges,function(t,n){var i=e.targetIds[t];if(i){var a=n.mapping;if(a)if(a instanceof bn)o.push(e.queryCache.removeMatchingKeysForTargetId(r,t).next(function(){return e.queryCache.addMatchingKeys(r,a.documents,t)}));else{if(!(a instanceof wn))return u("Unknown mapping type: "+JSON.stringify(a));o.push(e.queryCache.removeMatchingKeys(r,a.removedDocuments,t).next(function(){return e.queryCache.addMatchingKeys(r,a.addedDocuments,t)}))}var s=n.resumeToken;s.length>0&&(i=i.update({resumeToken:s,snapshotVersion:n.snapshotVersion}),e.targetIds[t]=i,o.push(e.queryCache.addQueryData(r,i)))}});var a=et();t.documentUpdates.forEach(function(t,s){a=a.add(t),o.push(n.getEntry(r,t).next(function(r){null==r||s.version.equals(He.MIN)||s.version.compareTo(r.version)>=0?n.addEntry(s):i("LocalStore","Ignoring outdated watch update for ",t,". Current version:",r.version," Watch version:",s.version),e.garbageCollector.addPotentialGarbageKey(t)}))});var s=e.queryCache.getLastRemoteSnapshotVersion(),h=t.snapshotVersion;h.equals(He.MIN)||(c(h.compareTo(s)>=0,"Watch stream reverted to previous snapshot?? "+h+" < "+s),o.push(e.queryCache.setLastRemoteSnapshotVersion(r,h)));var l;return Hn.waitFor(o).next(function(){return e.releaseHeldBatchResults(r,n)}).next(function(t){return l=t,n.apply(r)}).next(function(){return e.localDocuments.getDocuments(r,a.unionWith(l))})})},t.prototype.notifyLocalViewChanges=function(t){var e=this;return this.persistence.runTransaction("Notify local view changes",function(n){for(var r=[],o=0,i=t;o0},t.prototype.releaseBatchResults=function(t,e,n){for(var r=this,o=Hn.resolve(),i=0,a=e;ithis.highestAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order");var o=this.indexOfExistingBatchId(r,"acknowledged"),i=this.mutationQueue[o];return c(r===i.batchId,"Queue ordering failure: expected batch "+r+", got batch "+i.batchId),c(!i.isTombstone(),"Can't acknowledge a previously removed batch"),this.highestAcknowledgedBatchId=r,this.lastStreamToken=n,Hn.resolve()},t.prototype.getLastStreamToken=function(t){return Hn.resolve(this.lastStreamToken)},t.prototype.setLastStreamToken=function(t,e){return this.lastStreamToken=e,Hn.resolve()},t.prototype.addMutationBatch=function(t,e,n){c(0!==n.length,"Mutation batches should not be empty");var r=this.nextBatchId;this.nextBatchId++,this.mutationQueue.length>0&&c(this.mutationQueue[this.mutationQueue.length-1].batchId=n?r=n:r++,Hn.resolve(this.getAllLiveMutationBatchesBeforeIndex(r))},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=new Jn(e,0),o=new Jn(e,Number.POSITIVE_INFINITY),i=[];return this.batchesByDocumentKey.forEachInRange([r,o],function(t){c(e.equals(t.key),"Should only iterate over a single key's batches");var r=n.findMutationBatch(t.targetOrBatchId);c(null!==r,"Batches in the index must exist in the main table"),i.push(r)}),Hn.resolve(i)},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=this,r=e.path,o=r.length+1,i=r;se.isDocumentKey(i)||(i=i.child(""));var a=new Jn(new se(i),0),s=new ln(L);this.batchesByDocumentKey.forEachWhile(function(t){var e=t.key.path;return!!r.isPrefixOf(e)&&(e.length===o&&(s=s.add(t.targetOrBatchId)),!0)},a);var u=[];return s.forEach(function(t){var e=n.findMutationBatch(t);null!==e&&u.push(e)}),Hn.resolve(u)},t.prototype.removeMutationBatches=function(t,e){var n=e.length;c(n>0,"Should not remove mutations when none exist.");var r=e[0].batchId,o=this.mutationQueue.length,i=this.indexOfExistingBatchId(r,"removed");c(this.mutationQueue[i].batchId===r,"Removed batches must exist in the queue");for(var a=1,s=i+1;a=0&&n=this.mutationQueue.length)return null;var n=this.mutationQueue[e];return c(n.batchId===t,"If found batch must match"),n.isTombstone()?null:n},t}(),Ur=function(){function t(){this.queries=new Qn(function(t){return t.canonicalId()}),this.lastRemoteSnapshotVersion=He.MIN,this.highestTargetId=0,this.references=new Yn}return t.prototype.start=function(t){return Hn.resolve()},t.prototype.getLastRemoteSnapshotVersion=function(){return this.lastRemoteSnapshotVersion},t.prototype.getHighestTargetId=function(){return this.highestTargetId},t.prototype.setLastRemoteSnapshotVersion=function(t,e){return this.lastRemoteSnapshotVersion=e,Hn.resolve()},t.prototype.addQueryData=function(t,e){this.queries.set(e.query,e);var n=e.targetId;return n>this.highestTargetId&&(this.highestTargetId=n),Hn.resolve()},t.prototype.removeQueryData=function(t,e){return this.queries.delete(e.query),this.references.removeReferencesForId(e.targetId),Hn.resolve()},t.prototype.getQueryData=function(t,e){var n=this.queries.get(e)||null;return Hn.resolve(n)},t.prototype.addMatchingKeys=function(t,e,n){return this.references.addReferences(e,n),Hn.resolve()},t.prototype.removeMatchingKeys=function(t,e,n){return this.references.removeReferences(e,n),Hn.resolve()},t.prototype.removeMatchingKeysForTargetId=function(t,e){return this.references.removeReferencesForId(e),Hn.resolve()},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=this.references.referencesForId(e);return Hn.resolve(n)},t.prototype.setGarbageCollector=function(t){this.references.setGarbageCollector(t)},t.prototype.containsKey=function(t,e){return this.references.containsKey(t,e)},t}(),Fr=function(){function t(){this.docs=$()}return t.prototype.addEntry=function(t,e){return this.docs=this.docs.insert(e.key,e),Hn.resolve()},t.prototype.removeEntry=function(t,e){return this.docs=this.docs.remove(e),Hn.resolve()},t.prototype.getEntry=function(t,e){return Hn.resolve(this.docs.get(e))},t.prototype.getDocumentsMatchingQuery=function(t,e){for(var n=Z(),r=new se(e.path.child("")),o=this.docs.getIteratorFrom(r);o.hasNext();){var i=o.getNext(),a=i.key,s=i.value;if(!e.path.isPrefixOf(a.path))break;s instanceof ue&&e.matches(s)&&(n=n.insert(s.key,s))}return Hn.resolve(n)},t}(),Vr=function(){function t(){this.mutationQueues={},this.remoteDocumentCache=new Fr,this.queryCache=new Ur,this.started=!1}return t.prototype.start=function(){return c(!this.started,"MemoryPersistence double-started!"),this.started=!0,Promise.resolve()},t.prototype.shutdown=function(){return c(this.started,"MemoryPersistence shutdown without start!"),this.started=!1,Promise.resolve()},t.prototype.getMutationQueue=function(t){var e=this.mutationQueues[t.toKey()];return e||(e=new Br,this.mutationQueues[t.toKey()]=e),e},t.prototype.getQueryCache=function(){return this.queryCache},t.prototype.getRemoteDocumentCache=function(){return this.remoteDocumentCache},t.prototype.runTransaction=function(t,e){return i("MemoryPersistence","Starting transaction:",t),e(new qr).toPromise()},t}(),qr=function(){function t(){}return t}(),jr=function(){function t(){this.isEager=!1}return t.prototype.addGarbageSource=function(t){},t.prototype.removeGarbageSource=function(t){},t.prototype.addPotentialGarbageKey=function(t){},t.prototype.collectGarbage=function(t){return Hn.resolve(et())},t}(),Qr=function(){function t(){var t=this;this.promise=new Promise(function(e,n){t.resolve=e,t.reject=n})}return t}(),Kr=function(){function t(t,e,n){this.initialDelayMs=t,this.backoffFactor=e,this.maxDelayMs=n,this.reset()}return t.prototype.reset=function(){this.currentBaseMs=0},t.prototype.resetToMax=function(){this.currentBaseMs=this.maxDelayMs},t.prototype.backoffAndWait=function(){var t=new Qr,e=this.currentBaseMs+this.jitterDelayMs();return this.currentBaseMs>0&&i("ExponentialBackoff","Backing off for "+e+" ms (base delay: "+this.currentBaseMs+" ms)"),setTimeout(function(){t.resolve()},e),this.currentBaseMs*=this.backoffFactor,this.currentBaseMsthis.maxDelayMs&&(this.currentBaseMs=this.maxDelayMs),t.promise},t.prototype.jitterDelayMs=function(){return(Math.random()-.5)*this.currentBaseMs},t}(),Wr=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.Initial=0]="Initial",t[t.Auth=1]="Auth",t[t.Open=2]="Open",t[t.Error=3]="Error",t[t.Backoff=4]="Backoff",t[t.Stopped=5]="Stopped"}(Zn||(Zn={}));var Gr,Hr=1e3,zr=6e4,Xr=1.5,Yr=function(){function t(t,e,n,r){this.queue=t,this.connection=e,this.credentialsProvider=n,this.idle=!1,this.stream=null,this.listener=null,this.backoff=new Kr(r||Hr,Xr,zr),this.state=Zn.Initial}return t.prototype.isStarted=function(){return this.state===Zn.Backoff||this.state===Zn.Auth||this.state===Zn.Open},t.prototype.isOpen=function(){return this.state===Zn.Open},t.prototype.start=function(t){if(this.state===Zn.Error)return void this.performBackoff(t);c(this.state===Zn.Initial,"Already started"),this.listener=t,this.auth()},t.prototype.stop=function(){this.isStarted()&&this.close(Zn.Stopped)},t.prototype.inhibitBackoff=function(){c(!this.isStarted(),"Can only inhibit backoff in a stopped state"),this.state=Zn.Initial,this.backoff.reset()},t.prototype.markIdle=function(){var t=this;this.idle=!0,this.queue.schedule(function(){return t.handleIdleCloseTimer()},6e4).catch(function(t){c(t.code===Ht.CANCELLED,"Received unexpected error in idle timeout closure. Expected CANCELLED, but was: "+t)})},t.prototype.sendRequest=function(t){this.cancelIdleCheck(),this.stream.send(t)},t.prototype.handleIdleCloseTimer=function(){return this.isOpen()&&this.idle?this.close(Zn.Initial):Promise.resolve()},t.prototype.cancelIdleCheck=function(){this.idle=!1},t.prototype.close=function(t,e){c(t==Zn.Error||K(e),"Can't provide an error when not in an error state."),this.cancelIdleCheck(),t!=Zn.Error?this.backoff.reset():e&&e.code===Ht.RESOURCE_EXHAUSTED&&(a(""+e),a("Using maximum backoff delay to prevent overloading the backend."),this.backoff.resetToMax()),null!==this.stream&&(this.tearDown(),this.stream.close(),this.stream=null),this.state=t;var n=this.listener;return this.listener=null,t!=Zn.Stopped?n.onClose(e):Promise.resolve()},t.prototype.tearDown=function(){},t.prototype.auth=function(){var t=this;c(this.state===Zn.Initial,"Must be in initial state to auth"),this.state=Zn.Auth,this.credentialsProvider.getToken(!1).then(function(e){t.startStream(e)},function(e){t.queue.schedule(function(){if(t.state!==Zn.Stopped){var n=new zt(Ht.UNKNOWN,"Fetching auth token failed: "+e.message);return t.handleStreamClose(n)}return Promise.resolve()})})},t.prototype.startStream=function(t){var e=this;if(this.state!==Zn.Stopped){c(this.state===Zn.Auth,"Trying to start stream in a non-auth state");var n=function(t,n){e.queue.schedule(function(){return e.stream===t?n():Promise.resolve()})};if(null!==this.listener){var r=this.startRpc(t);this.stream=r,this.stream.onOpen(function(){n(r,function(){return c(e.state===Zn.Auth,"Expected stream to be in state auth, but was "+e.state),e.state=Zn.Open,e.listener.onOpen()})}),this.stream.onClose(function(t){n(r,function(){return e.handleStreamClose(t)})}),this.stream.onMessage(function(t){n(r,function(){return e.onMessage(t)})})}}},t.prototype.performBackoff=function(t){var e=this;c(this.state===Zn.Error,"Should only perform backoff in an error case"),this.state=Zn.Backoff,this.backoff.backoffAndWait().then(function(){e.queue.schedule(function(){return e.state===Zn.Stopped?Promise.resolve():(e.state=Zn.Initial,e.start(t),c(e.isStarted(),"PersistentStream should have started"),Promise.resolve())})})},t.prototype.handleStreamClose=function(t){return c(this.isStarted(),"Can't handle server close on non-started stream"),i("PersistentStream","close with error: "+t),this.stream=null,this.close(Zn.Error,t)},t}(),Jr=function(t){function e(e,n,r,o,i,a){var s=t.call(this,n,r,o,a)||this;return s.databaseInfo=e,s.serializer=i,s}return Wr(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}(Yr),$r=function(t){function e(e,n,r,o,i,a){var s=t.call(this,n,r,o,a)||this;return s.databaseInfo=e,s.serializer=i,s.y=!1,s}return Wr(e,t),Object.defineProperty(e.prototype,"handshakeComplete",{get:function(){return this.y},enumerable:!0,configurable:!0}),e.prototype.start=function(e){this.y=!1,t.prototype.start.call(this,e)},e.prototype.tearDown=function(){this.y&&this.writeMutations([])},e.prototype.startRpc=function(t){return this.connection.openStream("Write",t)},e.prototype.onMessage=function(t){if(c(!!t.streamToken,"Got a write response without a stream token"),this.lastStreamToken=t.streamToken,this.y){this.backoff.reset();var e=this.serializer.fromWriteResults(t.writeResults),n=this.serializer.fromVersion(t.commitTime);return this.listener.onMutationResult(n,e)}return c(!t.writeResults||0===t.writeResults.length,"Got mutation results for handshake"),this.y=!0,this.listener.onHandshakeComplete()},e.prototype.writeHandshake=function(){c(this.isOpen(),"Writing handshake requires an opened stream"),c(!this.y,"Handshake already completed");var t={};t.database=this.serializer.encodedDatabaseId,this.sendRequest(t)},e.prototype.writeMutations=function(t){var e=this;c(this.isOpen(),"Writing mutations requires an opened stream"),c(this.y,"Handshake must be complete before writing mutations"),c(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}(Yr),Zr=function(){function t(t,e,n,r,o,i){this.databaseInfo=t,this.queue=e,this.connection=n,this.credentials=r,this.serializer=o,this.initialBackoffDelay=i}return t.prototype.newPersistentWriteStream=function(){return new $r(this.databaseInfo,this.queue,this.connection,this.credentials,this.serializer,this.initialBackoffDelay)},t.prototype.newPersistentWatchStream=function(){return new Jr(this.databaseInfo,this.queue,this.connection,this.credentials,this.serializer,this.initialBackoffDelay)},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.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=$();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);c(!!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(!1).then(function(r){return n.connection.invokeRPC(t,e,r)})},t.prototype.invokeStreamingRPC=function(t,e){var n=this;return this.credentials.getToken(!1).then(function(r){return n.connection.invokeStreamingRPC(t,e,r)})},t}(),to=function(){function t(t){this.datastore=t,this.readVersions=tt(),this.mutations=[],this.committed=!1}return t.prototype.recordVersion=function(t){var e=t.version;t instanceof ce&&(e=He.forDeletedDoc());var n=this.readVersions.get(t.key);if(null!==n){if(!e.equals(n))throw new zt(Ht.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){return e.recordVersion(t)}),t})},t.prototype.write=function(t){if(this.committed)throw new zt(Ht.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?nn.updateTime(e):nn.NONE},t.prototype.preconditionForUpdate=function(t){var e=this.readVersions.get(t);if(e&&e.equals(He.forDeletedDoc()))throw new zt(Ht.FAILED_PRECONDITION,"Can't update a document that doesn't exist.");return e?nn.updateTime(e):nn.exists(!0)},t.prototype.set=function(t,e){this.write(e.toMutations(t,this.precondition(t)))},t.prototype.update=function(t,e){this.write(e.toMutations(t,this.preconditionForUpdate(t)))},t.prototype.delete=function(t){this.write([new un(t,this.precondition(t))]),this.readVersions=this.readVersions.insert(t,He.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}(),eo=function(){function t(t,e,n){this.localStore=t,this.datastore=e,this.onlineStateHandler=n,this.pendingWrites=[],this.lastBatchSeen=ar,this.listenTargets={},this.pendingTargetResponses={},this.accumulatedWatchChanges=[],this.watchStream=null,this.writeStream=null,this.watchStreamOnlineState=Ln.Unknown,this.watchStreamFailures=0,this.shouldWarnOffline=!0}return t.prototype.start=function(){return this.enableNetwork()},t.prototype.setOnlineStateToHealthy=function(){this.shouldWarnOffline=!1,this.updateAndBroadcastOnlineState(Ln.Healthy)},t.prototype.setOnlineStateToUnknown=function(){this.watchStreamFailures=0,this.updateAndBroadcastOnlineState(Ln.Unknown)},t.prototype.updateOnlineStateAfterFailure=function(){this.watchStreamOnlineState===Ln.Healthy?this.setOnlineStateToUnknown():++this.watchStreamFailures>=2&&(this.shouldWarnOffline&&(a("Could not reach Firestore backend."),this.shouldWarnOffline=!1),this.updateAndBroadcastOnlineState(Ln.Failed))},t.prototype.updateAndBroadcastOnlineState=function(t){var e=this.watchStreamOnlineState!==t;this.watchStreamOnlineState=t,e&&this.onlineStateHandler(t)},t.prototype.isNetworkEnabled=function(){return c(null==this.watchStream==(null==this.writeStream),"WatchStream and WriteStream should both be null or non-null"),null!=this.watchStream},t.prototype.enableNetwork=function(){var t=this;return c(null==this.watchStream,"enableNetwork() called with non-null watchStream."),c(null==this.writeStream,"enableNetwork() called with non-null writeStream."),this.watchStream=this.datastore.newPersistentWatchStream(),this.writeStream=this.datastore.newPersistentWriteStream(),this.localStore.getLastStreamToken().then(function(e){return t.writeStream.lastStreamToken=e,t.shouldStartWatchStream()&&t.startWatchStream(),t.updateAndBroadcastOnlineState(Ln.Unknown),t.fillWritePipeline()})},t.prototype.disableNetwork=function(){return this.updateAndBroadcastOnlineState(Ln.Failed),this.watchStream.stop(),this.writeStream.stop(),this.cleanUpWatchStreamState(),this.cleanUpWriteStreamState(),this.writeStream=null,this.watchStream=null,Promise.resolve()},t.prototype.shutdown=function(){return i("RemoteStore","RemoteStore shutting down."),this.disableNetwork(),Promise.resolve(void 0)},t.prototype.listen=function(t){c(!f(this.listenTargets,t.targetId),"listen called with duplicate targetId!"),this.listenTargets[t.targetId]=t,this.shouldStartWatchStream()?this.startWatchStream():this.isNetworkEnabled()&&this.watchStream.isOpen()&&this.sendWatchRequest(t)},t.prototype.unlisten=function(t){c(f(this.listenTargets,t),"unlisten called without assigned target ID!"),this.listenTargets[t],delete this.listenTargets[t],this.isNetworkEnabled()&&this.watchStream.isOpen()&&(this.sendUnwatchRequest(t),m(this.listenTargets)&&this.watchStream.markIdle())},t.prototype.sendWatchRequest=function(t){this.recordPendingTargetRequest(t.targetId),this.watchStream.watch(t)},t.prototype.sendUnwatchRequest=function(t){this.recordPendingTargetRequest(t),this.watchStream.unwatch(t)},t.prototype.recordPendingTargetRequest=function(t){this.pendingTargetResponses[t]=(this.pendingTargetResponses[t]||0)+1},t.prototype.startWatchStream=function(){c(this.shouldStartWatchStream(),"startWriteStream() called when shouldStartWatchStream() is false."),this.watchStream.start({onOpen:this.onWatchStreamOpen.bind(this),onClose:this.onWatchStreamClose.bind(this),onWatchChange:this.onWatchStreamChange.bind(this)})},t.prototype.shouldStartWatchStream=function(){return this.isNetworkEnabled()&&!this.watchStream.isStarted()&&!m(this.listenTargets)},t.prototype.cleanUpWatchStreamState=function(){this.accumulatedWatchChanges=[],this.pendingTargetResponses={}},t.prototype.onWatchStreamOpen=function(){var t=this;return p(this.listenTargets,function(e,n){t.sendWatchRequest(n)}),Promise.resolve()},t.prototype.onWatchStreamClose=function(t){return c(this.isNetworkEnabled(),"onWatchStreamClose() should only be called when the network is enabled"),this.cleanUpWatchStreamState(),this.shouldStartWatchStream()?(this.updateOnlineStateAfterFailure(),this.startWatchStream()):this.setOnlineStateToUnknown(),Promise.resolve()},t.prototype.onWatchStreamChange=function(t,e){if(this.setOnlineStateToHealthy(),t instanceof En&&t.state===gn.Removed&&t.cause)return this.handleTargetError(t);if(this.accumulatedWatchChanges.push(t),!e.equals(He.MIN)&&e.compareTo(this.localStore.getLastRemoteSnapshotVersion())>=0){var n=this.accumulatedWatchChanges;return this.accumulatedWatchChanges=[],this.handleWatchChangeBatch(e,n)}return Promise.resolve()},t.prototype.handleWatchChangeBatch=function(t,e){var n=this,r=new Sn(t,this.listenTargets,this.pendingTargetResponses);r.addChanges(e);var o=r.createRemoteEvent();this.pendingTargetResponses=r.pendingTargetResponses;var i=[];return p(r.existenceFilters,function(e,r){var a=n.listenTargets[e];if(a){var s=a.query;if(s.isDocumentQuery())if(0===r.count){var u=new se(s.path),h=new ce(u,t);o.addDocumentUpdate(h)}else c(1===r.count,"Single document existence filter with count: "+r.count);else{var l=n.localStore.remoteDocumentKeys(e).then(function(t){if(o.targetChanges[e]){var i=o.targetChanges[e].mapping;null!==i&&(i instanceof wn?t=i.applyToKeySet(t):(c(i instanceof bn,"Expected either reset or update mapping but got something else: "+i),t=i.documents))}if(t.size!==r.count){o.handleExistenceFilterMismatch(e);var u=new Xe(s,e,a.purpose);n.listenTargets[e]=u,n.sendUnwatchRequest(e);var h=new Xe(s,e,me.ExistenceFilterMismatch);n.sendWatchRequest(h)}});i.push(l)}}}),Promise.all(i).then(function(){return p(o.targetChanges,function(t,e){if(e.resumeToken.length>0){var r=n.listenTargets[t];r&&(n.listenTargets[t]=r.update({resumeToken:e.resumeToken,snapshotVersion:e.snapshotVersion}))}}),n.syncEngine.applyRemoteEvent(o)})},t.prototype.handleTargetError=function(t){var e=this;c(!!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 f(e.listenTargets,t)?(delete e.listenTargets[t],e.syncEngine.rejectListen(t,n)):Promise.resolve()})}),r},t.prototype.cleanUpWriteStreamState=function(){this.lastBatchSeen=ar,this.pendingWrites=[]},t.prototype.fillWritePipeline=function(){var t=this;return this.canWriteMutations()?this.localStore.nextMutationBatch(this.lastBatchSeen).then(function(e){return null===e?(0==t.pendingWrites.length&&t.writeStream.markIdle(),Promise.resolve()):(t.commit(e),t.fillWritePipeline())}):Promise.resolve()},t.prototype.canWriteMutations=function(){return this.isNetworkEnabled()&&this.pendingWrites.length<10},t.prototype.outstandingWrites=function(){return this.pendingWrites.length},t.prototype.commit=function(t){c(this.canWriteMutations(),"commit called when batches can't be written"),this.lastBatchSeen=t.batchId,this.pendingWrites.push(t),this.shouldStartWriteStream()?this.startWriteStream():this.isNetworkEnabled()&&this.writeStream.handshakeComplete&&this.writeStream.writeMutations(t.mutations)},t.prototype.shouldStartWriteStream=function(){return this.isNetworkEnabled()&&!this.writeStream.isStarted()&&this.pendingWrites.length>0},t.prototype.startWriteStream=function(){c(this.shouldStartWriteStream(),"startWriteStream() called when shouldStartWriteStream() is false."),this.writeStream.start({onOpen:this.onWriteStreamOpen.bind(this),onClose:this.onWriteStreamClose.bind(this),onHandshakeComplete:this.onWriteHandshakeComplete.bind(this),onMutationResult:this.onMutationResult.bind(this)})},t.prototype.onWriteStreamOpen=function(){return this.writeStream.writeHandshake(),Promise.resolve()},t.prototype.onWriteHandshakeComplete=function(){var t=this;return this.localStore.setLastStreamToken(this.writeStream.lastStreamToken).then(function(){for(var e=0,n=t.pendingWrites;e0,"Got result for empty pending writes");var r=this.pendingWrites.shift(),o=ur.from(r,t,e,this.writeStream.lastStreamToken);return this.syncEngine.applySuccessfulWrite(o).then(function(){return n.fillWritePipeline()})},t.prototype.onWriteStreamClose=function(t){var e=this;if(c(this.isNetworkEnabled(),"onWriteStreamClose() should only be called when the network is enabled"),t&&this.pendingWrites.length>0){c(!!t,"We have pending writes, but the write stream closed without an error");var n=void 0;return n=this.writeStream.handshakeComplete?this.handleWriteError(t):this.handleHandshakeError(t),n.then(function(){e.shouldStartWriteStream()&&e.startWriteStream()})}return Promise.resolve()},t.prototype.handleHandshakeError=function(t){return H(t.code)||t.code===Ht.ABORTED?(i("RemoteStore","RemoteStore error before completed handshake; resetting stream token: ",this.writeStream.lastStreamToken),this.writeStream.lastStreamToken=h(),this.localStore.setLastStreamToken(h())):Promise.resolve()},t.prototype.handleWriteError=function(t){var e=this;if(H(t.code)){var n=this.pendingWrites.shift();return this.writeStream.inhibitBackoff(),this.syncEngine.rejectFailedWrite(n.batchId,t).then(function(){return e.fillWritePipeline()})}return Promise.resolve()},t.prototype.createTransaction=function(){return new to(this.datastore)},t.prototype.handleUserChange=function(t){return i("RemoteStore","RemoteStore changing users: uid=",t.uid),this.disableNetwork(),this.enableNetwork()},t}(),no=function(){function t(t,e,n,r){this.platform=t,this.databaseInfo=e,this.credentials=n,this.asyncQueue=r}return t.prototype.start=function(t){var e=this,n=new Qr,r=new Qr,o=!1;return this.credentials.setUserChangeListener(function(i){o?e.asyncQueue.schedule(function(){return e.handleUserChange(i)}):(o=!0,e.initializePersistence(t,r).then(function(){return e.initializeRest(i)}).then(n.resolve,n.reject))}),this.asyncQueue.schedule(function(){return n.promise}),r.promise},t.prototype.enableNetwork=function(){var t=this;return this.asyncQueue.schedule(function(){return t.remoteStore.enableNetwork()})},t.prototype.initializePersistence=function(t,e){var n=this;return t?this.startIndexedDbPersistence().then(e.resolve).catch(function(t){return e.reject(t),n.canFallback(t)?(console.warn("Error enabling offline storage. Falling back to storage disabled: "+t),n.startMemoryPersistence()):Promise.reject(t)}):(e.resolve(),this.startMemoryPersistence())},t.prototype.canFallback=function(t){return t.code===Ht.FAILED_PRECONDITION||t.code===Ht.UNIMPLEMENTED},t.prototype.startIndexedDbPersistence=function(){this.garbageCollector=new jr;var t=_r.buildStoragePrefix(this.databaseInfo),e=new kn(this.databaseInfo.databaseId,{useProto3Json:!0});return this.persistence=new _r(t,e),this.persistence.start()},t.prototype.startMemoryPersistence=function(){return this.garbageCollector=new zn,this.persistence=new Vr,this.persistence.start()},t.prototype.initializeRest=function(t){var e=this;return this.platform.loadConnection(this.databaseInfo).then(function(n){e.localStore=new xr(e.persistence,t,e.garbageCollector);var r=e.platform.newSerializer(e.databaseInfo.databaseId),o=new Zr(e.databaseInfo,e.asyncQueue,n,e.credentials,r),i=function(t){e.eventMgr.onOnlineStateChanged(t)};return e.remoteStore=new eo(e.localStore,o,i),e.syncEngine=new ir(e.localStore,e.remoteStore,t),e.remoteStore.syncEngine=e.syncEngine,e.eventMgr=new Wn(e.syncEngine),e.localStore.start()}).then(function(){return e.remoteStore.start()})},t.prototype.handleUserChange=function(t){return this.asyncQueue.verifyOperationInProgress(),i("FirestoreClient","User Changed: "+t.uid),this.syncEngine.handleUserChange(t)},t.prototype.disableNetwork=function(){var t=this;return this.asyncQueue.schedule(function(){return t.remoteStore.disableNetwork()})},t.prototype.shutdown=function(){var t=this;return this.asyncQueue.schedule(function(){return t.credentials.removeUserChangeListener(),t.remoteStore.shutdown()}).then(function(){return t.persistence.shutdown()})},t.prototype.listen=function(t,e,n){var r=this,o=new Gn(t,e,n);return this.asyncQueue.schedule(function(){return r.eventMgr.listen(o)}),o},t.prototype.unlisten=function(t){var e=this;this.asyncQueue.schedule(function(){return e.eventMgr.unlisten(t)})},t.prototype.write=function(t){var e=this,n=new Qr;return this.asyncQueue.schedule(function(){return e.syncEngine.write(t,n)}),n.promise},t.prototype.databaseId=function(){return this.databaseInfo.databaseId},t.prototype.transaction=function(t){var e=this;return this.asyncQueue.schedule(function(){return Promise.resolve()}).then(function(){return e.syncEngine.runTransaction(t)})},t}(),ro=function(){function t(t){this.observer=t,this.muted=!1}return t.prototype.next=function(t){this.scheduleEvent(this.observer.next,t)},t.prototype.error=function(t){this.scheduleEvent(this.observer.error,t)},t.prototype.mute=function(){this.muted=!0},t.prototype.scheduleEvent=function(t,e){var n=this;this.muted||setTimeout(function(){n.muted||t(e)},0)},t}(),oo=function(){function t(){this.tail=Promise.resolve(),this.delayedOperations=[],this.delayedOperationsCount=0,this.operationInProgress=!1}return t.prototype.schedule=function(t,e){var n=this;if(this.failure&&u("AsyncQueue is already failed: "+(this.failure.stack||this.failure.message)),(e||0)>0){this.delayedOperationsCount++;var r={handle:null,op:t,deferred:new Qr};return r.handle=setTimeout(function(){n.scheduleInternal(function(){return r.op().then(function(t){r.deferred.resolve(t)})}),r.handle=null,0==--n.delayedOperationsCount&&(n.delayedOperations=[])},e),this.delayedOperations.push(r),r.deferred.promise}return this.scheduleInternal(t)},t.prototype.scheduleInternal=function(t){var e=this;return this.tail=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 a("INTERNAL UNHANDLED ERROR: ",n),n.indexOf("Firestore Test Simulated Error")<0&&setTimeout(function(){throw t},0),t}).then(function(){e.operationInProgress=!1})}),this.tail},t.prototype.verifyOperationInProgress=function(){c(this.operationInProgress,"verifyOpInProgress() called when no op in progress on this queue.")},t.prototype.drain=function(t){var e=this;return this.delayedOperations.forEach(function(n){n.handle&&(clearTimeout(n.handle),t?e.scheduleInternal(n.op).then(n.deferred.resolve,n.deferred.reject):n.deferred.reject(new zt(Ht.CANCELLED,"Operation cancelled by shutdown")))}),this.delayedOperations=[],this.delayedOperationsCount=0,this.schedule(function(){return Promise.resolve()})},t}(),io=function(){function t(t){this.uid=t}return t.prototype.isUnauthenticated=function(){return null==this.uid},t.prototype.toKey=function(){return this.isUnauthenticated()?"anonymous-user":"uid:"+this.uid},t.prototype.equals=function(t){return t.uid===this.uid},t.UNAUTHENTICATED=new t(null),t.GOOGLE_CREDENTIALS=new t("google-credentials-uid"),t.FIRST_PARTY=new t("first-party-uid"),t}(),ao=function(){function t(t,e){this.user=e,this.type="OAuth",this.authHeaders={Authorization:"Bearer "+t}}return t}(),so=function(){function t(){this.userListener=null}return t.prototype.getToken=function(t){return Promise.resolve(null)},t.prototype.setUserChangeListener=function(t){c(!this.userListener,"Can only call setUserChangeListener() once."),this.userListener=t,t(io.UNAUTHENTICATED)},t.prototype.removeUserChangeListener=function(){c(null!==this.userListener,"removeUserChangeListener() when no listener registered"),this.userListener=null},t}(),uo=function(){function t(t){var e=this;this.app=t,this.tokenListener=null,this.userCounter=0,this.userListener=null,this.tokenListener=function(){var t=e.getUser();e.currentUser&&t.equals(e.currentUser)||(e.currentUser=t,e.userCounter++,e.userListener&&e.userListener(e.currentUser))},this.userCounter=0,this.app.INTERNAL.addAuthTokenListener(this.tokenListener)}return t.prototype.getToken=function(t){var e=this;c(null!=this.tokenListener,"getToken cannot be called after listener removed.");var n=this.userCounter;return this.app.INTERNAL.getToken(t).then(function(t){if(e.userCounter!==n)throw new zt(Ht.ABORTED,"getToken aborted due to uid change.");return t?(c("string"==typeof t.accessToken,"Invalid tokenData returned from getToken():"+t),new ao(t.accessToken,e.currentUser)):null})},t.prototype.setUserChangeListener=function(t){c(!this.userListener,"Can only call setUserChangeListener() once."),this.userListener=t,this.currentUser&&t(this.currentUser)},t.prototype.removeUserChangeListener=function(){c(null!=this.tokenListener,"removeUserChangeListener() called twice"),c(null!==this.userListener,"removeUserChangeListener() called when no listener registered"),this.app.INTERNAL.removeAuthTokenListener(this.tokenListener),this.tokenListener=null,this.userListener=null},t.prototype.getUser=function(){"function"!=typeof this.app.INTERNAL.getUid&&u("This version of the Firestore SDK requires at least version 3.7.0 of firebase.js.");var t=this.app.INTERNAL.getUid();return c(null===t||"string"==typeof t,"Received invalid UID: "+t),new io(t)},t}(),co=function(){function t(t,e){this.gapi=t,this.sessionIndex=e,this.type="FirstParty",this.user=io.FIRST_PARTY,c(this.gapi&&this.gapi.auth&&this.gapi.auth.getAuthHeaderValueForFirstParty,"unexpected gapi interface")}return Object.defineProperty(t.prototype,"authHeaders",{get:function(){return{Authorization:this.gapi.auth.getAuthHeaderValueForFirstParty([]),"X-Goog-AuthUser":this.sessionIndex}},enumerable:!0,configurable:!0}),t}(),ho=function(){function t(t,e){this.gapi=t,this.sessionIndex=e,c(this.gapi&&this.gapi.auth&&this.gapi.auth.getAuthHeaderValueForFirstParty,"unexpected gapi interface")}return t.prototype.getToken=function(t){return Promise.resolve(new co(this.gapi,this.sessionIndex))},t.prototype.setUserChangeListener=function(t){t(io.FIRST_PARTY)},t.prototype.removeUserChangeListener=function(){},t}(),lo=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),fo=function(){function t(){}return t.delete=function(){return po.instance},t.serverTimestamp=function(){return yo.instance},t}(),po=function(t){function e(){return t.call(this)||this}return lo(e,t),e.instance=new e,e}(fo),yo=function(t){function e(){return t.call(this)||this}return lo(e,t),e.instance=new e,e}(fo),mo=l(fo,"Use FieldValue.() instead."),go=/^__.*__$/,vo=function(){function t(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}return t.prototype.toMutations=function(t,e){var n=[];return null!==this.fieldMask?n.push(new an(t,this.data,this.fieldMask,e)):n.push(new on(t,this.data,e)),this.fieldTransforms.length>0&&n.push(new sn(t,this.fieldTransforms)),n},t}(),bo=function(){function t(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}return t.prototype.toMutations=function(t,e){var n=[new an(t,this.data,this.fieldMask,e)];return this.fieldTransforms.length>0&&n.push(new sn(t,this.fieldTransforms)),n},t}();!function(t){t[t.Set=0]="Set",t[t.Update=1]="Update",t[t.MergeSet=2]="MergeSet",t[t.QueryValue=3]="QueryValue"}(Gr||(Gr={}));var wo=function(){function t(t,e,n,r,o,i){this.dataSource=t,this.methodName=e,this.path=n,this.arrayElement=r,void 0===o&&this.validatePath(),this.arrayElement=void 0!==r&&r,this.fieldTransforms=o||[],this.fieldMask=i||[]}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+")";return new zt(Ht.INVALID_ARGUMENT,"Function "+this.methodName+"() called with invalid data. "+t+e)},t.prototype.validatePath=function(){if(null!==this.path)for(var t=0;t0,"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() can only be used with update() and set() with {merge:true}")}if(t instanceof yo){if(!At(e.dataSource))throw e.createError("FieldValue.serverTimestamp() can only be used with set() and update()");if(null===e.path)throw e.createError("FieldValue.serverTimestamp() is not currently supported inside arrays");return e.fieldTransforms.push(new Ze(e.path,$e.instance)),null}return u("Unknown FieldValue type: "+t)}throw e.createError("Unsupported field value: "+N(t))},t}(),Eo=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),So="firestore.googleapis.com",Co=!0,Do=function(){function t(t){if(void 0===t.host){if(void 0!==t.ssl)throw new zt(Ht.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=So,this.ssl=Co}else S("settings","string","host",t.host),this.host=t.host,C("settings","boolean","ssl",t.ssl),this.ssl=d(t.ssl,Co);O("settings",t,["host","ssl","credentials"]),C("settings","object","credentials",t.credentials),this.credentials=t.credentials}return t.prototype.equals=function(t){return this.host===t.host&&this.ssl===t.ssl&&this.credentials===t.credentials},t}(),ko=function(){function t(){}return t}(),No=function(){function t(e){var n=this;this.k=new oo,this.INTERNAL={delete:function(){return n._?n._.shutdown():Promise.resolve()},disableNetwork:function(){return n._.disableNetwork()},enableNetwork:function(){return n._.enableNetwork()},drainAsyncQueue:function(t){return n.k.drain(t)}};var r=new ko;if("object"==typeof e.options){var o=e;r.firebaseApp=o,r.databaseId=t.databaseIdFromApp(o),r.persistenceKey=r.firebaseApp.name,r.credentials=new uo(o)}else{var i=e;if(!i.projectId)throw new zt(Ht.INVALID_ARGUMENT,"Must provide projectId");r.databaseId=new ee(i.projectId,i.database),r.persistenceKey="[DEFAULT]",r.credentials=new so}r.settings=new Do({}),this.x=r,this._databaseId=r.databaseId}return t.prototype.settings=function(t){if(v("Firestore.settings",arguments,1),T("Firestore.settings","object",1,t),f(t,"persistence"))throw new zt(Ht.INVALID_ARGUMENT,'"persistence" is now specified with a separate call to firestore.enablePersistence().');var e=new Do(t);if(this._&&!this.x.settings.equals(e))throw new zt(Ht.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only call settings() before calling any other methods on a Firestore object.");this.x.settings=e,void 0!==e.credentials&&(this.x.credentials=Dt(e.credentials))},t.prototype.enablePersistence=function(){if(this._)throw new zt(Ht.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only call enablePersistence() before calling any other methods on a Firestore object.");return this.configureClient(!0)},t.prototype.ensureClientConfigured=function(){return this._||this.configureClient(!1),this._},t.prototype.configureClient=function(t){var e=this;c(!!this.x.settings.host,"FirestoreSettings.host cannot be falsey"),c(!this._,"configureClient() called multiple times");var n=new Zt(this.x.databaseId,this.x.persistenceKey,this.x.settings.host,this.x.settings.ssl),r=function(t){if(t instanceof Oo){var n=e.x.databaseId,r=t.firestore.x.databaseId;if(!r.equals(n))throw new zt(Ht.INVALID_ARGUMENT,"Document reference is for database "+r.projectId+"/"+r.database+" but should be for database "+n.projectId+"/"+n.database);return new Io(e.x.databaseId,t.q)}return t};return this._dataConverter=new To(r),this._=new no(Wt.getPlatform(),n,this.x.credentials,this.k),this._.start(t)},t.databaseIdFromApp=function(t){var e=t.options;if(!f(e,"projectId")){if(f(e,"firestoreId"))throw new zt(Ht.INVALID_ARGUMENT,'"firestoreId" is now specified as "projectId" in firebase.initializeApp.');throw new zt(Ht.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.')}if(f(e,"firestoreOptions"))throw new zt(Ht.INVALID_ARGUMENT,'"firestoreOptions" values are now specified with Firestore.settings()');var n=e.projectId;if(!n||"string"!=typeof n)throw new zt(Ht.INVALID_ARGUMENT,"projectId must be a string in FirebaseApp.options");return new ee(n)},Object.defineProperty(t.prototype,"app",{get:function(){if(!this.x.firebaseApp)throw new zt(Ht.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this.x.firebaseApp},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(v("Firestore.collection",arguments,1),T("Firestore.collection","string",1,t),!t)throw new zt(Ht.INVALID_ARGUMENT,"Must provide a non-empty collection path to collection()");return this.ensureClientConfigured(),new Lo(oe.fromString(t),this)},t.prototype.doc=function(t){if(v("Firestore.doc",arguments,1),T("Firestore.doc","string",1,t),!t)throw new zt(Ht.INVALID_ARGUMENT,"Must provide a non-empty document path to doc()");return this.ensureClientConfigured(),Oo.forPath(oe.fromString(t),this)},t.prototype.runTransaction=function(t){var e=this;return v("Firestore.runTransaction",arguments,1),T("Firestore.runTransaction","function",1,t),this.ensureClientConfigured().transaction(function(n){return t(new Ao(e,n))})},t.prototype.batch=function(){return this.ensureClientConfigured(),new Ro(this)},Object.defineProperty(t,"logLevel",{get:function(){switch(r()){case qt.DEBUG:return"debug";case qt.ERROR:return"error";case qt.SILENT:return"silent";default:return u("Unknown log level: "+r())}},enumerable:!0,configurable:!0}),t.setLogLevel=function(t){switch(v("Firestore.setLogLevel",arguments,1),T("Firestore.setLogLevel","string",1,t),t){case"debug":o(qt.DEBUG);break;case"error":o(qt.ERROR);break;case"silent":o(qt.SILENT);break;default:throw new zt(Ht.INVALID_ARGUMENT,"Invalid log level: "+t)}},t}(),Ao=function(){function t(t,e){this.Q=t,this.z=e}return t.prototype.get=function(t){var e=this;v("Transaction.get",arguments,1);var n=xt("Transaction.get",t,this.Q);return this.z.lookup([n.q]).then(function(t){if(!t||1!==t.length)return u("Mismatch in docs returned from document lookup.");var r=t[0];return r instanceof ce?new Mo(e.Q,n.q,null,!1):new Mo(e.Q,n.q,r,!1)})},t.prototype.set=function(t,e,n){w("Transaction.set",arguments,2,3);var r=xt("Transaction.set",t,this.Q);n=Lt("Transaction.set",n);var o=n.merge?this.Q._dataConverter.parseMergeData("Transaction.set",e):this.Q._dataConverter.parseSetData("Transaction.set",e);return this.z.set(r.q,o),this},t.prototype.update=function(t,e,n){for(var r=[],o=3;o0?this.Q.ensureClientConfigured().write(this.tt):Promise.resolve()},t.prototype.verifyNotCommitted=function(){if(this.et)throw new zt(Ht.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")},t}(),Oo=function(){function t(t,e){this.q=t,this.firestore=e,this._=this.firestore.ensureClientConfigured()}return t.forPath=function(e,n){if(e.length%2!=0)throw new zt(Ht.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but "+e.canonicalString()+" has "+e.length);return new t(new se(e),n)},Object.defineProperty(t.prototype,"id",{get:function(){return this.q.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return new Lo(this.q.path.popLast(),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"path",{get:function(){return this.q.path.canonicalString()},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(v("DocumentReference.collection",arguments,1),T("DocumentReference.collection","string",1,t),!t)throw new zt(Ht.INVALID_ARGUMENT,"Must provide a non-empty collection name to collection()");var e=oe.fromString(t);return new Lo(this.q.path.child(e),this.firestore)},t.prototype.isEqual=function(e){if(!(e instanceof t))throw M("isEqual","DocumentReference",1,e);return this.firestore===e.firestore&&this.q.equals(e.q)},t.prototype.set=function(t,e){w("DocumentReference.set",arguments,1,2),e=Lt("DocumentReference.set",e);var n=e.merge?this.firestore._dataConverter.parseMergeData("DocumentReference.set",t):this.firestore._dataConverter.parseSetData("DocumentReference.set",t);return this._.write(n.toMutations(this.q,nn.NONE))},t.prototype.update=function(t,e){for(var n=[],r=2;r0)throw new zt(Ht.INVALID_ARGUMENT,"Too many arguments provided to "+t+"().");var o=e;if(!o.exists)throw new zt(Ht.NOT_FOUND,"Can't use a DocumentSnapshot that doesn't exist for "+t+"().");return this.boundFromDocument(t,o.nt,r)}var i=[e].concat(n);return this.boundFromFields(t,i,r)},t.prototype.boundFromDocument=function(t,e,n){for(var r=[],o=0,i=this.ot.orderBy;or.length)throw new zt(Ht.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, or >=) must be on the same field. But you have inequality filters on '"+e+"' and '"+t.field+"'");var n=this.ot.getFirstOrderByField();null!==n&&this.validateOrderByAndInequalityMatch(t.field,n)}},t.prototype.validateNewOrderBy=function(t){if(null===this.ot.getFirstOrderByField()){var e=this.ot.getInequalityFilterField();null!==e&&this.validateOrderByAndInequalityMatch(e,t.field)}},t.prototype.validateOrderByAndInequalityMatch=function(t,e){if(!e.equals(t))throw new zt(Ht.INVALID_ARGUMENT,"Invalid query. You have a where filter with an inequality (<, <=, >, or >=) on field '"+t+"' and so you must also use '"+t+"' as your first Query.orderBy(), but your first Query.orderBy() is on field '"+e+"' instead.")},t}(),Po=function(){function t(t,e,n){this.Q=t,this.it=e,this.at=n,this._cachedChanges=null,this.metadata={fromCache:n.fromCache,hasPendingWrites:n.hasPendingWrites}}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.at.docs.isEmpty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"size",{get:function(){return this.at.docs.size},enumerable:!0,configurable:!0}),t.prototype.forEach=function(t,e){var n=this;w("QuerySnapshot.forEach",arguments,1,2),T("QuerySnapshot.forEach","function",1,t),this.at.docs.forEach(function(r){t.call(e,n.convertToDocumentImpl(r))})},Object.defineProperty(t.prototype,"query",{get:function(){return new _o(this.it,this.Q)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"docChanges",{get:function(){return this._cachedChanges||(this._cachedChanges=Bt(this.Q,this.at)),this._cachedChanges},enumerable:!0,configurable:!0}),t.prototype.convertToDocumentImpl=function(t){return new Mo(this.Q,t.key,t,this.metadata.fromCache)},t}(),Lo=function(t){function e(e,n){var r=t.call(this,Le.atPath(e),n)||this;if(e.length%2!=1)throw new zt(Ht.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but "+e.canonicalString()+" has "+e.length);return r}return Eo(e,t),Object.defineProperty(e.prototype,"id",{get:function(){return this.ot.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){var t=this.ot.path.popLast();return t.isEmpty()?null:new Oo(new se(t),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return this.ot.path.canonicalString()},enumerable:!0,configurable:!0}),e.prototype.doc=function(t){if(w("CollectionReference.doc",arguments,0,1),0===arguments.length&&(t=Xt.newId()),T("CollectionReference.doc","string",1,t),""===t)throw new zt(Ht.INVALID_ARGUMENT,"Document path must be a non-empty string");var e=oe.fromString(t);return Oo.forPath(this.ot.path.child(e),this.firestore)},e.prototype.add=function(t){v("CollectionReference.add",arguments,1),T("CollectionReference.add","object",1,t);var e=this.doc();return e.set(t).then(function(){return e})},e}(_o),xo=l(No,"Use firebase.firestore() instead."),Bo=l(Ao,"Use firebase.firestore().runTransaction() instead."),Uo=l(Ro,"Use firebase.firestore().batch() instead."),Fo=l(Oo,"Use firebase.firestore().doc() instead."),Vo=l(Mo),qo=l(_o),jo=l(Po),Qo=l(Lo,"Use firebase.firestore().collection() instead."),Ko={Firestore:xo,GeoPoint:$t,Blob:Jt,Transaction:Bo,WriteBatch:Uo,DocumentReference:Fo,DocumentSnapshot:Vo,Query:qo,QuerySnapshot:jo,CollectionReference:Qo,FieldPath:xn,FieldValue:mo,setLogLevel:No.setLogLevel};e.registerFirestore=Vt,Vt(jt.default)},115:function(module,exports,__webpack_require__){(function(global){(function(){function l(t){return"string"==typeof t}function aa(){}function ba(t){var e=typeof t;if("object"==e){if(!t)return"null";if(t instanceof Array)return"array";if(t instanceof Object)return e;var n=Object.prototype.toString.call(t);if("[object Window]"==n)return"object";if("[object Array]"==n||"number"==typeof t.length&&void 0!==t.splice&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("splice"))return"array";if("[object Function]"==n||void 0!==t.call&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("call"))return"function"}else if("function"==e&&void 0===t.call)return"object";return e}function n(t){return"array"==ba(t)}function ca(t){var e=ba(t);return"array"==e||"object"==e&&"number"==typeof t.length}function da(t){return"function"==ba(t)}function p(t){var e=typeof t;return"object"==e&&null!=t||"function"==e}function fa(t,e,n){return t.call.apply(t.bind,arguments)}function ha(t,e,n){if(!t)throw Error();if(2e?1:0}function na(t,e){e.unshift(t),ja.call(this,ka.apply(null,e)),e.shift()}function oa(t,e){throw new na("Failure"+(t?": "+t:""),Array.prototype.slice.call(arguments,1))}function w(){0!=qa&&(ra[this[q]||(this[q]=++ea)]=this),this.i=this.i,this.w=this.w}function ua(t){t:{for(var e=va,n=t.length,r=l(t)?t.split(""):t,o=0;oe?null:l(t)?t.charAt(e):t[e]}function wa(t){if(!n(t))for(var e=t.length-1;0<=e;e--)delete t[e];t.length=0}function xa(t){return Array.prototype.concat.apply([],arguments)}function ya(t){var e=t.length;if(0r.keyCode||void 0!=r.returnValue)){t:{var o=!1;if(0==r.keyCode)try{r.keyCode=-1;break t}catch(t){o=!0}(o||void 0==r.returnValue)&&(r.returnValue=!0)}for(r=[],o=e.a;o;o=o.parentNode)r.push(o);for(t=t.type,o=r.length-1;0<=o;o--){e.a=r[o];var i=xb(r[o],t,!0,e);n=n&&i}for(o=0;oe.b&&(e.b++,t.next=e.a,e.a=t)}Wb=!1}function Xb(e,n){B.call(this),this.b=e||1,this.a=n||k,this.f=r(this.ib,this),this.g=t()}function Yb(t){t.$=!1,t.K&&(t.a.clearTimeout(t.K),t.K=null)}function Zb(t,e,n){if(da(t))n&&(t=r(t,n));else{if(!t||"function"!=typeof t.handleEvent)throw Error("Invalid listener argument");t=r(t.handleEvent,t)}return 2147483647<+e?-1:k.setTimeout(t,e||0)}function $b(t,e,n){w.call(this),this.f=null!=n?r(t,n):t,this.c=e,this.b=r(this.bb,this),this.a=[]}function ac(t){t.X=Zb(t.b,t.c),t.f.apply(null,t.a)}function C(t){w.call(this),this.b=t,this.a={}}function cc(t){Ba(t.a,function(t,e){this.a.hasOwnProperty(e)&&wb(t)},t),t.a={}}function dc(t,e,n){this.reset(t,e,n,void 0,void 0)}function fc(t){this.f=t,this.b=this.c=this.a=null}function D(t,e){this.name=t,this.value=e}function lc(t){return t.c?t.c:t.a?lc(t.a):(oa("Root logger has no level set."),null)}function oc(t){nc||(nc=new fc(""),mc[""]=nc,nc.c=jc);var e;if(!(e=mc[t])){e=new fc(t);var n=t.lastIndexOf("."),r=t.substr(n+1);n=oc(t.substr(0,n)),n.b||(n.b={}),n.b[r]=e,e.a=n,mc[t]=e}return e}function E(t,e){t&&t.log(hc,e,void 0)}function pc(t,e){t&&t.log(ic,e,void 0)}function F(t,e){t&&t.log(kc,e,void 0)}function qc(){this.a=oc("goog.labs.net.webChannel.WebChannelDebug"),this.b=!0}function rc(t,e,n,r,o,i){H(t,function(){if(t.b)if(i)for(var a="",s=i.split("&"),u=0;ui.length)){var a=i[1];if(n(a)&&!(1>a.length)){var s=a[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var u=1;ue||3==e&&!Ka&&!t.a.V())){t.B||4!=e||7==n||Ac(8==n||0>=r?3:2),Zc(t);var o=t.a.W();t.C=o,(n=t.a.V())||I(t.b,function(){return"No response text for uri "+t.g+" status "+o}),t.c=200==o,sc(t.b,t.o,t.g,t.f,t.T,e,o),t.c?(t.M?($c(t,e,n),Ka&&t.c&&3==e&&ad(t)):(tc(t.b,t.f,n,null),bd(t,n)),4==e&&cd(t),t.c&&!t.B&&(4==e?t.i.ua(t):(t.c=!1,Wc(t)))):(400==o&&0e.length?Rc:(e=e.substr(r,n),t.F=r+n,e))}function Wc(e){e.U=t()+e.S,fd(e,e.S)}function fd(t,e){if(null!=t.w)throw Error("WatchDog timer not null");t.w=Ec(r(t.cb,t),e)}function Zc(t){t.w&&(k.clearTimeout(t.w),t.w=null)}function dd(t){t.i.Ja()||t.B||t.i.ua(t)}function cd(t){Zc(t);var e=t.I;e&&"function"==typeof e.Z&&e.Z(),t.I=null,Yb(t.H),cc(t.N),t.a&&(e=t.a,t.a=null,e.abort(),e.Z())}function bd(t,e){try{t.i.Ma(t,e),Ac(4)}catch(e){wc(t.b,e,"Error in httprequest callback")}}function gd(t){if(t.v&&"function"==typeof t.v)return t.v();if(l(t))return t.split("");if(ca(t)){for(var e=[],n=t.length,r=0;r2*t.c&&id(t),!0)}function id(t){if(t.c!=t.a.length){for(var e=0,n=0;ee)throw Error("Bad port number "+e);t.i=e}else t.i=null}function qd(t,e,n){e instanceof td?(t.c=e,zd(t.c,t.h)):(n||(e=ud(e,Ad)),t.c=new td(e,t.h))}function Q(t,e,n){t.c.set(e,n)}function Xc(t,e,r){n(r)||(r=[r+""]),Bd(t.c,e,r)}function Tc(e){return Q(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^t()).toString(36)),e}function Cd(t){return t instanceof P?L(t):new P(t,void 0)}function Dd(t,e,n,r){var o=new P(null,void 0);return t&&nd(o,t),e&&od(o,e),n&&pd(o,n),r&&(o.a=r),o}function sd(t,e){return t?e?decodeURI(t.replace(/%25/g,"%2525")):decodeURIComponent(t):""}function ud(t,e,n){return l(t)?(t=encodeURI(t).replace(e,Ed),n&&(t=t.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),t):null}function Ed(t){return t=t.charCodeAt(0),"%"+(t>>4&15).toString(16)+(15&t).toString(16)}function td(t,e){this.b=this.a=null,this.c=t||null,this.f=!!e}function R(t){t.a||(t.a=new N,t.b=0,t.c&&md(t.c,function(e,n){t.add(decodeURIComponent(e.replace(/\+/g," ")),n)}))}function Gd(t,e){R(t),e=Fd(t,e),O(t.a.b,e)&&(t.c=null,t.b-=t.a.get(e).length,kd(t.a,e))}function Hd(t,e){return R(t),e=Fd(t,e),O(t.a.b,e)}function Bd(t,e,n){Gd(t,e),0=t.f}function ce(t,e){return t.b?t.b==e:!!t.a&&t.a.contains(e)}function ae(t,e){t.a?t.a.add(e):t.b=e}function de(t,e){t.b&&t.b==e?t.b=null:t.a&&t.a.contains(e)&&kd(t.a.a,Wd(e))}function ee(t){if(null!=t.b)return t.c.concat(t.b.s);if(null!=t.a&&0!=t.a.a.c){var e=t.c;return ta(t.a.v(),function(t){e=e.concat(t.s)}),e}return ya(t.c)}function fe(t,e){t.c=t.c.concat(e)}function ge(){}function he(){this.a=new ge}function ie(t,e,n){var r=n||"";try{hd(t,function(t,n){var o=t;p(t)&&(o=Db(t)),e.push(r+n+"="+encodeURIComponent(o))})}catch(t){throw e.push(r+"type="+encodeURIComponent("_badmap")),t}}function je(t,e){var n=new qc;I(n,"TestLoadImage: loading "+t);var r=new Image;r.onload=ia(ke,n,r,"TestLoadImage: loaded",!0,e),r.onerror=ia(ke,n,r,"TestLoadImage: error",!1,e),r.onabort=ia(ke,n,r,"TestLoadImage: abort",!1,e),r.ontimeout=ia(ke,n,r,"TestLoadImage: timeout",!1,e),k.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=t}function ke(t,e,n,r,o){try{I(t,n),e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null,o(r)}catch(e){wc(t,e)}}function T(t){B.call(this),this.headers=new N,this.F=t||null,this.f=!1,this.D=this.a=null,this.M=this.s="",this.j=0,this.g="",this.h=this.I=this.o=this.H=!1,this.l=0,this.B=null,this.N=le,this.C=this.m=!1}function qe(t){return z&&Ta(9)&&"number"==typeof t.timeout&&void 0!==t.ontimeout}function va(t){return"content-type"==t.toLowerCase()}function oe(t,e){t.f=!1,t.a&&(t.h=!0,t.a.abort(),t.h=!1),t.g=e,t.j=5,re(t),se(t)}function re(t){t.H||(t.H=!0,t.dispatchEvent("complete"),t.dispatchEvent("error"))}function te(t){if(t.f&&void 0!==goog)if(t.D[1]&&4==M(t)&&2==t.W())F(t.b,U(t,"Local request error detected and ignored"));else if(t.o&&4==M(t))Zb(t.La,0,t);else if(t.dispatchEvent("readystatechange"),4==M(t)){F(t.b,U(t,"Request complete")),t.f=!1;try{var e=t.W();t:switch(e){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var n=!0;break t;default:n=!1}var r;if(!(r=n)){var o;if(o=0===e){var i=(t.s+"").match(ld)[1]||null;if(!i&&k.self&&k.self.location){var a=k.self.location.protocol;i=a.substr(0,a.length-1)}o=!me.test(i?i.toLowerCase():"")}r=o}r?(t.dispatchEvent("complete"),t.dispatchEvent("success")):(t.j=6,t.g=t.Ga()+" ["+t.W()+"]",re(t))}finally{se(t)}}}function se(t,e){if(t.a){pe(t);var n=t.a,r=t.D[0]?aa:null;t.a=null,t.D=null,e||t.dispatchEvent("ready");try{n.onreadystatechange=r}catch(e){(t=t.b)&&t.log(gc,"Problem encountered resetting onreadystatechange: "+e.message,void 0)}}}function pe(t){t.a&&t.C&&(t.a.ontimeout=null),t.B&&(k.clearTimeout(t.B),t.B=null)}function M(t){return t.a?t.a.readyState:0}function U(t,e){return e+" ["+t.M+" "+t.s+" "+t.W()+"]"}function ue(t){var e="";return Ba(t,function(t,n){e+=n,e+=":",e+=t,e+="\r\n"}),e}function ve(t,e,n){t:{for(r in n){var r=!1;break t}r=!0}if(r)return t;if(n=ue(n),l(t)){if(e=encodeURIComponent(e+""),n=null!=n?"="+encodeURIComponent(n+""):"",e+=n){if(n=t.indexOf("#"),0>n&&(n=t.length),0>(r=t.indexOf("?"))||r>n){r=n;var o=""}else o=t.substring(r+1,n);t=[t.substr(0,r),o,t.substr(n)],n=t[1],t[1]=e?n?n+"&"+e:e:n,t=t[0]+(t[1]?"?"+t[1]:"")+t[2]}return t}return Q(t,e,n),t}function we(t){this.ya=0,this.g=[],this.a=new qc,this.H=new Vd,this.ja=this.wa=this.F=this.ka=this.b=this.J=this.j=this.U=this.h=this.M=this.i=null,this.Ua=this.P=0,this.la=this.B=this.o=this.m=this.l=this.f=null,this.s=this.xa=this.N=-1,this.T=this.w=this.C=0,this.S=t&&t.supportsCrossDomainXhr||!1,this.I="",this.c=new Yd(t&&t.concurrentRequestLimit),this.ma=new he,this.D=!t||void 0===t.backgroundChannelTest||t.backgroundChannelTest,this.Ta=t&&t.fastHandshake||!1,t&&t.Ea&&this.a.Ea()}function xe(e){if(I(e.a,"disconnect()"),ye(e),3==e.G){var n=e.P++,r=L(e.F);Q(r,"SID",e.I),Q(r,"RID",n),Q(r,"TYPE","terminate"),ze(e,r),n=new K(e,e.a,n,void 0),n.J=2,n.h=Tc(L(r)),r=!1,k.navigator&&k.navigator.sendBeacon&&(r=k.navigator.sendBeacon(""+n.h,"")),!r&&k.Image&&((new Image).src=n.h,r=!0),r||(n.a=n.i.da(null),n.a.fa(n.h)),n.D=t(),Wc(n)}Ae(e)}function ye(t){t.B&&(t.B.abort(),t.B=null),t.b&&(t.b.cancel(),t.b=null),t.m&&(k.clearTimeout(t.m),t.m=null),Be(t),t.c.cancel(),t.l&&(k.clearTimeout(t.l),t.l=null)}function Ce(t,e){1e3==t.g.length&&xc(t.a,function(){return"Already have 1000 queued maps upon queueing "+Db(e)}),t.g.push(new Xd(t.Ua++,e)),3==t.G&&De(t)}function De(t){be(t.c)||t.l||(t.l=Ec(r(t.Oa,t),0),t.C=0)}function Ee(t,e){var n=t.c;return(n.b?1:n.a?n.a.u():0)>=t.c.f-(t.l?1:0)?(xc(t.a,"Unexpected retry request is scheduled."),!1):t.l?(I(t.a,"Use the retry request that is already scheduled."),t.g=e.s.concat(t.g),!0):!(1==t.G||2==t.G||2<=t.C||(I(t.a,"Going to retry POST"),t.l=Ec(r(t.Oa,t,e),Fe(t,t.C)),t.C++,0))}function He(t,e){var n;n=e?e.f:t.P++;var r=L(t.F);Q(r,"SID",t.I),Q(r,"RID",n),Q(r,"AID",t.N),ze(t,r),t.h&&t.i&&ve(r,t.h,t.i),n=new K(t,t.a,n,t.C+1),null===t.h&&(n.j=t.i),e&&(t.g=e.s.concat(t.g)),e=Ge(t,n),n.setTimeout(Math.round(1e4)+Math.round(1e4*Math.random())),ae(t.c,n),Sc(n,r,e)}function ze(t,e){t.f&&hd({},function(t,n){Q(e,n,t)})}function Ge(t,e){var n=Math.min(t.g.length,1e3),o=t.f?r(t.f.Va,t.f,t):null;t:for(var i=t.g,a=-1;;){var s=["count="+n];-1==a?0(h-=a))a=Math.max(0,i[c].a-100),u=!1;else try{ie(l,s,"req"+h+"_")}catch(t){o&&o(l)}}if(u){o=s.join("&");break t}}return t=t.g.splice(0,n),e.s=t,o}function Ie(t){if(!t.b&&!t.m){t.T=1;var e=t.Na;Tb||Ub(),Wb||(Tb(),Wb=!0),Pb.add(e,t),t.w=0}}function Je(t){return t.b||t.m?(xc(t.a,"Request already in progress"),!1):!(3<=t.w||(I(t.a,"Going to retry GET"),t.T++,t.m=Ec(r(t.Na,t),Fe(t,t.w)),t.w++,0))}function Sd(t,e,n){I(t.a,"Test Connection Finished");var r=e.m;r&&$d(t.c,r),t.la=n,t.s=e.f,I(t.a,"connectChannel_()"),t.F=Ke(t,t.ka),De(t)}function Ud(t,e){I(t.a,"Test Connection Failed"),t.s=e.f,V(t,2)}function Be(t){null!=t.o&&(k.clearTimeout(t.o),t.o=null)}function Fe(t,e){var n=5e3+Math.floor(1e4*Math.random());return t.ra()||(I(t.a,"Inactive channel"),n*=2),n*e}function V(t,e){if(H(t.a,"Error code "+e),2==e){var n=null;t.f&&(n=null);var o=r(t.hb,t);n||(n=new P("//www.google.com/images/cleardot.gif"),k.location&&"http"==k.location.protocol||nd(n,"https"),Tc(n)),je(""+n,o)}else J(2);I(t.a,"HttpChannel: error - "+e),t.G=0,t.f&&t.f.Ba(e),Ae(t),ye(t)}function Ae(t){if(t.G=0,t.s=-1,t.f){var e=ee(t.c);0==e.length&&0==t.g.length||(I(t.a,function(){return"Number of undelivered maps, pending: "+e.length+", outgoing: "+t.g.length}),t.c.c.length=0,ya(t.g),t.g.length=0),t.f.Aa()}}function Ke(t,e){return e=Le(t,null,e),I(t.a,"GetForwardChannelUri: "+e),e}function Td(t,e,n){return e=Le(t,t.ia()?e:null,n),I(t.a,"GetBackChannelUri: "+e),e}function Le(t,e,n){var r=Cd(n);if(""!=r.b)e&&od(r,e+"."+r.b),pd(r,r.i);else{var o,i=k.location;o=e?e+"."+i.hostname:i.hostname,r=Dd(i.protocol,o,i.port,n)}return t.U&&Ba(t.U,function(t,e){Q(r,e,t)}),e=t.j,n=t.J,e&&n&&Q(r,e,n),Q(r,"VER",t.oa),ze(t,r),r}function Me(){}function Ne(t){for(var e=arguments[0],n=1;nthis.c)throw Error(We);this.a=new Te,this.b=new S,this.g=null,this.ba()}function Xe(t){if("function"==typeof t.Z)t.Z();else for(var e in t)t[e]=null}function Ye(t,e){this.a=t,this.b=e}function Ze(t){if(this.a=[],t)t:{if(t instanceof Ze){var e=t.O();if(t=t.v(),0>=this.u()){for(var n=this.a,r=0;r>1,t[r].a>n.a);)t[e]=t[r],e=r;t[e]=n}function af(){Ze.call(this)}function X(t,e){this.f=new af,Ve.call(this,t,e)}function Y(t,e,n,r){this.l=t,this.j=!!r,X.call(this,e,n)}var g,goog=goog||{},k=this,q="closure_uid_"+(1e9*Math.random()>>>0),ea=0,t=Date.now||function(){return+new Date};u(ja,Error),ja.prototype.name="CustomError";var la=String.prototype.trim?function(t){return t.trim()}:function(t){return t.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")};u(na,ja),na.prototype.name="AssertionError";var qa=0,ra={};w.prototype.i=!1,w.prototype.Z=function(){if(!this.i&&(this.i=!0,this.A(),0!=qa)){var t=this[q]||(this[q]=++ea);delete ra[t]}},w.prototype.A=function(){if(this.w)for(;this.w.length;)this.w.shift()()};var sa=Array.prototype.indexOf?function(t,e){return Array.prototype.indexOf.call(t,e,void 0)}:function(t,e){if(l(t))return l(e)&&1==e.length?t.indexOf(e,0):-1;for(var n=0;nparseFloat(Qa)){Pa=Sa+"";break t}}Pa=Qa}var Ja={},Ua,Va=k.document;Ua=Va&&z?Oa()||("CSS1Compat"==Va.compatMode?parseInt(Pa,10):5):void 0;var Wa=Object.freeze||function(t){return t},Xa=!z||9<=+Ua,Ya=z&&!Ta("9"),Za=function(){if(!k.addEventListener||!Object.defineProperty)return!1;var t=!1,e=Object.defineProperty({},"passive",{get:function(){t=!0}});return k.addEventListener("test",aa,e),k.removeEventListener("test",aa,e),t}();A.prototype.b=function(){this.Pa=!1},u($a,A);var ab=Wa({2:"touch",3:"pen",4:"mouse"});$a.prototype.b=function(){$a.L.b.call(this);var t=this.c;if(t.preventDefault)t.preventDefault();else if(t.returnValue=!1,Ya)try{(t.ctrlKey||112<=t.keyCode&&123>=t.keyCode)&&(t.keyCode=-1)}catch(t){}};var bb="closure_listenable_"+(1e6*Math.random()|0),db=0;gb.prototype.add=function(t,e,n,r,o){var i=""+t;(t=this.a[i])||(t=this.a[i]=[],this.b++);var a=hb(t,e,r,o);return-1>>0);u(B,w),B.prototype[bb]=!0,g=B.prototype,g.addEventListener=function(t,e,n,r){nb(this,t,e,n,r)},g.removeEventListener=function(t,e,n,r){vb(this,t,e,n,r)},g.dispatchEvent=function(t){var e,n=this.J;if(n)for(e=[];n;n=n.J)e.push(n);n=this.P;var r=t.type||t;if(l(t))t=new A(t,n);else if(t instanceof A)t.target=t.target||n;else{var o=t;t=new A(r,n),Ga(t,o)}if(o=!0,e)for(var i=e.length-1;0<=i;i--){var a=t.a=e[i];o=Ab(a,r,!0,t)&&o}if(a=t.a=n,o=Ab(a,r,!0,t)&&o,o=Ab(a,r,!1,t)&&o,e)for(i=0;i=lc(this).value)for(da(e)&&(e=e()),t=new dc(t,e+"",this.f),n&&(t.a=n),n=this;n;)n=n.a};var mc={},nc=null;qc.prototype.Ea=function(){this.b=!1};var yc=new B;u(zc,A),u(Bc,A),u(Cc,A);var Fc={NO_ERROR:0,jb:1,qb:2,pb:3,mb:4,ob:5,rb:6,Ra:7,TIMEOUT:8,ub:9},Gc={lb:"complete",yb:"success",Sa:"error",Ra:"abort",wb:"ready",xb:"readystatechange",TIMEOUT:"timeout",sb:"incrementaldata",vb:"progress",nb:"downloadprogress",zb:"uploadprogress"};Hc.prototype.a=null;var Kc;u(Lc,Hc),Kc=new Lc;var Nc=45e3,Oc=250,Qc={},Rc={};g=K.prototype,g.setTimeout=function(t){this.S=t},g.fb=function(t){t=t.target;var e=this.I;e&&3==M(t)?(I(this.b,"Throttling readystatechange."),e.Xa()):this.Qa(t)},g.Qa=function(t){try{t==this.a?Yc(this):E(this.b.a,"Called back with an unexpected xmlhttp")}catch(t){if(I(this.b,"Failed call to OnXmlHttpReadyStateChanged_"),this.a&&this.a.V()){var e=this;wc(this.b,t,function(){return"ResponseText: "+e.a.V()})}else wc(this.b,t,"No response text")}},g.eb=function(){var t=M(this.a),e=this.a.V();this.Fe&&this.la&&0==this.w&&!this.o&&(this.o=Ec(r(this.$a,this),6e3)));else I(this.a,"Bad POST response data returned"),V(this,11)}else if(this.b==t&&Be(this),!/^[\s\xa0]*$/.test(e))for(e=o=this.ma.a.parse(e),o=0;oe-this.g)){for(var n;0this.c&&0=o)i=void 0;else{if(1==o)wa(r);else{r[0]=r.pop(),r=0,n=n.a,o=n.length;for(var a=n[r];r>1;){var s=2*r+1,u=2*r+2;if(s=ua.a)break;n[r]=n[s],r=s}n[r]=a}i=i.b}i.apply(this,[e])}},g.na=function(t){X.L.na.call(this,t),this.sa()},g.ba=function(){X.L.ba.call(this),this.sa()},g.A=function(){X.L.A.call(this),k.clearTimeout(void 0),wa(this.f.a),this.f=null},u(Y,X),Y.prototype.qa=function(){var t=new T,e=this.l;return e&&e.forEach(function(e,n){t.headers.set(n,e)}),this.j&&(t.m=!0),t},Y.prototype.ta=function(t){return!t.i&&!t.a},Oe.prototype.createWebChannel=Oe.prototype.a,W.prototype.send=W.prototype.l,W.prototype.open=W.prototype.j,W.prototype.close=W.prototype.close,Fc.NO_ERROR=0,Fc.TIMEOUT=8,Fc.HTTP_ERROR=6,Gc.COMPLETE="complete",Md.EventType=Nd,Nd.OPEN="a",Nd.CLOSE="b",Nd.ERROR="c",Nd.MESSAGE="d",B.prototype.listen=B.prototype.aa,Y.prototype.getObject=Y.prototype.ea,Y.prototype.releaseObject=Y.prototype.gb,T.prototype.listenOnce=T.prototype.Ha,T.prototype.getLastError=T.prototype.Za,T.prototype.getLastErrorCode=T.prototype.Fa,T.prototype.getStatus=T.prototype.W,T.prototype.getStatusText=T.prototype.Ga,T.prototype.getResponseJson=T.prototype.Ya,T.prototype.getResponseText=T.prototype.V,T.prototype.getResponseText=T.prototype.V,T.prototype.send=T.prototype.fa,module.exports={createWebChannelTransport:Se,ErrorCode:Fc,EventType:Gc,WebChannel:Md,XhrIoPool:Y}}).call(void 0!==global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})}).call(exports,__webpack_require__(12))}},[113])}catch(t){throw Error("Cannot instantiate firebase-firestore.js - be sure to load firebase-app.js first.")} //# sourceMappingURL=firebase-firestore.js.map