!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app"],e):e((t=t||self).firebase)}(this,function(Od){"use strict";try{(function(){var o,t;Od=Od&&Od.hasOwnProperty("default")?Od.default:Od,(t=o=o||{})[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT";function e(t,e){for(var n=[],r=2;ra[0]&&e[1]"})}(o,r):"Error",s=this.serviceName+": "+a+" ("+i+").",u=new f(i,s),c=0,h=Object.keys(r);c>>0),R=0;function M(t,e,n){return t.call.apply(t.bind,arguments)}function _(e,n,t){if(!e)throw Error();if(2parseFloat(ct)){tt=String(lt);break t}}tt=ct}var ft,pt={};function dt(s){return function(t,e){var n=pt;return Object.prototype.hasOwnProperty.call(n,t)?n[t]:n[t]=e(t)}(s,function(){for(var t=0,e=j(String(tt)).split("."),n=j(String(s)).split("."),r=Math.max(e.length,n.length),i=0;0==t&&i>>0);function Vt(e){return"function"==C(e)?e:(e[Ft]||(e[Ft]=function(t){return e.handleEvent(t)}),e[Ft])}function Bt(){q.call(this),this.c=new Dt(this),(this.J=this).B=null}function Ut(t,e,n,r){if(!(e=t.c.a[String(e)]))return!0;e=e.concat();for(var i=!0,o=0;oe.length?ke:(e=e.substr(r,n),t.A=r+n,e))}function Le(t){t.R=L()+t.O,xe(t,t.O)}function xe(t,e){if(null!=t.i)throw Error("WatchDog timer not null");t.i=me(O(t.bb,t),e)}function qe(t){t.i&&(w.clearTimeout(t.i),t.i=null)}function Fe(t){t.g.Da()||t.m||t.g.na(t)}function Ve(t){qe(t);var e=t.B;e&&"function"==typeof e.la&&e.la(),t.B=null,te(t.P),se(t.I),t.a&&(e=t.a,t.a=null,e.abort(),e.la())}function Be(t,e){try{t.g.Ga(t,e),le(4)}catch(t){}}function Ue(t,e){if(t.forEach&&"function"==typeof t.forEach)t.forEach(e,void 0);else if(N(t)||E(t))V(t,e,void 0);else{if(t.K&&"function"==typeof t.K)var n=t.K();else if(t.C&&"function"==typeof t.C)n=void 0;else if(N(t)||E(t)){n=[];for(var r=t.length,i=0;i2*t.c&&je(t))}function je(t){if(t.c!=t.a.length){for(var e=0,n=0;e>4&15).toString(16)+(15&t).toString(16)}ze.prototype.toString=function(){var t=[],e=this.f;e&&t.push(rn(e,an,!0),":");var n=this.b;return!n&&"file"!=e||(t.push("//"),(e=this.j)&&t.push(rn(e,an,!0),"@"),t.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.i)&&t.push(":",String(n))),(n=this.a)&&(this.b&&"/"!=n.charAt(0)&&t.push("/"),t.push(rn(n,"/"==n.charAt(0)?un:sn,!0))),(n=this.c.toString())&&t.push("?",n),(n=this.g)&&t.push("#",rn(n,hn)),t.join("")},ze.prototype.resolve=function(t){var e=He(this),n=!!t.f;n?Ye(e,t.f):n=!!t.j,n?e.j=t.j:n=!!t.b,n?Xe(e,t.b):n=null!=t.i;var r=t.a;if(n)Je(e,t.i);else if(n=!!t.a){if("/"!=r.charAt(0))if(this.b&&!this.a)r="/"+r;else{var i=e.a.lastIndexOf("/");-1!=i&&(r=e.a.substr(0,i+1)+r)}if(".."==(i=r)||"."==i)r="";else if(W(i,"./")||W(i,"/.")){r=0==i.lastIndexOf("/",0),i=i.split("/");for(var o=[],a=0;a=t.f}function An(t){return t.b?1:t.a?t.a.a.c:0}function kn(t,e){return t=t.b?t.b==e:!!t.a&&(e=Sn(e),We(t.a.a.b,e))}function Rn(t,e){t.a?t.a.add(e):t.b=e}function Mn(t,e){var n;t.b&&t.b==e?t.b=null:((n=t.a)&&(n=Sn(e),n=We(t.a.a.b,n)),n&&Ke(t.a.a,Sn(e)))}function _n(t){if(null!=t.b)return t.c.concat(t.b.j);if(null==t.a||0==t.a.a.c)return U(t.c);var e=t.c;return V(t.a.C(),function(t){e=e.concat(t.j)}),e}function On(){}function Pn(){this.a=new On}function Ln(t,r,e){var i=e||"";try{Ue(t,function(t,e){var n=t;A(t)&&(n=Qt(t)),r.push(i+e+"="+encodeURIComponent(n))})}catch(t){throw r.push(i+"type="+encodeURIComponent("_badmap")),t}}function xn(t,e,n,r,i){try{e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null,i(r)}catch(t){}}In.prototype.cancel=function(){this.c=_n(this),this.b?(this.b.cancel(),this.b=null):this.a&&0!=this.a.a.c&&(V(this.a.C(),function(t){t.cancel()}),function(t){t.b={},t.a.length=0,t.c=0}(this.a.a))},On.prototype.stringify=function(t){return w.JSON.stringify(t,void 0)},On.prototype.parse=function(t){return w.JSON.parse(t,void 0)};var qn=w.JSON.parse;function Fn(t){Bt.call(this),this.headers=new Qe,this.H=t||null,this.b=!1,this.s=this.a=null,this.A="",this.h=0,this.f="",this.g=this.w=this.l=this.v=!1,this.o=0,this.m=null,this.I=Vn,this.D=this.F=!1}x(Fn,Bt);var Vn="",Bn=/^https?$/i,Un=["POST","PUT"];function Qn(t){return"content-type"==t.toLowerCase()}function Kn(t,e){t.b=!1,t.a&&(t.g=!0,t.a.abort(),t.g=!1),t.f=e,t.h=5,jn(t),Gn(t)}function jn(t){t.v||(t.v=!0,t.dispatchEvent("complete"),t.dispatchEvent("error"))}function Wn(t){if(t.b&&void 0!==b&&(!t.s[1]||4!=Hn(t)||2!=t.T()))if(t.l&&4==Hn(t))ee(t.Fa,0,t);else if(t.dispatchEvent("readystatechange"),4==Hn(t)){t.b=!1;try{var e,n=t.T();t:switch(n){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var r=!0;break t;default:r=!1}if(!(e=r)){var i;if(i=0===n){var o=String(t.A).match(Ge)[1]||null;if(!o&&w.self&&w.self.location){var a=w.self.location.protocol;o=a.substr(0,a.length-1)}i=!Bn.test(o?o.toLowerCase():"")}e=i}e?(t.dispatchEvent("complete"),t.dispatchEvent("success")):(t.h=6,t.f=t.za()+" ["+t.T()+"]",jn(t))}finally{Gn(t)}}}function Gn(t,e){if(t.a){zn(t);var n=t.a,r=t.s[0]?I:null;t.a=null,t.s=null,e||t.dispatchEvent("ready");try{n.onreadystatechange=r}catch(t){}}}function zn(t){t.a&&t.D&&(t.a.ontimeout=null),t.m&&(w.clearTimeout(t.m),t.m=null)}function Hn(t){return t.a?t.a.readyState:0}function Yn(t,e){return t.a?t.a.getResponseHeader(e):null}function Xn(t,e,n){t:{for(r in n){var r=!1;break t}r=!0}if(r)return t;if(n=function(t){var n="";return Y(t,function(t,e){n+=e,n+=":",n+=t,n+="\r\n"}),n}(n),E(t)){if(e=encodeURIComponent(String(e)),e+=n=null!=n?"="+encodeURIComponent(String(n)):""){if((n=t.indexOf("#"))<0&&(n=t.length),(r=t.indexOf("?"))<0||n=t.b.f-(t.h?1:0))&&(t.h?(t.f=e.j.concat(t.f),!0):!(1==t.u||2==t.u||t.A>=(t.Pa?0:t.Qa))&&(t.h=me(O(t.Ia,t,e),cr(t,t.A)),t.A++,!0))}(this,t)||2==n&&ar(this)))switch(e&&0r)throw new Qr(Ur.INVALID_ARGUMENT,"Function "+t+"() requires between "+n+" and "+r+" arguments, but was called with "+pi(e.length,"argument")+".")}function ti(t,e,n,r){ai(t,e,fi(n)+" argument",r)}function ei(t,e,n,r){void 0!==r&&ti(t,e,n,r)}function ni(t,e,n,r){ai(t,e,n+" option",r)}function ri(t,e,n,r){void 0!==r&&ni(t,e,n,r)}function ii(t,e,n,r,i){void 0!==r&&function(t,e,n,r,i){if(!(r instanceof Array))throw new Qr(Ur.INVALID_ARGUMENT,"Function "+t+"() requires its "+e+" option to be an array, but it was: "+ui(r));for(var o=0;o=t,"Can't call popFirst() with less segments"),this.construct(this.segments,this.offset+t,this.length-t)},_i.prototype.popLast=function(){return xr(!this.isEmpty(),"Can't call popLast() on empty path"),this.construct(this.segments,this.offset,this.length-1)},_i.prototype.firstSegment=function(){return xr(!this.isEmpty(),"Can't call firstSegment() on empty path"),this.segments[this.offset]},_i.prototype.lastSegment=function(){return this.get(this.length-1)},_i.prototype.get=function(t){return xr(te.length?1:0},_i);function _i(t,e,n){void 0===e?e=0:e>t.length&&Lr("offset "+e+" out of range "+t.length),void 0===n?n=t.length-e:n>t.length-e&&Lr("length "+n+" out of range "+(t.length-e)),this.segments=t,this.offset=e,this.len=n}var Oi,Pi=(s(Li,Oi=Mi),Li.prototype.construct=function(t,e,n){return new Li(t,e,n)},Li.prototype.canonicalString=function(){return this.toArray().join("/")},Li.prototype.toString=function(){return this.canonicalString()},Li.fromString=function(t){if(0<=t.indexOf("//"))throw new Qr(Ur.INVALID_ARGUMENT,"Invalid path ("+t+"). Paths must not contain // in them.");return new Li(t.split("/").filter(function(t){return 0=i,"Should have found mutation after "+i),o=r.serializer.fromDbMutationBatch(e)),n.done()}).next(function(){return o})},Fo.prototype.getHighestUnacknowledgedBatchId=function(t){var e=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]),r=-1;return Qo(t).iterate({index:pu.userMutationsIndex,range:e,reverse:!0},function(t,e,n){r=e.batchId,n.done()}).next(function(){return r})},Fo.prototype.getAllMutationBatches=function(t){var e=this,n=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return Qo(t).loadAll(pu.userMutationsIndex,n).next(function(t){return t.map(function(t){return e.serializer.fromDbMutationBatch(t)})})},Fo.prototype.getAllMutationBatchesAffectingDocumentKey=function(s,u){var c=this,t=mu.prefixForPath(this.userId,u.path),e=IDBKeyRange.lowerBound(t),h=[];return Ko(s).iterate({range:e},function(e,t,n){var r=e[0],i=e[1],o=e[2],a=no(i);if(r===c.userId&&u.path.isEqual(a))return Qo(s).get(o).next(function(t){if(!t)throw Lr("Dangling document-mutation reference found: "+e+" which points to "+o);xr(t.userId===c.userId,"Unexpected user '"+t.userId+"' for mutation batch "+o),h.push(c.serializer.fromDbMutationBatch(t))});n.done()}).next(function(){return h})},Fo.prototype.getAllMutationBatchesAffectingDocumentKeys=function(r,t){var u=this,c=new yo(yi),i=[];return t.forEach(function(s){var t=mu.prefixForPath(u.userId,s.path),e=IDBKeyRange.lowerBound(t),n=Ko(r).iterate({range:e},function(t,e,n){var r=t[0],i=t[1],o=t[2],a=no(i);r===u.userId&&s.path.isEqual(a)?c=c.add(o):n.done()});i.push(n)}),Lo.waitFor(i).next(function(){return u.lookupMutationBatches(r,c)})},Fo.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var s=this;xr(!e.isDocumentQuery(),"Document queries shouldn't go down this path"),xr(!e.isCollectionGroupQuery(),"CollectionGroup queries should be handled in LocalDocumentsView");var u=e.path,c=u.length+1,n=mu.prefixForPath(this.userId,u),r=IDBKeyRange.lowerBound(n),h=new yo(yi);return Ko(t).iterate({range:r},function(t,e,n){var r=t[0],i=t[1],o=t[2],a=no(i);r===s.userId&&u.isPrefixOf(a)?a.length===c&&(h=h.add(o)):n.done()}).next(function(){return s.lookupMutationBatches(t,h)})},Fo.prototype.lookupMutationBatches=function(t,e){var n=this,r=[],i=[];return e.forEach(function(e){i.push(Qo(t).get(e).next(function(t){if(null===t)throw Lr("Dangling document-mutation reference found, which points to "+e);xr(t.userId===n.userId,"Unexpected user '"+t.userId+"' for mutation batch "+e),r.push(n.serializer.fromDbMutationBatch(t))}))}),Lo.waitFor(i).next(function(){return r})},Fo.prototype.removeMutationBatch=function(e,n){var r=this;return Bo(e.simpleDbTransaction,this.userId,n).next(function(t){return r.removeCachedMutationKeys(n.batchId),Lo.forEach(t,function(t){return r.referenceDelegate.removeMutationReference(e,t)})})},Fo.prototype.removeCachedMutationKeys=function(t){delete this.documentKeysByBatchId[t]},Fo.prototype.performConsistencyCheck=function(n){var o=this;return this.checkEmpty(n).next(function(t){if(!t)return Lo.resolve();var e=IDBKeyRange.lowerBound(mu.prefixForUser(o.userId)),i=[];return Ko(n).iterate({range:e},function(t,e,n){if(t[0]===o.userId){var r=no(t[1]);i.push(r)}else n.done()}).next(function(){xr(0===i.length,"Document leak -- detected dangling mutation references when queue is empty. Dangling keys: "+i.map(function(t){return t.canonicalString()}))})})},Fo.prototype.containsKey=function(t,e){return Vo(t,this.userId,e)},Fo.prototype.getMutationQueueMetadata=function(t){var e=this;return jo(t).get(this.userId).next(function(t){return t||new lu(e.userId,-1,"")})},Fo);function Fo(t,e,n,r){this.userId=t,this.serializer=e,this.indexManager=n,this.referenceDelegate=r,this.documentKeysByBatchId={}}function Vo(t,o,e){var n=mu.prefixForPath(o,e.path),a=n[1],r=IDBKeyRange.lowerBound(n),s=!1;return Ko(t).iterate({range:r,keysOnly:!0},function(t,e,n){var r=t[0],i=t[1];t[2];r===o&&i===a&&(s=!0),n.done()}).next(function(){return s})}function Bo(t,e,n){var r=t.store(pu.store),i=t.store(mu.store),o=[],a=IDBKeyRange.only(n.batchId),s=0,u=r.iterate({range:a},function(t,e,n){return s++,n.delete()});o.push(u.next(function(){xr(1===s,"Dangling document-mutation reference found: Missing batch "+n.batchId)}));for(var c=[],h=0,l=n.mutations;h",t),this.store.put(t)))},ra.prototype.add=function(t){return _r(Yo,"ADD",this.store.name,t,t),ia(this.store.add(t))},ra.prototype.get=function(e){var n=this;return ia(this.store.get(e)).next(function(t){return void 0===t&&(t=null),_r(Yo,"GET",n.store.name,e,t),t})},ra.prototype.delete=function(t){return _r(Yo,"DELETE",this.store.name,t),ia(this.store.delete(t))},ra.prototype.count=function(){return _r(Yo,"COUNT",this.store.name),ia(this.store.count())},ra.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})},ra.prototype.deleteAll=function(t,e){_r(Yo,"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()})},ra.prototype.iterate=function(t,e){var n;e?n=t:(n={},e=t);var r=this.cursor(n);return this.iterateCursor(r,e)},ra.prototype.iterateSerial=function(i){var t=this.cursor({});return new Lo(function(n,r){t.onerror=function(t){var e=aa(t.target.error);r(e)},t.onsuccess=function(t){var e=t.target.result;e?i(e.primaryKey,e.value).next(function(t){t?e.continue():n()}):n()}})},ra.prototype.iterateCursor=function(t,a){var s=[];return new Lo(function(o,e){t.onerror=function(t){e(t.target.error)},t.onsuccess=function(t){var e=t.target.result;if(e){var n=new $o(e),r=a(e.primaryKey,e.value,n);if(r instanceof Lo){var i=r.catch(function(t){return n.done(),Lo.reject(t)});s.push(i)}n.isDone?o():null===n.skipToKey?e.continue():e.continue(n.skipToKey)}else o()}}).next(function(){return Lo.waitFor(s)})},ra.prototype.options=function(t,e){var n=void 0;return void 0!==t&&("string"==typeof t?n=t:(xr(void 0===e,"3rd argument must not be defined if 2nd is a range."),e=t)),{index:n,range:e}},ra.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)},ra);function ra(t){this.store=t}function ia(t){return new Lo(function(n,r){t.onsuccess=function(t){var e=t.target.result;n(e)},t.onerror=function(t){var e=aa(t.target.error);r(e)}})}var oa=!1;function aa(t){var e=Xo.getIOSVersion(u());if(12.2<=e&&e<13){var n="An internal error was encountered in the Indexed Database server";if(0<=t.message.indexOf(n)){var r=new Qr("internal","IOS_INDEXEDDB_BUG1: IndexedDb has thrown '"+n+"'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.");return oa||(oa=!0,setTimeout(function(){throw r},0)),r}}return t}var sa=(ua.prototype.allocateTargetId=function(e){var n=this;return this.retrieveMetadata(e).next(function(t){return t.highestTargetId=n.targetIdGenerator.after(t.highestTargetId),n.saveMetadata(e,t).next(function(){return t.highestTargetId})})},ua.prototype.getLastRemoteSnapshotVersion=function(t){return this.retrieveMetadata(t).next(function(t){return oo.fromTimestamp(new ro(t.lastRemoteSnapshotVersion.seconds,t.lastRemoteSnapshotVersion.nanoseconds))})},ua.prototype.getHighestSequenceNumber=function(t){return la(t.simpleDbTransaction)},ua.prototype.setTargetsMetadata=function(e,n,r){var i=this;return this.retrieveMetadata(e).next(function(t){return t.highestListenSequenceNumber=n,r&&(t.lastRemoteSnapshotVersion=r.toTimestamp()),n>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=n),i.saveMetadata(e,t)})},ua.prototype.addQueryData=function(e,n){var r=this;return this.saveQueryData(e,n).next(function(){return r.retrieveMetadata(e).next(function(t){return t.targetCount+=1,r.updateMetadataFromQueryData(n,t),r.saveMetadata(e,t)})})},ua.prototype.updateQueryData=function(t,e){return this.saveQueryData(t,e)},ua.prototype.removeQueryData=function(e,t){var n=this;return this.removeMatchingKeysForTargetId(e,t.targetId).next(function(){return ca(e).delete(t.targetId)}).next(function(){return n.retrieveMetadata(e)}).next(function(t){return xr(0e.highestTargetId&&(e.highestTargetId=t.targetId,n=!0),t.sequenceNumber>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=t.sequenceNumber,n=!0),n},ua.prototype.getQueryCount=function(t){return this.retrieveMetadata(t).next(function(t){return t.targetCount})},ua.prototype.getQueryData=function(t,i){var o=this,e=i.canonicalId(),n=IDBKeyRange.bound([e,Number.NEGATIVE_INFINITY],[e,Number.POSITIVE_INFINITY]),a=null;return ca(t).iterate({range:n,index:Tu.queryTargetsIndexName},function(t,e,n){var r=o.serializer.fromDbTarget(e);i.isEqual(r.query)&&(a=r,n.done())}).next(function(){return a})},ua.prototype.addMatchingKeys=function(n,t,r){var i=this,o=[],a=fa(n);return t.forEach(function(t){var e=Zi(t.path);o.push(a.put(new Cu(r,e))),o.push(i.referenceDelegate.addReference(n,t))}),Lo.waitFor(o)},ua.prototype.removeMatchingKeys=function(n,t,r){var i=this,o=fa(n);return Lo.forEach(t,function(t){var e=Zi(t.path);return Lo.waitFor([o.delete([r,e]),i.referenceDelegate.removeReference(n,t)])})},ua.prototype.removeMatchingKeysForTargetId=function(t,e){var n=fa(t),r=IDBKeyRange.bound([e],[e+1],!1,!0);return n.delete(r)},ua.prototype.getMatchingKeysForTargetId=function(t,e){var n=IDBKeyRange.bound([e],[e+1],!1,!0),r=fa(t),o=Ao();return r.iterate({range:n,keysOnly:!0},function(t,e,n){var r=no(t[1]),i=new Bi(r);o=o.add(i)}).next(function(){return o})},ua.prototype.containsKey=function(t,e){var n=Zi(e.path),r=IDBKeyRange.bound([n],[vi(n)],!1,!0),i=0;return fa(t).iterate({index:Cu.documentTargetsIndex,keysOnly:!0,range:r},function(t,e,n){var r=t[0];t[1],0!==r&&(i++,n.done())}).next(function(){return 0"},ds);function ds(t,e){var n=fs.call(this)||this;return n.localWriteTime=t,n.previousValue=e,n.typeOrder=Pa.TimestampValue,n}var ms,ys=(s(gs,ms=Qa),gs.prototype.value=function(t){return this.internalValue},gs.prototype.isEqual=function(t){return t instanceof gs&&this.internalValue.isEqual(t.internalValue)},gs.prototype.compareTo=function(t){return t instanceof gs?this.internalValue._compareTo(t.internalValue):this.defaultCompareTo(t)},gs);function gs(t){var e=ms.call(this)||this;return e.internalValue=t,e.typeOrder=Pa.BlobValue,e}var vs,bs=(s(ws,vs=Qa),ws.prototype.value=function(t){return this.key},ws.prototype.isEqual=function(t){return t instanceof ws&&this.key.isEqual(t.key)&&this.databaseId.isEqual(t.databaseId)},ws.prototype.compareTo=function(t){if(t instanceof ws){var e=this.databaseId.compareTo(t.databaseId);return 0!==e?e:Bi.comparator(this.key,t.key)}return this.defaultCompareTo(t)},ws);function ws(t,e){var n=vs.call(this)||this;return n.databaseId=t,n.key=e,n.typeOrder=Pa.RefValue,n}var Es,Ss=(s(Ts,Es=Qa),Ts.prototype.value=function(t){return this.internalValue},Ts.prototype.isEqual=function(t){return t instanceof Ts&&this.internalValue.isEqual(t.internalValue)},Ts.prototype.compareTo=function(t){return t instanceof Ts?this.internalValue._compareTo(t.internalValue):this.defaultCompareTo(t)},Ts);function Ts(t){var e=Es.call(this)||this;return e.internalValue=t,e.typeOrder=Pa.GeoPointValue,e}var Is,Cs=(s(Ds,Is=Qa),Ds.prototype.value=function(n){var r={};return this.internalValue.inorderTraversal(function(t,e){r[t]=e.value(n)}),r},Ds.prototype.forEach=function(t){this.internalValue.inorderTraversal(t)},Ds.prototype.isEqual=function(t){if(t instanceof Ds){for(var e=this.internalValue.getIterator(),n=t.internalValue.getIterator();e.hasNext()&&n.hasNext();){var r=e.getNext(),i=n.getNext();if(r.key!==i.key||!r.value.isEqual(i.value))return!1}return!e.hasNext()&&!n.hasNext()}return!1},Ds.prototype.compareTo=function(t){if(t instanceof Ds){for(var e=this.internalValue.getIterator(),n=t.internalValue.getIterator();e.hasNext()&&n.hasNext();){var r=e.getNext(),i=n.getNext(),o=yi(r.key,i.key)||r.value.compareTo(i.value);if(o)return o}return yi(e.hasNext(),n.hasNext())}return this.defaultCompareTo(t)},Ds.prototype.set=function(t,e){if(xr(!t.isEmpty(),"Cannot set field for empty path on ObjectValue"),1===t.length)return this.setChild(t.firstSegment(),e);var n=this.child(t.firstSegment());n instanceof Ds||(n=Ds.EMPTY);var r=n.set(t.popFirst(),e);return this.setChild(t.firstSegment(),r)},Ds.prototype.delete=function(t){if(xr(!t.isEmpty(),"Cannot delete field for empty path on ObjectValue"),1===t.length)return new Ds(this.internalValue.remove(t.firstSegment()));var e=this.child(t.firstSegment());if(e instanceof Ds){var n=e.delete(t.popFirst());return new Ds(this.internalValue.insert(t.firstSegment(),n))}return this},Ds.prototype.contains=function(t){return null!==this.field(t)},Ds.prototype.field=function(t){xr(!t.isEmpty(),"Can't get field of empty path");var e=this;return t.forEach(function(t){e=e instanceof Ds?e.internalValue.get(t):null}),e},Ds.prototype.fieldMask=function(){var i=new yo(Fi.comparator);return this.internalValue.forEach(function(t,e){var n=new Fi([t]);if(e instanceof Ds){var r=e.fieldMask().fields;r.isEmpty()?i=i.add(n):r.forEach(function(t){i=i.add(n.child(t))})}else i=i.add(n)}),pa.fromSet(i)},Ds.prototype.toString=function(){return this.internalValue.toString()},Ds.prototype.child=function(t){return this.internalValue.get(t)||void 0},Ds.prototype.setChild=function(t,e){return new Ds(this.internalValue.insert(t,e))},Ds.EMPTY=new Ds(new so(yi)),Ds);function Ds(t){var e=Is.call(this)||this;return e.internalValue=t,e.typeOrder=Pa.ObjectValue,e}var Ns,As=(s(ks,Ns=Qa),ks.prototype.value=function(e){return this.internalValue.map(function(t){return t.value(e)})},ks.prototype.contains=function(t){for(var e=0,n=this.internalValue;eh.params.maximumSequenceNumbersToCollect?(_r("LruGarbageCollector","Capping sequence numbers to collect down to the maximum of "+h.params.maximumSequenceNumbersToCollect+" from "+t),h.params.maximumSequenceNumbersToCollect):t,a=Date.now(),h.nthSequenceNumber(e,i)}).next(function(t){return r=t,s=Date.now(),h.removeTargets(e,r,n)}).next(function(t){return o=t,u=Date.now(),h.removeOrphanedDocuments(e,r)}).next(function(t){return c=Date.now(),Rr()<=wr.DEBUG&&_r("LruGarbageCollector","LRU Garbage Collection\n\tCounted targets in "+(a-l)+"ms\n\tDetermined least recently used "+i+" in "+(s-a)+"ms\n\tRemoved "+o+" targets in "+(u-s)+"ms\n\tRemoved "+t+" documents in "+(c-u)+"ms\nTotal Duration: "+(c-l)+"ms"),Lo.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:o,documentsRemoved:t})})},ec);function ec(t,e){this.delegate=t,this.params=e}var nc,rc="IndexedDbPersistence",ic="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.",oc="Another tab has exclusive access to the persistence layer. To allow shared access, make sure to invoke `enablePersistence()` with `synchronizeTabs:true` in all tabs.",ac=(s(sc,nc=function(){}),sc);function sc(t,e){var n=nc.call(this)||this;return n.simpleDbTransaction=t,n.currentSequenceNumber=e,n}var uc=(cc.getStore=function(t,e){if(t instanceof ac)return Xo.getStore(t.simpleDbTransaction,e);throw Lr("IndexedDbPersistence must use instances of IndexedDbTransaction")},cc.createIndexedDbPersistence=function(n,r,i,o,a,s){return p(this,void 0,void 0,function(){var e;return d(this,function(t){switch(t.label){case 0:return[4,(e=new cc(n,r,i,o,a,s)).start()];case 1:return t.sent(),[2,e]}})})},cc.createMultiClientIndexedDbPersistence=function(n,r,i,o,a,s,u){return p(this,void 0,void 0,function(){var e;return d(this,function(t){switch(t.label){case 0:return[4,(e=new cc(n,r,i,o,a,s,u)).start()];case 1:return t.sent(),[2,e]}})})},cc.prototype.start=function(){var n=this;return xr(!this.started,"IndexedDbPersistence double-started!"),xr(null!==this.window,"Expected 'window' to be defined"),Xo.openOrCreate(this.dbName,ou,new au(this.serializer)).then(function(t){return n.simpleDb=t,n.updateClientMetadataAndTryBecomePrimary()}).then(function(){return n.attachVisibilityHandler(),n.attachWindowUnloadHook(),n.scheduleClientMetadataAndPrimaryLeaseRefreshes(),n.startRemoteDocumentCache()}).then(function(){return n.simpleDb.runTransaction("readonly",[Nu.store],function(t){return la(t).next(function(t){var e=n.multiClientParams?n.multiClientParams.sequenceNumberSyncer:void 0;n.listenSequence=new Ai(t,e)})})}).then(function(){n._started=!0}).catch(function(t){return n.simpleDb&&n.simpleDb.close(),Promise.reject(t)})},cc.prototype.startRemoteDocumentCache=function(){var e=this;return this.simpleDb.runTransaction("readonly",Fu,function(t){return e.remoteDocumentCache.start(t)})},cc.prototype.setPrimaryStateListener=function(n){var t=this;return this.primaryStateListener=function(e){return p(t,void 0,void 0,function(){return d(this,function(t){return this.started?[2,n(e)]:[2]})})},n(this.isPrimary)},cc.prototype.setDatabaseDeletedListener=function(n){var t=this;this.simpleDb.setVersionChangeListener(function(e){return p(t,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return null!==e.newVersion?[3,2]:[4,n()];case 1:t.sent(),t.label=2;case 2:return[2]}})})})},cc.prototype.setNetworkEnabled=function(t){var e=this;this.networkEnabled!==t&&(this.networkEnabled=t,this.queue.enqueueAndForget(function(){return p(e,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return this.started?[4,this.updateClientMetadataAndTryBecomePrimary()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})})}))},cc.prototype.updateClientMetadataAndTryBecomePrimary=function(){var r=this;return this.simpleDb.runTransaction("readwrite",Fu,function(n){return fc(n).put(new Pu(r.clientId,Date.now(),r.networkEnabled,r.inForeground,r.remoteDocumentCache.lastProcessedDocumentChangeId)).next(function(){if(r.isPrimary)return r.verifyPrimaryLease(n).next(function(t){t||(r.isPrimary=!1,r.queue.enqueueAndForget(function(){return r.primaryStateListener(!1)}))})}).next(function(){return r.canActAsPrimary(n)}).next(function(t){var e=r.isPrimary;return r.isPrimary=t,e!==r.isPrimary&&r.queue.enqueueAndForget(function(){return r.primaryStateListener(r.isPrimary)}),e&&!r.isPrimary?r.releasePrimaryLeaseIfHeld(n):r.isPrimary?r.acquireOrExtendPrimaryLease(n):void 0})})},cc.prototype.verifyPrimaryLease=function(t){var e=this;return lc(t).get(cu.key).next(function(t){return Lo.resolve(e.isLocalClient(t))})},cc.prototype.removeClientMetadata=function(t){return fc(t).delete(this.clientId)},cc.prototype.maybeGarbageCollectMultiClientState=function(){return p(this,void 0,void 0,function(){var r,i,o=this;return d(this,function(t){switch(t.label){case 0:return!this.isPrimary||this.isWithinAge(this.lastGarbageCollectionTime,18e5)?[3,2]:(this.lastGarbageCollectionTime=Date.now(),i=[],[4,this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",function(n){var e=cc.getStore(n,Pu.store);return e.loadAll().next(function(t){r=o.filterActiveClients(t,18e5),i=t.filter(function(t){return-1===r.indexOf(t)})}).next(function(){return Lo.forEach(i,function(t){return e.delete(t.clientId)})}).next(function(){if(0<(r=r.filter(function(t){return t.clientId!==o.clientId})).length){var t=r.map(function(t){return t.lastProcessedDocumentChangeId||0}),e=Math.min.apply(Math,t);return o.remoteDocumentCache.removeDocumentChangesThroughChangeId(n,e)}})})]);case 1:t.sent(),i.forEach(function(t){o.window.localStorage.removeItem(o.zombiedClientLocalStorageKey(t.clientId))}),t.label=2;case 2:return[2]}})})},cc.prototype.scheduleClientMetadataAndPrimaryLeaseRefreshes=function(){var t=this;this.clientMetadataRefresher=this.queue.enqueueAfterDelay(Qi.ClientMetadataRefresh,4e3,function(){return t.updateClientMetadataAndTryBecomePrimary().then(function(){return t.maybeGarbageCollectMultiClientState()}).then(function(){return t.scheduleClientMetadataAndPrimaryLeaseRefreshes()})})},cc.prototype.isLocalClient=function(t){return!!t&&t.ownerId===this.clientId},cc.prototype.canActAsPrimary=function(e){var i=this;return lc(e).get(cu.key).next(function(t){if(null!==t&&i.isWithinAge(t.leaseTimestampMs,5e3)&&!i.isClientZombied(t.ownerId)){if(i.isLocalClient(t)&&i.networkEnabled)return!0;if(!i.isLocalClient(t)){if(!t.allowTabSynchronization)throw new Qr(Ur.FAILED_PRECONDITION,oc);return!1}}return!(!i.networkEnabled||!i.inForeground)||fc(e).loadAll().next(function(t){return void 0===i.filterActiveClients(t,5e3).find(function(t){if(i.clientId!==t.clientId){var e=!i.networkEnabled&&t.networkEnabled,n=!i.inForeground&&t.inForeground,r=i.networkEnabled===t.networkEnabled;if(e||n&&r)return!0}return!1})})}).next(function(t){return i.isPrimary!==t&&_r(rc,"Client "+(t?"is":"is not")+" eligible for a primary lease."),t})},cc.prototype.shutdown=function(){return p(this,void 0,void 0,function(){var e=this;return d(this,function(t){switch(t.label){case 0:return this._started=!1,this.markClientZombied(),this.clientMetadataRefresher&&(this.clientMetadataRefresher.cancel(),this.clientMetadataRefresher=null),this.detachVisibilityHandler(),this.detachWindowUnloadHook(),[4,this.simpleDb.runTransaction("readwrite",[cu.store,Pu.store],function(t){return e.releasePrimaryLeaseIfHeld(t).next(function(){return e.removeClientMetadata(t)})})];case 1:return t.sent(),this.simpleDb.close(),this.removeClientZombiedEntry(),[2]}})})},cc.prototype.filterActiveClients=function(t,e){var n=this;return t.filter(function(t){return n.isWithinAge(t.updateTimeMs,e)&&!n.isClientZombied(t.clientId)})},cc.prototype.getActiveClients=function(){var e=this;return this.simpleDb.runTransaction("readonly",[Pu.store],function(t){return fc(t).loadAll().next(function(t){return e.filterActiveClients(t,18e5).map(function(t){return t.clientId})})})},cc.clearPersistence=function(n){return p(this,void 0,void 0,function(){var e;return d(this,function(t){switch(t.label){case 0:return cc.isAvailable()?(e=n+cc.MAIN_DATABASE,[4,Xo.delete(e)]):[2,Promise.resolve()];case 1:return t.sent(),[2]}})})},Object.defineProperty(cc.prototype,"started",{get:function(){return this._started},enumerable:!0,configurable:!0}),cc.prototype.getMutationQueue=function(t){return xr(this.started,"Cannot initialize MutationQueue before persistence is started."),qo.forUser(t,this.serializer,this.indexManager,this.referenceDelegate)},cc.prototype.getQueryCache=function(){return xr(this.started,"Cannot initialize QueryCache before persistence is started."),this.queryCache},cc.prototype.getRemoteDocumentCache=function(){return xr(this.started,"Cannot initialize RemoteDocumentCache before persistence is started."),this.remoteDocumentCache},cc.prototype.getIndexManager=function(){return xr(this.started,"Cannot initialize IndexManager before persistence is started."),this.indexManager},cc.prototype.runTransaction=function(n,t,r){var i=this;return _r(rc,"Starting transaction:",n),this.simpleDb.runTransaction("readonly"===t?"readonly":"readwrite",Fu,function(e){return"readwrite-primary"===t?i.verifyPrimaryLease(e).next(function(t){if(!t)throw Or("Failed to obtain primary lease for action '"+n+"'."),i.isPrimary=!1,i.queue.enqueueAndForget(function(){return i.primaryStateListener(!1)}),new Qr(Ur.FAILED_PRECONDITION,ic);return r(new ac(e,i.listenSequence.next()))}).next(function(t){return i.acquireOrExtendPrimaryLease(e).next(function(){return t})}):i.verifyAllowTabSynchronization(e).next(function(){return r(new ac(e,i.listenSequence.next()))})})},cc.prototype.verifyAllowTabSynchronization=function(t){var e=this;return lc(t).get(cu.key).next(function(t){if(null!==t&&e.isWithinAge(t.leaseTimestampMs,5e3)&&!e.isClientZombied(t.ownerId)&&!e.isLocalClient(t)&&!t.allowTabSynchronization)throw new Qr(Ur.FAILED_PRECONDITION,oc)})},cc.prototype.acquireOrExtendPrimaryLease=function(t){var e=new cu(this.clientId,this.allowTabSynchronization,Date.now());return lc(t).put(cu.key,e)},cc.isAvailable=function(){return Xo.isAvailable()},cc.buildStoragePrefix=function(t){var e=t.databaseId.projectId;return t.databaseId.isDefaultDatabase||(e+="."+t.databaseId.database),"firestore/"+t.persistenceKey+"/"+e+"/"},cc.prototype.releasePrimaryLeaseIfHeld=function(t){var e=this,n=lc(t);return n.get(cu.key).next(function(t){return e.isLocalClient(t)?(_r(rc,"Releasing primary lease."),n.delete(cu.key)):Lo.resolve()})},cc.prototype.isWithinAge=function(t,e){var n=Date.now();return!(t "+n),1))},cc.prototype.attachVisibilityHandler=function(){var t=this;null!==this.document&&"function"==typeof this.document.addEventListener&&(this.documentVisibilityHandler=function(){t.queue.enqueueAndForget(function(){return t.inForeground="visible"===t.document.visibilityState,t.updateClientMetadataAndTryBecomePrimary()})},this.document.addEventListener("visibilitychange",this.documentVisibilityHandler),this.inForeground="visible"===this.document.visibilityState)},cc.prototype.detachVisibilityHandler=function(){this.documentVisibilityHandler&&(xr(null!==this.document&&"function"==typeof this.document.addEventListener,"Expected 'document.addEventListener' to be a function"),this.document.removeEventListener("visibilitychange",this.documentVisibilityHandler),this.documentVisibilityHandler=null)},cc.prototype.attachWindowUnloadHook=function(){var t=this;"function"==typeof this.window.addEventListener&&(this.windowUnloadHandler=function(){t.markClientZombied(),t.queue.enqueueAndForget(function(){return t.shutdown()})},this.window.addEventListener("unload",this.windowUnloadHandler))},cc.prototype.detachWindowUnloadHook=function(){this.windowUnloadHandler&&(xr("function"==typeof this.window.removeEventListener,"Expected 'window.removeEventListener' to be a function"),this.window.removeEventListener("unload",this.windowUnloadHandler),this.windowUnloadHandler=null)},cc.prototype.isClientZombied=function(t){try{var e=null!==this.webStorage.getItem(this.zombiedClientLocalStorageKey(t));return _r(rc,"Client '"+t+"' "+(e?"is":"is not")+" zombied in LocalStorage"),e}catch(t){return Or(rc,"Failed to get zombied client id.",t),!1}},cc.prototype.markClientZombied=function(){try{this.webStorage.setItem(this.zombiedClientLocalStorageKey(this.clientId),String(Date.now()))}catch(t){Or("Failed to set zombie client id.",t)}},cc.prototype.removeClientZombiedEntry=function(){try{this.webStorage.removeItem(this.zombiedClientLocalStorageKey(this.clientId))}catch(t){}},cc.prototype.zombiedClientLocalStorageKey=function(t){return"firestore_zombie_"+this.persistenceKey+"_"+t},cc.MAIN_DATABASE="main",cc);function cc(t,e,n,r,i,o,a){if(this.persistenceKey=t,this.clientId=e,this.queue=r,this.multiClientParams=a,this._started=!1,this.isPrimary=!1,this.networkEnabled=!0,this.windowUnloadHandler=null,this.inForeground=!1,this.documentVisibilityHandler=null,this.clientMetadataRefresher=null,this.lastGarbageCollectionTime=Number.NEGATIVE_INFINITY,this.primaryStateListener=function(t){return Promise.resolve()},!cc.isAvailable())throw new Qr(Ur.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");if(this.referenceDelegate=new pc(this,o),this.dbName=t+cc.MAIN_DATABASE,this.serializer=new ju(i),this.document=n.document,this.allowTabSynchronization=void 0!==a,this.queryCache=new sa(this.referenceDelegate,this.serializer),this.indexManager=new Vu,this.remoteDocumentCache=new zs(this.serializer,this.indexManager,this.allowTabSynchronization),!n.window||!n.window.localStorage)throw new Qr(Ur.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");this.window=n.window,this.webStorage=this.window.localStorage}function hc(e){return p(this,void 0,void 0,function(){return d(this,function(t){if(!function(t){return t.code===Ur.FAILED_PRECONDITION&&t.message===ic}(e))throw e;return _r(rc,"Unexpectedly lost primary lease"),[2]})})}function lc(t){return t.store(cu.store)}function fc(t){return t.store(Pu.store)}var pc=(dc.prototype.getSequenceNumberCount=function(t){var n=this.orphanedDocmentCount(t);return this.db.getQueryCache().getQueryCount(t).next(function(e){return n.next(function(t){return e+t})})},dc.prototype.orphanedDocmentCount=function(t){var e=0;return this.forEachOrphanedDocumentSequenceNumber(t,function(t){e++}).next(function(){return e})},dc.prototype.forEachTarget=function(t,e){return this.db.getQueryCache().forEachTarget(t,e)},dc.prototype.forEachOrphanedDocumentSequenceNumber=function(t,n){return this.forEachOrphanedDocument(t,function(t,e){return n(e)})},dc.prototype.setInMemoryPins=function(t){this.inMemoryPins=t},dc.prototype.addReference=function(t,e){return mc(t,e)},dc.prototype.removeReference=function(t,e){return mc(t,e)},dc.prototype.removeTargets=function(t,e,n){return this.db.getQueryCache().removeTargets(t,e,n)},dc.prototype.removeMutationReference=function(t,e){return mc(t,e)},dc.prototype.isPinned=function(t,e){return this.inMemoryPins.containsKey(e)?Lo.resolve(!0):function(e,n){var r=!1;return jo(e).iterateSerial(function(t){return Vo(e,t,n).next(function(t){return t&&(r=!0),Lo.resolve(!t)})}).next(function(){return r})}(t,e)},dc.prototype.removeOrphanedDocuments=function(r,i){var o=this,a=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[],u=0;return this.forEachOrphanedDocument(r,function(e,t){if(t<=i){var n=o.isPinned(r,e).next(function(t){if(!t)return u++,a.getEntry(r,e).next(function(){return a.removeEntry(e),fa(r).delete(function(t){return[0,Zi(t.path)]}(e))})});s.push(n)}}).next(function(){return Lo.waitFor(s)}).next(function(){return a.apply(r)}).next(function(){return u})},dc.prototype.removeTarget=function(t,e){var n=e.copy({sequenceNumber:t.currentSequenceNumber});return this.db.getQueryCache().updateQueryData(t,n)},dc.prototype.updateLimboDocument=function(t,e){return mc(t,e)},dc.prototype.forEachOrphanedDocument=function(t,o){var a,e=fa(t),s=Ai.INVALID;return e.iterate({index:Cu.documentTargetsIndex},function(t,e){var n=t[0],r=(t[1],e.path),i=e.sequenceNumber;0===n?(s!==Ai.INVALID&&o(new Bi(no(a)),s),s=i,a=r):s=Ai.INVALID}).next(function(){s!==Ai.INVALID&&o(new Bi(no(a)),s)})},dc.prototype.getCacheSize=function(t){return this.db.getRemoteDocumentCache().getSize(t)},dc);function dc(t,e){this.db=t,this.inMemoryPins=null,this.garbageCollector=new tc(this,e)}function mc(t,e){return fa(t).put(function(t,e){return new Cu(0,Zi(t.path),e)}(e,t.currentSequenceNumber))}var yc=(gc.prototype.getDocument=function(e,n){var r=this;return this.mutationQueue.getAllMutationBatchesAffectingDocumentKey(e,n).next(function(t){return r.getDocumentInternal(e,n,t)})},gc.prototype.getDocumentInternal=function(t,r,i){return this.remoteDocumentCache.getEntry(t,r).next(function(t){for(var e=0,n=i;e=this.RESUME_TOKEN_MAX_AGE_MICROS||0i?this.mutationQueue[i]:null)},Cc.prototype.getHighestUnacknowledgedBatchId=function(){return Lo.resolve(0===this.mutationQueue.length?-1:this.nextBatchId-1)},Cc.prototype.getAllMutationBatches=function(t){return Lo.resolve(this.mutationQueue.slice())},Cc.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,n){var r=this,e=new wc(n,0),i=new wc(n,Number.POSITIVE_INFINITY),o=[];return this.batchesByDocumentKey.forEachInRange([e,i],function(t){xr(n.isEqual(t.key),"Should only iterate over a single key's batches");var e=r.findMutationBatch(t.targetOrBatchId);xr(null!==e,"Batches in the index must exist in the main table"),o.push(e)}),Lo.resolve(o)},Cc.prototype.getAllMutationBatchesAffectingDocumentKeys=function(t,e){var r=this,i=new yo(yi);return e.forEach(function(e){var t=new wc(e,0),n=new wc(e,Number.POSITIVE_INFINITY);r.batchesByDocumentKey.forEachInRange([t,n],function(t){xr(e.isEqual(t.key),"For each key, should only iterate over a single key's batches"),i=i.add(t.targetOrBatchId)})}),Lo.resolve(this.findMutationBatches(i))},Cc.prototype.getAllMutationBatchesAffectingQuery=function(t,e){xr(!e.isCollectionGroupQuery(),"CollectionGroup queries should be handled in LocalDocumentsView");var n=e.path,r=n.length+1,i=n;Bi.isDocumentKey(i)||(i=i.child(""));var o=new wc(new Bi(i),0),a=new yo(yi);return this.batchesByDocumentKey.forEachWhile(function(t){var e=t.key.path;return!!n.isPrefixOf(e)&&(e.length===r&&(a=a.add(t.targetOrBatchId)),!0)},o),Lo.resolve(this.findMutationBatches(a))},Cc.prototype.findMutationBatches=function(t){var n=this,r=[];return t.forEach(function(t){var e=n.findMutationBatch(t);null!==e&&r.push(e)}),r},Cc.prototype.removeMutationBatch=function(n,r){var i=this;xr(0===this.indexOfExistingBatchId(r.batchId,"removed"),"Can only remove the first entry of the mutation queue"),this.mutationQueue.shift();var o=this.batchesByDocumentKey;return Lo.forEach(r.mutations,function(t){var e=new wc(t.key,r.batchId);return o=o.delete(e),i.referenceDelegate.removeMutationReference(n,t.key)}).next(function(){i.batchesByDocumentKey=o})},Cc.prototype.removeCachedMutationKeys=function(t){},Cc.prototype.containsKey=function(t,e){var n=new wc(e,0),r=this.batchesByDocumentKey.firstAfterOrEqual(n);return Lo.resolve(e.isEqual(r&&r.key))},Cc.prototype.performConsistencyCheck=function(t){return 0===this.mutationQueue.length&&xr(this.batchesByDocumentKey.isEmpty(),"Document leak -- detected dangling mutation references when queue is empty."),Lo.resolve()},Cc.prototype.indexOfExistingBatchId=function(t,e){var n=this.indexOfBatchId(t);return xr(0<=n&&n=this.mutationQueue.length)return null;var n=this.mutationQueue[e];return xr(n.batchId===t,"If found batch must match"),n},Cc);function Cc(t,e){this.indexManager=t,this.referenceDelegate=e,this.mutationQueue=[],this.nextBatchId=1,this.lastStreamToken=Vr(),this.batchesByDocumentKey=new yo(wc.compareByKey)}var Dc=(Nc.prototype.getTargetCount=function(t){return Lo.resolve(this.targetCount)},Nc.prototype.forEachTarget=function(t,n){return this.queries.forEach(function(t,e){return n(e)}),Lo.resolve()},Nc.prototype.getLastRemoteSnapshotVersion=function(t){return Lo.resolve(this.lastRemoteSnapshotVersion)},Nc.prototype.getHighestSequenceNumber=function(t){return Lo.resolve(this.highestSequenceNumber)},Nc.prototype.allocateTargetId=function(t){var e=this.targetIdGenerator.after(this.highestTargetId);return this.highestTargetId=e,Lo.resolve(e)},Nc.prototype.setTargetsMetadata=function(t,e,n){return n&&(this.lastRemoteSnapshotVersion=n),e>this.highestSequenceNumber&&(this.highestSequenceNumber=e),Lo.resolve()},Nc.prototype.saveQueryData=function(t){this.queries.set(t.query,t);var e=t.targetId;e>this.highestTargetId&&(this.highestTargetId=e),t.sequenceNumber>this.highestSequenceNumber&&(this.highestSequenceNumber=t.sequenceNumber)},Nc.prototype.addQueryData=function(t,e){return xr(!this.queries.has(e.query),"Adding a query that already exists"),this.saveQueryData(e),this.targetCount+=1,Lo.resolve()},Nc.prototype.updateQueryData=function(t,e){return xr(this.queries.has(e.query),"Updating a non-existent query"),this.saveQueryData(e),Lo.resolve()},Nc.prototype.removeQueryData=function(t,e){return xr(0this.maxDelayMs&&(this.currentBaseMs=this.maxDelayMs)},Gc.prototype.cancel=function(){null!==this.timerPromise&&(this.timerPromise.cancel(),this.timerPromise=null)},Gc.prototype.jitterDelayMs=function(){return(Math.random()-.5)*this.currentBaseMs},Gc);function Gc(t,e,n,r,i){void 0===n&&(n=1e3),void 0===r&&(r=1.5),void 0===i&&(i=6e4),this.queue=t,this.timerId=e,this.initialDelayMs=n,this.backoffFactor=r,this.maxDelayMs=i,this.currentBaseMs=0,this.timerPromise=null,this.lastAttemptTime=Date.now(),this.reset()}var zc,Hc,Yc="PersistentStream";(Hc=zc=zc||{})[Hc.Initial=0]="Initial",Hc[Hc.Starting=1]="Starting",Hc[Hc.Open=2]="Open",Hc[Hc.Error=3]="Error",Hc[Hc.Backoff=4]="Backoff";var Xc=(Jc.prototype.isStarted=function(){return this.state===zc.Starting||this.state===zc.Open||this.state===zc.Backoff},Jc.prototype.isOpen=function(){return this.state===zc.Open},Jc.prototype.start=function(){this.state!==zc.Error?(xr(this.state===zc.Initial,"Already started"),this.auth()):this.performBackoff()},Jc.prototype.stop=function(){return p(this,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return this.isStarted()?[4,this.close(zc.Initial)]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})})},Jc.prototype.inhibitBackoff=function(){xr(!this.isStarted(),"Can only inhibit backoff in a stopped state"),this.state=zc.Initial,this.backoff.reset()},Jc.prototype.markIdle=function(){var t=this;this.isOpen()&&null===this.idleTimer&&(this.idleTimer=this.queue.enqueueAfterDelay(this.idleTimerId,6e4,function(){return t.handleIdleCloseTimer()}))},Jc.prototype.sendRequest=function(t){this.cancelIdleCheck(),this.stream.send(t)},Jc.prototype.handleIdleCloseTimer=function(){return p(this,void 0,void 0,function(){return d(this,function(t){return this.isOpen()?[2,this.close(zc.Initial)]:[2]})})},Jc.prototype.cancelIdleCheck=function(){this.idleTimer&&(this.idleTimer.cancel(),this.idleTimer=null)},Jc.prototype.close=function(e,n){return p(this,void 0,void 0,function(){return d(this,function(t){switch(t.label){case 0:return xr(this.isStarted(),"Only started streams should be closed."),xr(e===zc.Error||Kc(n),"Can't provide an error when not in an error state."),this.cancelIdleCheck(),this.backoff.cancel(),this.closeCount++,e!==zc.Error?this.backoff.reset():n&&n.code===Ur.RESOURCE_EXHAUSTED?(Or(n.toString()),Or("Using maximum backoff delay to prevent overloading the backend."),this.backoff.resetToMax()):n&&n.code===Ur.UNAUTHENTICATED&&this.credentialsProvider.invalidateToken(),null!==this.stream&&(this.tearDown(),this.stream.close(),this.stream=null),this.state=e,[4,this.listener.onClose(n)];case 1:return t.sent(),[2]}})})},Jc.prototype.tearDown=function(){},Jc.prototype.auth=function(){var n=this;xr(this.state===zc.Initial,"Must be in initial state to auth"),this.state=zc.Starting;var t=this.getCloseGuardedDispatcher(this.closeCount),e=this.closeCount;this.credentialsProvider.getToken().then(function(t){n.closeCount===e&&n.startStream(t)},function(e){t(function(){var t=new Qr(Ur.UNKNOWN,"Fetching auth token failed: "+e.message);return n.handleStreamClose(t)})})},Jc.prototype.startStream=function(t){var e=this;xr(this.state===zc.Starting,"Trying to start stream in a non-starting state");var n=this.getCloseGuardedDispatcher(this.closeCount);this.stream=this.startRpc(t),this.stream.onOpen(function(){n(function(){return xr(e.state===zc.Starting,"Expected stream to be in state Starting, but was "+e.state),e.state=zc.Open,e.listener.onOpen()})}),this.stream.onClose(function(t){n(function(){return e.handleStreamClose(t)})}),this.stream.onMessage(function(t){n(function(){return e.onMessage(t)})})},Jc.prototype.performBackoff=function(){var t=this;xr(this.state===zc.Error,"Should only perform backoff when in Error state"),this.state=zc.Backoff,this.backoff.backoffAndRun(function(){return p(t,void 0,void 0,function(){return d(this,function(t){return xr(this.state===zc.Backoff,"Backoff elapsed but state is now: "+this.state),this.state=zc.Initial,this.start(),xr(this.isStarted(),"PersistentStream should have started"),[2]})})})},Jc.prototype.handleStreamClose=function(t){return xr(this.isStarted(),"Can't handle server close on non-started stream"),_r(Yc,"close with error: "+t),this.stream=null,this.close(zc.Error,t)},Jc.prototype.getCloseGuardedDispatcher=function(e){var n=this;return function(t){n.queue.enqueueAndForget(function(){return n.closeCount===e?t():(_r(Yc,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())})}},Jc);function Jc(t,e,n,r,i,o){this.queue=t,this.idleTimerId=n,this.connection=r,this.credentialsProvider=i,this.listener=o,this.state=zc.Initial,this.closeCount=0,this.idleTimer=null,this.stream=null,this.backoff=new Wc(t,e)}var $c,Zc=(s(th,$c=Xc),th.prototype.startRpc=function(t){return this.connection.openStream("Listen",t)},th.prototype.onMessage=function(t){this.backoff.reset();var e=this.serializer.fromWatchChange(t),n=this.serializer.versionFromListenResponse(t);return this.listener.onWatchChange(e,n)},th.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)},th.prototype.unwatch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.removeTarget=t,this.sendRequest(e)},th);function th(t,e,n,r,i){var o=$c.call(this,t,Qi.ListenStreamConnectionBackoff,Qi.ListenStreamIdle,e,n,i)||this;return o.serializer=r,o}var eh,nh=(s(rh,eh=Xc),Object.defineProperty(rh.prototype,"handshakeComplete",{get:function(){return this.handshakeComplete_},enumerable:!0,configurable:!0}),rh.prototype.start=function(){this.handshakeComplete_=!1,eh.prototype.start.call(this)},rh.prototype.tearDown=function(){this.handshakeComplete_&&this.writeMutations([])},rh.prototype.startRpc=function(t){return this.connection.openStream("Write",t)},rh.prototype.onMessage=function(t){if(xr(!!t.streamToken,"Got a write response without a stream token"),this.lastStreamToken=t.streamToken,this.handshakeComplete_){this.backoff.reset();var e=this.serializer.fromWriteResults(t.writeResults,t.commitTime),n=this.serializer.fromVersion(t.commitTime);return this.listener.onMutationResult(n,e)}return xr(!t.writeResults||0===t.writeResults.length,"Got mutation results for handshake"),this.handshakeComplete_=!0,this.listener.onHandshakeComplete()},rh.prototype.writeHandshake=function(){xr(this.isOpen(),"Writing handshake requires an opened stream"),xr(!this.handshakeComplete_,"Handshake already completed");var t={};t.database=this.serializer.encodedDatabaseId,this.sendRequest(t)},rh.prototype.writeMutations=function(t){var e=this;xr(this.isOpen(),"Writing mutations requires an opened stream"),xr(this.handshakeComplete_,"Handshake must be complete before writing mutations"),xr(0=":return $h.GREATER_THAN_OR_EQUAL;case">":return $h.GREATER_THAN;case"array-contains":return $h.ARRAY_CONTAINS;case"in":return $h.IN;case"array-contains-any":return $h.ARRAY_CONTAINS_ANY;default:return Lr("Unknown FieldFilter operator: "+t)}},$h.prototype.toString=function(){return this.name},$h.prototype.isEqual=function(t){return this.name===t.name},$h.LESS_THAN=new $h("<"),$h.LESS_THAN_OR_EQUAL=new $h("<="),$h.EQUAL=new $h("=="),$h.GREATER_THAN=new $h(">"),$h.GREATER_THAN_OR_EQUAL=new $h(">="),$h.ARRAY_CONTAINS=new $h("array-contains"),$h.IN=new $h("in"),$h.ARRAY_CONTAINS_ANY=new $h("array-contains-any"),$h);function $h(t){this.name=t}var Zh,tl=(s(el,Zh=Xh),el.create=function(t,e,n){if(t.isKeyField())return e===Jh.IN?(xr(n instanceof As,"Comparing on key with IN, but filter value not an ArrayValue"),xr(n.internalValue.every(function(t){return t instanceof bs}),"Comparing on key with IN, but an array value was not a RefValue"),new al(t,n)):(xr(n instanceof bs,"Comparing on key, but filter value not a RefValue"),xr(e!==Jh.ARRAY_CONTAINS&&e!==Jh.ARRAY_CONTAINS_ANY,"'"+e.toString()+"' queries don't make sense on document keys."),new rl(t,e,n));if(n.isEqual(Wa.INSTANCE)){if(e!==Jh.EQUAL)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. Null supports only equality comparisons.");return new el(t,e,n)}if(n.isEqual(is.NAN)){if(e!==Jh.EQUAL)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. NaN supports only equality comparisons.");return new el(t,e,n)}return e===Jh.ARRAY_CONTAINS?new cl(t,n):e===Jh.IN?(xr(n instanceof As,"IN filter has invalid value: "+n.toString()),new fl(t,n)):e===Jh.ARRAY_CONTAINS_ANY?(xr(n instanceof As,"ARRAY_CONTAINS_ANY filter has invalid value: "+n.toString()),new ml(t,n)):new el(t,e,n)},el.prototype.matches=function(t){var e=t.field(this.field);return null!==e&&this.value.typeOrder===e.typeOrder&&this.matchesComparison(e.compareTo(this.value))},el.prototype.matchesComparison=function(t){switch(this.op){case Jh.LESS_THAN:return t<0;case Jh.LESS_THAN_OR_EQUAL:return t<=0;case Jh.EQUAL:return 0===t;case Jh.GREATER_THAN:return 0() instead."),mp=/^__.*__$/,yp=(gp.prototype.toMutations=function(t,e){var n=[];return null!==this.fieldMask?n.push(new Aa(t,this.data,this.fieldMask,e)):n.push(new Ca(t,this.data,e)),0=",">","array-contains"],2,e);var r,i=Rp("Query.where",t),o=Jh.fromString(e);if(i.isKeyField()){if(o===Jh.ARRAY_CONTAINS||o===Jh.ARRAY_CONTAINS_ANY)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid Query. You can't perform '"+o.toString()+"' queries on FieldPath.documentId().");if(o===Jh.IN){this.validateDisjunctiveFilterElements(n,o);for(var a=[],s=0,u=n;sr.length)throw new Qr(Ur.INVALID_ARGUMENT,"Too many arguments provided to "+t+"(). The number of arguments must be less than or equal to the number of Query.orderBy() clauses");for(var i=[],o=0;o, or >=) must be on the same field. But you have inequality filters on '"+o.toString()+"' and '"+t.field.toString()+"'");var a=this._query.getFirstOrderByField();null!==a&&this.validateOrderByAndInequalityMatch(t.field,a)}else if(i||r){var s=null;if(i&&(s=this._query.findFilterOperator(n)),null===s&&r&&(s=this._query.findFilterOperator(e)),null!=s)throw s===t.op?new Qr(Ur.INVALID_ARGUMENT,"Invalid query. You cannot use more than one '"+t.op.toString()+"' filter."):new Qr(Ur.INVALID_ARGUMENT,"Invalid query. You cannot use '"+t.op.toString()+"' filters with '"+s.toString()+"' filters.")}}},$p.prototype.validateNewOrderBy=function(t){if(null===this._query.getFirstOrderByField()){var e=this._query.getInequalityFilterField();null!==e&&this.validateOrderByAndInequalityMatch(e,t.field)}},$p.prototype.validateOrderByAndInequalityMatch=function(t,e){if(!e.isEqual(t))throw new Qr(Ur.INVALID_ARGUMENT,"Invalid query. You have a where filter with an inequality (<, <=, >, or >=) on field '"+t.toString()+"' and so you must also use '"+t.toString()+"' as your first Query.orderBy(), but your first Query.orderBy() is on field '"+e.toString()+"' instead.")},$p);function $p(t,e){this._query=t,this.firestore=e}var Zp=(Object.defineProperty(td.prototype,"docs",{get:function(){var e=[];return this.forEach(function(t){return e.push(t)}),e},enumerable:!0,configurable:!0}),Object.defineProperty(td.prototype,"empty",{get:function(){return this._snapshot.docs.isEmpty()},enumerable:!0,configurable:!0}),Object.defineProperty(td.prototype,"size",{get:function(){return this._snapshot.docs.size},enumerable:!0,configurable:!0}),td.prototype.forEach=function(e,n){var r=this;Zr("QuerySnapshot.forEach",arguments,1,2),ti("QuerySnapshot.forEach","function",1,e),this._snapshot.docs.forEach(function(t){e.call(n,r.convertToDocumentImpl(t))})},Object.defineProperty(td.prototype,"query",{get:function(){return new Jp(this._originalQuery,this._firestore)},enumerable:!0,configurable:!0}),td.prototype.docChanges=function(t){t&&(hi("QuerySnapshot.docChanges",t,["includeMetadataChanges"]),ri("QuerySnapshot.docChanges","boolean","includeMetadataChanges",t.includeMetadataChanges));var e=!(!t||!t.includeMetadataChanges);if(e&&this._snapshot.excludesMetadataChanges)throw new Qr(Ur.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===e||(this._cachedChanges=function(i,e,o){if(o.oldDocs.isEmpty()){var n,r=0;return o.docChanges.map(function(t){var e=new Yp(i,t.doc.key,t.doc,o.fromCache,o.mutatedKeys.has(t.doc.key));return xr(t.type===vh.Added,"Invalid event type for first snapshot"),xr(!n||o.query.docComparator(n,t.doc)<0,"Got added events in wrong order"),n=t.doc,{type:"added",doc:e,oldIndex:-1,newIndex:r++}})}var a=o.oldDocs;return o.docChanges.filter(function(t){return e||t.type!==vh.Metadata}).map(function(t){var e=new Yp(i,t.doc.key,t.doc,o.fromCache,o.mutatedKeys.has(t.doc.key)),n=-1,r=-1;return t.type!==vh.Added&&(xr(0<=(n=a.indexOf(t.doc.key)),"Index for document not found"),a=a.delete(t.doc.key)),t.type!==vh.Removed&&(r=(a=a.add(t.doc)).indexOf(t.doc.key)),{type:function(t){switch(t){case vh.Added:return"added";case vh.Modified:case vh.Metadata:return"modified";case vh.Removed:return"removed";default:return Lr("Unknown change type: "+t)}}(t.type),doc:e,oldIndex:n,newIndex:r}})}(this._firestore,e,this._snapshot),this._cachedChangesIncludeMetadataChanges=e),this._cachedChanges},td.prototype.isEqual=function(t){if(!(t instanceof td))throw li("isEqual","QuerySnapshot",1,t);return this._firestore===t._firestore&&this._originalQuery.isEqual(t._originalQuery)&&this._snapshot.isEqual(t._snapshot)},td.prototype.convertToDocumentImpl=function(t){return new Yp(this._firestore,t.key,t,this.metadata.fromCache,this._snapshot.mutatedKeys.has(t.key))},td);function td(t,e,n){this._firestore=t,this._originalQuery=e,this._snapshot=n,this._cachedChanges=null,this._cachedChangesIncludeMetadataChanges=null,this.metadata=new jp(n.hasPendingWrites,n.fromCache)}["length","forEach","map"].concat("undefined"!=typeof Symbol?[Symbol.iterator]:[]).forEach(function(t){try{Object.defineProperty(Zp.prototype.docChanges,t,{get:function(){return function(){throw new Qr(Ur.INVALID_ARGUMENT,'QuerySnapshot.docChanges has been changed from a property into a method, so usages like "querySnapshot.docChanges" should become "querySnapshot.docChanges()"')}()}})}catch(t){}});var ed,nd=(s(rd,ed=Jp),Object.defineProperty(rd.prototype,"id",{get:function(){return this._query.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(rd.prototype,"parent",{get:function(){var t=this._query.path.popLast();return t.isEmpty()?null:new Qp(new Bi(t),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(rd.prototype,"path",{get:function(){return this._query.path.canonicalString()},enumerable:!0,configurable:!0}),rd.prototype.doc=function(t){if(Zr("CollectionReference.doc",arguments,0,1),0===arguments.length&&(t=di.newId()),ti("CollectionReference.doc","non-empty string",1,t),""===t)throw new Qr(Ur.INVALID_ARGUMENT,"Document path must be a non-empty string");var e=Pi.fromString(t);return Qp.forPath(this._query.path.child(e),this.firestore)},rd.prototype.add=function(t){Jr("CollectionReference.add",arguments,1),ti("CollectionReference.add","object",1,t);var e=this.doc();return e.set(t).then(function(){return e})},rd);function rd(t,e){var n=ed.call(this,Hh.atPath(t),e)||this;if(t.length%2!=1)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but "+t.canonicalString()+" has "+t.length);return n}function id(t,e){if(void 0===e)return{merge:!1};if(hi(t,e,["merge","mergeFields"]),ri(t,"boolean","merge",e.merge),ii(t,"mergeFields","a string or a FieldPath",e.mergeFields,function(t){return"string"==typeof t||t instanceof Ff}),void 0!==e.mergeFields&&void 0!==e.merge)throw new Qr(Ur.INVALID_ARGUMENT,"Invalid options passed to function "+t+'(): You cannot specify both "merge" and "mergeFields".');return e}function od(t,e){return void 0===e?{}:(hi(t,e,["serverTimestamps"]),oi(t,0,"serverTimestamps",e.serverTimestamps,["estimate","previous","none"]),e)}function ad(t,e){ei(t,"object",1,e),e&&(hi(t,e,["source"]),oi(t,0,"source",e.source,["default","server","cache"]))}function sd(t,e,n){if(e instanceof Qp){if(e.firestore!==n)throw new Qr(Ur.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}throw li(t,"DocumentReference",1,e)}var ud=jr(xp,"Use firebase.firestore() instead."),cd=jr(Fp,"Use firebase.firestore().runTransaction() instead."),hd=jr(Bp,"Use firebase.firestore().batch() instead."),ld=jr(Qp,"Use firebase.firestore().doc() instead."),fd=jr(Gp),pd=jr(Yp),dd=jr(Jp),md=jr(Zp),yd=jr(nd,"Use firebase.firestore().collection() instead."),gd={Firestore:ud,GeoPoint:Gh,Timestamp:ro,Blob:Ti,Transaction:cd,WriteBatch:hd,DocumentReference:ld,DocumentSnapshot:fd,Query:dd,QueryDocumentSnapshot:pd,QuerySnapshot:md,CollectionReference:yd,FieldPath:Ff,FieldValue:dp,setLogLevel:xp.setLogLevel,CACHE_SIZE_UNLIMITED:Op};function vd(t){t.INTERNAL.registerService("firestore",function(t){return new xp(t)},function(t){xr(t&&"object"==typeof t,"shallowCopy() expects object parameter.");var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}(gd))}var bd=(wd.prototype.addCallback=function(t){},wd.prototype.shutdown=function(){},wd);function wd(){}var Ed="ConnectivityMonitor",Sd=(Td.prototype.addCallback=function(t){this.callbacks.push(t)},Td.prototype.shutdown=function(){window.removeEventListener("online",this.networkAvailableListener),window.removeEventListener("offline",this.networkUnavailableListener)},Td.prototype.configureNetworkMonitoring=function(){window.addEventListener("online",this.networkAvailableListener),window.addEventListener("offline",this.networkUnavailableListener)},Td.prototype.onNetworkAvailable=function(){_r(Ed,"Network connectivity changed: AVAILABLE");for(var t=0,e=this.callbacks;t