From f4f22ddd4605dd6e9fd4ded680d481ee54593229 Mon Sep 17 00:00:00 2001 From: thierrymichel Date: Thu, 11 Jul 2024 10:34:04 +0000 Subject: [PATCH] Deploy website [ci skip] --- docs/getstarted/intro/index.html | 2 +- examples/index.html | 20 ++++++++++---------- js/main.js | 4 ++-- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/getstarted/intro/index.html b/docs/getstarted/intro/index.html index 9c4356b9..be624ef4 100644 --- a/docs/getstarted/intro/index.html +++ b/docs/getstarted/intro/index.html @@ -553,7 +553,7 @@

-

barba.js [v2]

Stability CircleCI Coverage Status Commitizen friendly Conventional Commits License Slack workspace

+

barba.js [v2]

Stability CircleCI Coverage Status Commitizen friendly Conventional Commits lerna License Slack workspace

@@ -336,7 +336,7 @@

Sync sliding

- +

Sync sliding

  • - -

    Once upon a router

    +
    +

    Sync sliding

    - Barba.js example 02 + Barba.js example 01
  • `debug` for the most verbose logging level, primarily for\n * debugging.
  • \n *
  • `error` to log errors only.
  • \n *
  • `silent` to turn off logging.
  • \n * \n */function l(e){for(var r=[],i=1;it.length&&y(),void 0===n?n=t.length-e:n>t.length-e&&y(),this.segments=t,this.offset=e,this.t=n;}return Object.defineProperty(t.prototype,\"length\",{get:function(){return this.t;},enumerable:!1,configurable:!0}),t.prototype.isEqual=function(e){return 0===t.i(this,e);},t.prototype.child=function(e){var n=this.segments.slice(this.offset,this.limit());return e instanceof t?e.forEach(function(t){n.push(t);}):n.push(e),this.o(n);},/** The index of one past the last segment of the path. */t.prototype.limit=function(){return this.offset+this.length;},t.prototype.u=function(t){return t=void 0===t?1:t,this.o(this.segments,this.offset+t,this.length-t);},t.prototype.h=function(){return this.o(this.segments,this.offset,this.length-1);},t.prototype.l=function(){return this.segments[this.offset];},t.prototype._=function(){return this.get(this.length-1);},t.prototype.get=function(t){return this.segments[this.offset+t];},t.prototype.m=function(){return 0===this.length;},t.prototype.T=function(t){if(t.lengtho)return 1;}return t.lengthe.length?1:0;},t;}(),E=/** @class */function(e){function n(){return null!==e&&e.apply(this,arguments)||this;}return t.__extends(n,e),n.prototype.o=function(t,e,r){return new n(t,e,r);},n.prototype.R=function(){// NOTE: The client is ignorant of any path segments containing escape\n// sequences (e.g. __id123__) and just passes them through raw (they exist\n// for legacy reasons and should not be used frequently).\nreturn this.A().join(\"/\");},n.prototype.toString=function(){return this.R();},/**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */n.g=function(){for(var t=[],e=0;e=0)throw new c(a.INVALID_ARGUMENT,\"Invalid segment (\"+s+\"). Paths must not contain // in them.\");// Strip leading and traling slashed.\nr.push.apply(r,s.split(\"/\").filter(function(t){return t.length>0;}));}return new n(r);},n.P=function(){return new n([]);},n;}(I),T=/^[_a-zA-Z][_a-zA-Z0-9]*$/,N=/** @class */function(e){function n(){return null!==e&&e.apply(this,arguments)||this;}return t.__extends(n,e),n.prototype.o=function(t,e,r){return new n(t,e,r);},/**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */n.V=function(t){return T.test(t);},n.prototype.R=function(){return this.A().map(function(t){return t=t.replace(\"\\\\\",\"\\\\\\\\\").replace(\"`\",\"\\\\`\"),n.V(t)||(t=\"`\"+t+\"`\"),t;}).join(\".\");},n.prototype.toString=function(){return this.R();},/**\n * Returns true if this field references the key of a document.\n */n.prototype.p=function(){return 1===this.length&&\"__name__\"===this.get(0);},/**\n * The field designating the key of a document.\n */n.v=function(){return new n([\"__name__\"]);},/**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */n.S=function(t){for(var e=[],r=\"\",i=0,o=function(){if(0===r.length)throw new c(a.INVALID_ARGUMENT,\"Invalid field path (\"+t+\"). Paths must not be empty, begin with '.', end with '.', or contain '..'\");e.push(r),r=\"\";},s=!1;i=2&&this.path.get(this.path.length-2)===t;},t.prototype.isEqual=function(t){return null!==t&&0===E.i(this.path,t.path);},t.prototype.toString=function(){return this.path.toString();},t.i=function(t,e){return E.i(t.path,e.path);},t.F=function(t){return t.length%2==0;},/**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments The segments of the path to the document\n * @return A new instance of DocumentKey\n */t.$=function(e){return new t(new E(e.slice()));},t;}();/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n */ /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * Validates that no arguments were passed in the invocation of functionName.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateNoArgs('myFunction', arguments);\n */function S(t,e){if(0!==e.length)throw new c(a.INVALID_ARGUMENT,\"Function \"+t+\"() does not support arguments, but was called with \"+W(e.length,\"argument\")+\".\");}/**\n * Validates the invocation of functionName has the exact number of arguments.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateExactNumberOfArgs('myFunction', arguments, 2);\n */function D(t,e,n){if(e.length!==n)throw new c(a.INVALID_ARGUMENT,\"Function \"+t+\"() requires \"+W(n,\"argument\")+\", but was called with \"+W(e.length,\"argument\")+\".\");}/**\n * Validates the invocation of functionName has at least the provided number of\n * arguments (but can have many more).\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateAtLeastNumberOfArgs('myFunction', arguments, 2);\n */function x(t,e,n){if(e.lengthr)throw new c(a.INVALID_ARGUMENT,\"Function \"+t+\"() requires between \"+n+\" and \"+r+\" arguments, but was called with \"+W(e.length,\"argument\")+\".\");}/**\n * Validates the provided argument is an array and has as least the expected\n * number of elements.\n */ /**\n * Validates the provided positional argument has the native JavaScript type\n * using typeof checks.\n */function k(t,e,n,r){C(t,e,B(n)+\" argument\",r);}/**\n * Validates the provided argument has the native JavaScript type using\n * typeof checks or is undefined.\n */function R(t,e,n,r){void 0!==r&&k(t,e,n,r);}/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks.\n */function O(t,e,n,r){C(t,e,n+\" option\",r);}/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks or is undefined.\n */function P(t,e,n,r){void 0!==r&&O(t,e,n,r);}/**\n * Validates that two boolean options are not set at the same time.\n */ /**\n * Validates that the provided named option equals one of the expected values.\n */ /**\n * Validates that the provided named option equals one of the expected values or\n * is undefined.\n */function V(t,e,n,r,i){void 0!==r&&function(t,e,n,r,i){for(var o=[],s=0,u=i;s20&&(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=/** Hacky method to try to get the constructor name for an object. */function(t){if(t.constructor){var e=/function\\s+([^\\s(]+)\\s*\\(/.exec(t.constructor.toString());if(e&&e.length>1)return e[1];}return null;}(t);return e?\"a custom \"+e+\" object\":\"an object\";}return\"function\"==typeof t?\"a function\":y();}function q(t,e,n){if(void 0===n)throw new c(a.INVALID_ARGUMENT,\"Function \"+t+\"() requires a valid \"+B(e)+\" argument, but it was undefined.\");}/**\n * Validates the provided positional argument is an object, and its keys and\n * values match the expected keys and types provided in optionTypes.\n */function j(t,e,n){_(e,function(e,r){if(n.indexOf(e)<0)throw new c(a.INVALID_ARGUMENT,\"Unknown option '\"+e+\"' passed to function \"+t+\"(). Available options: \"+n.join(\", \"));});}/**\n * Helper method to throw an error that the provided argument did not pass\n * an instanceof check.\n */function G(t,e,n,r){var i=M(r);return new c(a.INVALID_ARGUMENT,\"Function \"+t+\"() requires its \"+B(n)+\" argument to be a \"+e+\", but it was: \"+i);}function z(t,e,n){if(n<=0)throw new c(a.INVALID_ARGUMENT,\"Function \"+t+\"() requires its \"+B(e)+\" argument to be a positive number, but it was: \"+n+\".\");}/** Converts a number to its english word representation */function B(t){switch(t){case 1:return\"first\";case 2:return\"second\";case 3:return\"third\";default:return t+\"th\";}}/**\n * Formats the given word as plural conditionally given the preceding number.\n */function W(t,e){return t+\" \"+e+(1===t?\"\":\"s\");}/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */function K(t){// Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\nvar e=// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\"undefined\"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(t);if(e&&\"function\"==typeof e.getRandomValues)e.getRandomValues(n);else// Falls back to Math.random\nfor(var r=0;re?1:0;}/** Helper to compare arrays using isEqual(). */function Y(t,e,n){return t.length===e.length&&t.every(function(t,r){return n(t,e[r]);});}/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */function $(t){// Return the input string, with an additional NUL byte appended.\nreturn t+\"\\0\";}/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n */var X=/** @class */function(){function t(t){this.M=t;}return t.fromBase64String=function(e){return new t(atob(e));},t.fromUint8Array=function(e){return new t(/**\n * Helper function to convert an Uint8array to a binary string.\n */function(t){for(var e=\"\",n=0;n value pair. Due to the possibility of\n * collisions we keep a list of entries that we do a linear search through\n * to find an actual match. Note that collisions should be rare, so we still\n * expect near constant time lookups in practice.\n */this.H={}/** Get a value for this key, or undefined if it does not exist. */;}return t.prototype.get=function(t){var e=this.K(t),n=this.H[e];if(void 0!==n)for(var r=0,i=n;r=1e9)throw new c(a.INVALID_ARGUMENT,\"Timestamp nanoseconds out of range: \"+e);if(t<-62135596800)throw new c(a.INVALID_ARGUMENT,\"Timestamp seconds out of range: \"+t);// This will break in the year 10,000.\nif(t>=253402300800)throw new c(a.INVALID_ARGUMENT,\"Timestamp seconds out of range: \"+t);}/**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @return a new timestamp representing the current date.\n */return t.now=function(){return t.fromMillis(Date.now());},/**\n * Creates a new timestamp from the given date.\n *\n * @param date The date to initialize the `Timestamp` from.\n * @return A new `Timestamp` representing the same point in time as the given\n * date.\n */t.fromDate=function(e){return t.fromMillis(e.getTime());},/**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @return A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */t.fromMillis=function(e){var n=Math.floor(e/1e3);return new t(n,1e6*(e-1e3*n));},/**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion causes\n * a loss of precision since `Date` objects only support millisecond precision.\n *\n * @return JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */t.prototype.toDate=function(){return new Date(this.toMillis());},/**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @return The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */t.prototype.toMillis=function(){return 1e3*this.seconds+this.nanoseconds/1e6;},t.prototype.Y=function(t){return this.seconds===t.seconds?H(this.nanoseconds,t.nanoseconds):H(this.seconds,t.seconds);},/**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other The `Timestamp` to compare against.\n * @return true if this `Timestamp` is equal to the provided one.\n */t.prototype.isEqual=function(t){return t.seconds===this.seconds&&t.nanoseconds===this.nanoseconds;},t.prototype.toString=function(){return\"Timestamp(seconds=\"+this.seconds+\", nanoseconds=\"+this.nanoseconds+\")\";},t.prototype.toJSON=function(){return{seconds:this.seconds,nanoseconds:this.nanoseconds};},/**\n * Converts this object to a primitive string, which allows Timestamp objects to be compared\n * using the `>`, `<=`, `>=` and `>` operators.\n */t.prototype.valueOf=function(){// This method returns a string of the form . where is\n// translated to have a non-negative value and both and are left-padded\n// with zeroes to be a consistent length. Strings with this format then have a lexiographical\n// ordering that matches the expected ordering. The translation is done to avoid\n// having a leading negative sign (i.e. a leading '-' character) in its string representation,\n// which would affect its lexiographical ordering.\nvar t=this.seconds- -62135596800;// Note: Up to 12 decimal digits are required to represent all valid 'seconds' values.\nreturn String(t).padStart(12,\"0\")+\".\"+String(this.nanoseconds).padStart(9,\"0\");},t;}(),st=/** @class */function(){function t(t){this.timestamp=t;}return t.J=function(e){return new t(e);},t.min=function(){return new t(new ot(0,0));},t.prototype.L=function(t){return this.timestamp.Y(t.timestamp);},t.prototype.isEqual=function(t){return this.timestamp.isEqual(t.timestamp);},/** Returns a number representation of the version for use in spec tests. */t.prototype.X=function(){// Convert to microseconds.\nreturn 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3;},t.prototype.toString=function(){return\"SnapshotVersion(\"+this.timestamp.toString()+\")\";},t.prototype.Z=function(){return this.timestamp;},t;}();/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * Returns whether a variable is either undefined or null.\n */function ut(t){return null==t;}/** Returns whether the value represents -0. */function at(t){// Detect if the value is -0.0. Based on polyfill from\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\nreturn 0===t&&1/t==-1/0;}/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value The value to test for being an integer and in the safe range\n */function ct(t){return\"number\"==typeof t&&Number.isInteger(t)&&!at(t)&&t<=Number.MAX_SAFE_INTEGER&&t>=Number.MIN_SAFE_INTEGER;}/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ // Visible for testing\nvar ht=function(t,e,n,r,i,o,s){void 0===e&&(e=null),void 0===n&&(n=[]),void 0===r&&(r=[]),void 0===i&&(i=null),void 0===o&&(o=null),void 0===s&&(s=null),this.path=t,this.collectionGroup=e,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=o,this.endAt=s,this.tt=null;};/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */function ft(t,e,n,r,i,o,s){return void 0===e&&(e=null),void 0===n&&(n=[]),void 0===r&&(r=[]),void 0===i&&(i=null),void 0===o&&(o=null),void 0===s&&(s=null),new ht(t,e,n,r,i,o,s);}function lt(t){var e=m(t);if(null===e.tt){var n=e.path.R();null!==e.collectionGroup&&(n+=\"|cg:\"+e.collectionGroup),n+=\"|f:\",n+=e.filters.map(function(t){return function(t){// TODO(b/29183165): Technically, this won't be unique if two values have\n// the same description, such as the int 3 and the string \"3\". So we should\n// add the types in here somehow, too.\nreturn t.field.R()+t.op.toString()+re(t.value);}(t);}).join(\",\"),n+=\"|ob:\",n+=e.orderBy.map(function(t){return(e=t).field.R()+e.dir;var e;}).join(\",\"),ut(e.limit)||(n+=\"|l:\",n+=e.limit),e.startAt&&(n+=\"|lb:\",n+=ar(e.startAt)),e.endAt&&(n+=\"|ub:\",n+=ar(e.endAt)),e.tt=n;}return e.tt;}function pt(t,e){if(t.limit!==e.limit)return!1;if(t.orderBy.length!==e.orderBy.length)return!1;for(var n=0;n0&&(e=e.right);}return null;},// Returns the index of the element in this sorted map, or -1 if it doesn't\n// exist.\nt.prototype.indexOf=function(t){for(// Number of nodes that were pruned when descending right\nvar e=0,n=this.root;!n.m();){var r=this.i(t,n.key);if(0===r)return e+n.left.size;r<0?n=n.left:(// Count all nodes left of the node plus the node itself\ne+=n.left.size+1,n=n.right);}// Node not found\nreturn-1;},t.prototype.m=function(){return this.root.m();},Object.defineProperty(t.prototype,\"size\",{// Returns the total number of nodes in the map.\nget:function(){return this.root.size;},enumerable:!1,configurable:!0}),// Returns the minimum key in the map.\nt.prototype.ct=function(){return this.root.ct();},// Returns the maximum key in the map.\nt.prototype.ut=function(){return this.root.ut();},// Traverses the map in key order and calls the specified action function\n// for each key/value pair. If action returns true, traversal is aborted.\n// Returns the first truthy value returned by action, or the last falsey\n// value returned by action.\nt.prototype.ht=function(t){return this.root.ht(t);},t.prototype.forEach=function(t){this.ht(function(e,n){return t(e,n),!1;});},t.prototype.toString=function(){var t=[];return this.ht(function(e,n){return t.push(e+\":\"+n),!1;}),\"{\"+t.join(\", \")+\"}\";},// Traverses the map in reverse key order and calls the specified action\n// function for each key/value pair. If action returns true, traversal is\n// aborted.\n// Returns the first truthy value returned by action, or the last falsey\n// value returned by action.\nt.prototype.lt=function(t){return this.root.lt(t);},// Returns an iterator over the SortedMap.\nt.prototype._t=function(){return new It(this.root,null,this.i,!1);},t.prototype.ft=function(t){return new It(this.root,t,this.i,!1);},t.prototype.dt=function(){return new It(this.root,null,this.i,!0);},t.prototype.wt=function(t){return new It(this.root,t,this.i,!0);},t;}(),It=/** @class */function(){function t(t,e,n,r){this.Tt=r,this.Et=[];for(var i=1;!t.m();)if(i=e?n(t.key,e):1,// flip the comparison if we're going in reverse\nr&&(i*=-1),i<0)// This node is less than our start key. ignore it\nt=this.Tt?t.left:t.right;else{if(0===i){// This node is exactly equal to our start key. Push it on the stack,\n// but stop iterating;\nthis.Et.push(t);break;}// This node is greater than our start key, add it to the stack and move\n// to the next one\nthis.Et.push(t),t=this.Tt?t.right:t.left;}}return t.prototype.It=function(){var t=this.Et.pop(),e={key:t.key,value:t.value};if(this.Tt)for(t=t.left;!t.m();)this.Et.push(t),t=t.right;else for(t=t.right;!t.m();)this.Et.push(t),t=t.left;return e;},t.prototype.At=function(){return this.Et.length>0;},t.prototype.Rt=function(){if(0===this.Et.length)return null;var t=this.Et[this.Et.length-1];return{key:t.key,value:t.value};},t;}(),Et=/** @class */function(){function t(e,n,r,i,o){this.key=e,this.value=n,this.color=null!=r?r:t.RED,this.left=null!=i?i:t.EMPTY,this.right=null!=o?o:t.EMPTY,this.size=this.left.size+1+this.right.size;}// Returns a copy of the current node, optionally replacing pieces of it.\nreturn t.prototype.copy=function(e,n,r,i,o){return new t(null!=e?e:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=i?i:this.left,null!=o?o:this.right);},t.prototype.m=function(){return!1;},// Traverses the tree in key order and calls the specified action function\n// for each node. If action returns true, traversal is aborted.\n// Returns the first truthy value returned by action, or the last falsey\n// value returned by action.\nt.prototype.ht=function(t){return this.left.ht(t)||t(this.key,this.value)||this.right.ht(t);},// Traverses the tree in reverse key order and calls the specified action\n// function for each node. If action returns true, traversal is aborted.\n// Returns the first truthy value returned by action, or the last falsey\n// value returned by action.\nt.prototype.lt=function(t){return this.right.lt(t)||t(this.key,this.value)||this.left.lt(t);},// Returns the minimum node in the tree.\nt.prototype.min=function(){return this.left.m()?this:this.left.min();},// Returns the maximum key in the tree.\nt.prototype.ct=function(){return this.min().key;},// Returns the maximum key in the tree.\nt.prototype.ut=function(){return this.right.m()?this.key:this.right.ut();},// Returns new tree, with the key/value added.\nt.prototype.ot=function(t,e,n){var r=this,i=n(t,r.key);return(r=i<0?r.copy(null,null,null,r.left.ot(t,e,n),null):0===i?r.copy(null,e,null,null,null):r.copy(null,null,null,null,r.right.ot(t,e,n))).gt();},t.prototype.Pt=function(){if(this.left.m())return t.EMPTY;var e=this;return e.left.yt()||e.left.left.yt()||(e=e.Vt()),(e=e.copy(null,null,null,e.left.Pt(),null)).gt();},// Returns new tree, with the specified item removed.\nt.prototype.remove=function(e,n){var r,i=this;if(n(e,i.key)<0)i.left.m()||i.left.yt()||i.left.left.yt()||(i=i.Vt()),i=i.copy(null,null,null,i.left.remove(e,n),null);else{if(i.left.yt()&&(i=i.bt()),i.right.m()||i.right.yt()||i.right.left.yt()||(i=i.vt()),0===n(e,i.key)){if(i.right.m())return t.EMPTY;r=i.right.min(),i=i.copy(r.key,r.value,null,null,i.right.Pt());}i=i.copy(null,null,null,null,i.right.remove(e,n));}return i.gt();},t.prototype.yt=function(){return this.color;},// Returns new tree after performing any needed rotations.\nt.prototype.gt=function(){var t=this;return t.right.yt()&&!t.left.yt()&&(t=t.St()),t.left.yt()&&t.left.left.yt()&&(t=t.bt()),t.left.yt()&&t.right.yt()&&(t=t.Dt()),t;},t.prototype.Vt=function(){var t=this.Dt();return t.right.left.yt()&&(t=(t=(t=t.copy(null,null,null,null,t.right.bt())).St()).Dt()),t;},t.prototype.vt=function(){var t=this.Dt();return t.left.left.yt()&&(t=(t=t.bt()).Dt()),t;},t.prototype.St=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.bt=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.Dt=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);},// For testing.\nt.prototype.Ct=function(){var t=this.Nt();return Math.pow(2,t)<=this.size+1;},// In a balanced RB tree, the black-depth (number of black nodes) from root to\n// leaves is equal on both sides. This function verifies that or asserts.\nt.prototype.Nt=function(){if(this.yt()&&this.left.yt())throw y();if(this.right.yt())throw y();var t=this.left.Nt();if(t!==this.right.Nt())throw y();return t+(this.yt()?0:1);},t;}();// end SortedMap\n// An iterator over an LLRBNode.\n// end LLRBNode\n// Empty node is shared between all LLRB trees.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nEt.EMPTY=null,Et.RED=!0,Et.at=!1,// end LLRBEmptyNode\nEt.EMPTY=new(/** @class */function(){function t(){this.size=0;}return Object.defineProperty(t.prototype,\"key\",{get:function(){throw y();},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,\"value\",{get:function(){throw y();},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,\"color\",{get:function(){throw y();},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,\"left\",{get:function(){throw y();},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,\"right\",{get:function(){throw y();},enumerable:!1,configurable:!0}),// Returns a copy of the current node.\nt.prototype.copy=function(t,e,n,r,i){return this;},// Returns a copy of the tree, with the specified key/value added.\nt.prototype.ot=function(t,e,n){return new Et(t,e);},// Returns a copy of the tree, with the specified key removed.\nt.prototype.remove=function(t,e){return this;},t.prototype.m=function(){return!0;},t.prototype.ht=function(t){return!1;},t.prototype.lt=function(t){return!1;},t.prototype.ct=function(){return null;},t.prototype.ut=function(){return null;},t.prototype.yt=function(){return!1;},// For testing.\nt.prototype.Ct=function(){return!0;},t.prototype.Nt=function(){return 0;},t;}())();/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */var Tt=/** @class */function(){function t(t){this.i=t,this.data=new bt(this.i);}return t.prototype.has=function(t){return null!==this.data.get(t);},t.prototype.first=function(){return this.data.ct();},t.prototype.last=function(){return this.data.ut();},Object.defineProperty(t.prototype,\"size\",{get:function(){return this.data.size;},enumerable:!1,configurable:!0}),t.prototype.indexOf=function(t){return this.data.indexOf(t);},/** Iterates elements in order defined by \"comparator\" */t.prototype.forEach=function(t){this.data.ht(function(e,n){return t(e),!1;});},/** Iterates over `elem`s such that: range[0] <= elem < range[1]. */t.prototype.Ft=function(t,e){for(var n=this.data.ft(t[0]);n.At();){var r=n.It();if(this.i(r.key,t[1])>=0)return;e(r.key);}},/**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */t.prototype.xt=function(t,e){var n;for(n=void 0!==e?this.data.ft(e):this.data._t();n.At();)if(!t(n.It().key))return;},/** Finds the least element greater than or equal to `elem`. */t.prototype.$t=function(t){var e=this.data.ft(t);return e.At()?e.It().key:null;},t.prototype._t=function(){return new Nt(this.data._t());},t.prototype.ft=function(t){return new Nt(this.data.ft(t));},/** Inserts or updates an element */t.prototype.add=function(t){return this.copy(this.data.remove(t).ot(t,!0));},/** Deletes an element */t.prototype.delete=function(t){return this.has(t)?this.copy(this.data.remove(t)):this;},t.prototype.m=function(){return this.data.m();},t.prototype.kt=function(t){var e=this;// Make sure `result` always refers to the larger one of the two sets.\nreturn e.sizeAdded\n// Removed->Removed\n// Modified->Added\n// Removed->Modified\n// Metadata->Added\n// Removed->Metadata\ny():this.qt=this.qt.ot(e,t);},t.prototype.Ut=function(){var t=[];return this.qt.ht(function(e,n){t.push(n);}),t;},t;}(),Ft=/** @class */function(){function t(t,e,n,r,i,o,s,u){this.query=t,this.docs=e,this.Qt=n,this.docChanges=r,this.Wt=i,this.fromCache=o,this.jt=s,this.Kt=u/** Returns a view snapshot as if all documents in the snapshot were added. */;}return t.Gt=function(e,n,r,i){var o=[];return n.forEach(function(t){o.push({type:0/* Added */,doc:t});}),new t(e,n,Ut.Bt(n),o,r,i,/* syncStateChanged= */!0,/* excludesMetadataChanges= */!1);},Object.defineProperty(t.prototype,\"hasPendingWrites\",{get:function(){return!this.Wt.m();},enumerable:!1,configurable:!0}),t.prototype.isEqual=function(t){if(!(this.fromCache===t.fromCache&&this.jt===t.jt&&this.Wt.isEqual(t.Wt)&&Qn(this.query,t.query)&&this.docs.isEqual(t.docs)&&this.Qt.isEqual(t.Qt)))return!1;var e=this.docChanges,n=t.docChanges;if(e.length!==n.length)return!1;for(var r=0;r0&&(this.le=!0,this.ue=t);},/**\n * Creates a target change from the current set of changes.\n *\n * To reset the document changes after raising this snapshot, call\n * `clearPendingChanges()`.\n */t.prototype.we=function(){var t=Ot(),e=Ot(),n=Ot();return this.ce.forEach(function(r,i){switch(i){case 0/* Added */:t=t.add(r);break;case 2/* Modified */:e=e.add(r);break;case 1/* Removed */:n=n.add(r);break;default:y();}}),new qt(this.ue,this.he,t,e,n);},/**\n * Resets the document changes and sets `hasPendingChanges` to false.\n */t.prototype.me=function(){this.le=!1,this.ce=Qt();},t.prototype.Te=function(t,e){this.le=!0,this.ce=this.ce.ot(t,e);},t.prototype.Ee=function(t){this.le=!0,this.ce=this.ce.remove(t);},t.prototype.Ie=function(){this.ae+=1;},t.prototype.Ae=function(){this.ae-=1;},t.prototype.Re=function(){this.le=!0,this.he=!0;},t;}(),Wt=/** @class */function(){function t(t){this.ge=t,/** The internal state of all tracked targets. */this.Pe=new Map(),/** Keeps track of the documents to update since the last raised snapshot. */this.ye=St(),/** A mapping of document keys to their set of target IDs. */this.Ve=Kt(),/**\n * A list of targets with existence filter mismatches. These targets are\n * known to be inconsistent and their listens needs to be re-established by\n * RemoteStore.\n */this.pe=new Tt(H)/**\n * Processes and adds the DocumentWatchChange to the current set of changes.\n */;}return t.prototype.be=function(t){for(var e=0,n=t.ie;e0?t.targetIds.forEach(e):this.Pe.forEach(function(t,r){n.Fe(r)&&e(r);});},/**\n * Handles existence filters and synthesizes deletes for filter mismatches.\n * Targets that are invalidated by filter mismatches are added to\n * `pendingTargetResets`.\n */t.prototype.$e=function(t){var e=t.targetId,n=t.oe.count,r=this.ke(e);if(r){var i=r.target;if(dt(i)){if(0===n){// The existence filter told us the document does not exist. We deduce\n// that this document does not exist and apply a deleted document to\n// our updates. Without applying this deleted document there might be\n// another query that will raise this document as part of a snapshot\n// until it is resolved, essentially exposing inconsistency between\n// queries.\nvar o=new A(i.path);this.Se(e,o,new Rn(o,st.min()));}else g(1===n);}else this.Me(e)!==n&&(// Existence filter mismatch: We reset the mapping and raise a new\n// snapshot with `isFromCache:true`.\nthis.xe(e),this.pe=this.pe.add(e));}},/**\n * Converts the currently accumulated state into a remote event at the\n * provided snapshot version. Resets the accumulated changes before returning.\n */t.prototype.Oe=function(t){var e=this,n=new Map();this.Pe.forEach(function(r,i){var o=e.ke(i);if(o){if(r.te&&dt(o.target)){// Document queries for document that don't exist can produce an empty\n// result set. To update our local cache, we synthesize a document\n// delete if we have not previously received the document. This\n// resolves the limbo state of the document, removing it from\n// limboDocumentRefs.\n// TODO(dimond): Ideally we would have an explicit lookup target\n// instead resulting in an explicit delete message and we could\n// remove this special logic.\nvar s=new A(o.target.path);null!==e.ye.get(s)||e.Le(i,s)||e.Se(i,s,new Rn(s,t));}r.fe&&(n.set(i,r.we()),r.me());}});var r=Ot();// We extract the set of limbo-only document updates as the GC logic\n// special-cases documents that do not appear in the target cache.\n// TODO(gsoltis): Expand on this comment once GC is available in the JS\n// client.\nthis.Ve.forEach(function(t,n){var i=!0;n.xt(function(t){var n=e.ke(t);return!n||2/* LimboResolution */===n.et||(i=!1,!1);}),i&&(r=r.add(t));});var i=new Mt(t,n,this.pe,this.ye,r);return this.ye=St(),this.Ve=Kt(),this.pe=new Tt(H),i;},/**\n * Adds the provided document to the internal list of document updates and\n * its document key to the given target's mapping.\n */ // Visible for testing.\nt.prototype.ve=function(t,e){if(this.Fe(t)){var n=this.Le(t,e.key)?2/* Modified */:0/* Added */;this.Ne(t).Te(e.key,n),this.ye=this.ye.ot(e.key,e),this.Ve=this.Ve.ot(e.key,this.Be(e.key).add(t));}},/**\n * Removes the provided document from the target mapping. If the\n * document no longer matches the target, but the document's state is still\n * known (e.g. we know that the document was deleted or we received the change\n * that caused the filter mismatch), the new document can be provided\n * to update the remote document cache.\n */ // Visible for testing.\nt.prototype.Se=function(t,e,n){if(this.Fe(t)){var r=this.Ne(t);this.Le(t,e)?r.Te(e,1/* Removed */):// The document may have entered and left the target before we raised a\n// snapshot, so we can just ignore the change.\nr.Ee(e),this.Ve=this.Ve.ot(e,this.Be(e).delete(t)),n&&(this.ye=this.ye.ot(e,n));}},t.prototype.removeTarget=function(t){this.Pe.delete(t);},/**\n * Returns the current count of documents in the target. This includes both\n * the number of documents that the LocalStore considers to be part of the\n * target as well as any accumulated changes.\n */t.prototype.Me=function(t){var e=this.Ne(t).we();return this.ge.qe(t).size+e.ee.size-e.se.size;},/**\n * Increment the number of acks needed from watch before we can consider the\n * server to be 'in-sync' with the client's active targets.\n */t.prototype.Ie=function(t){this.Ne(t).Ie();},t.prototype.Ne=function(t){var e=this.Pe.get(t);return e||(e=new Bt(),this.Pe.set(t,e)),e;},t.prototype.Be=function(t){var e=this.Ve.get(t);return e||(e=new Tt(H),this.Ve=this.Ve.ot(t,e)),e;},/**\n * Verifies that the user is still interested in this target (by calling\n * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs\n * from watch.\n */t.prototype.Fe=function(t){var e=null!==this.ke(t);return e||l(\"WatchChangeAggregator\",\"Detected inactive target\",t),e;},/**\n * Returns the TargetData for an active target (i.e. a target that the user\n * is still interested in that has no outstanding target change requests).\n */t.prototype.ke=function(t){var e=this.Pe.get(t);return e&&e._e?null:this.ge.Ue(t);},/**\n * Resets the state of a Watch target to its initial state (e.g. sets\n * 'current' to false, clears the resume token and removes its target mapping\n * from all documents).\n */t.prototype.xe=function(t){var e=this;this.Pe.set(t,new Bt()),this.ge.qe(t).forEach(function(n){e.Se(t,n,/*updatedDocument=*/null);});},/**\n * Returns whether the LocalStore considers the document to be part of the\n * specified target.\n */t.prototype.Le=function(t,e){return this.ge.qe(t).has(e);},t;}();/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */function Kt(){return new bt(A.i);}function Qt(){return new bt(A.i);}/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * TransformMutation (see TransformMutation.applyTo()). They can only exist in\n * the local view of a document. Therefore they do not need to be parsed or\n * serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */function Ht(t){var e,n;return\"server_timestamp\"===(null===(n=((null===(e=null==t?void 0:t.mapValue)||void 0===e?void 0:e.fields)||{}).__type__)||void 0===n?void 0:n.stringValue);}/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */ /**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */function Yt(t){var e=t.mapValue.fields.__previous_value__;return Ht(e)?Yt(e):e;}/**\n * Returns the local time at which this timestamp was first set.\n */function $t(t){var e=oe(t.mapValue.fields.__local_write_time__.timestampValue);return new ot(e.seconds,e.nanos);}/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ // A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nvar Xt=new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);/** Extracts the backend's type order for the provided value. */function Jt(t){return\"nullValue\"in t?0/* NullValue */:\"booleanValue\"in t?1/* BooleanValue */:\"integerValue\"in t||\"doubleValue\"in t?2/* NumberValue */:\"timestampValue\"in t?3/* TimestampValue */:\"stringValue\"in t?5/* StringValue */:\"bytesValue\"in t?6/* BlobValue */:\"referenceValue\"in t?7/* RefValue */:\"geoPointValue\"in t?8/* GeoPointValue */:\"arrayValue\"in t?9/* ArrayValue */:\"mapValue\"in t?Ht(t)?4/* ServerTimestampValue */:10/* ObjectValue */:y();}/** Tests `left` and `right` for equality based on the backend semantics. */function Zt(t,e){var n=Jt(t);if(n!==Jt(e))return!1;switch(n){case 0/* NullValue */:return!0;case 1/* BooleanValue */:return t.booleanValue===e.booleanValue;case 4/* ServerTimestampValue */:return $t(t).isEqual($t(e));case 3/* TimestampValue */:return function(t,e){if(\"string\"==typeof t.timestampValue&&\"string\"==typeof e.timestampValue&&t.timestampValue.length===e.timestampValue.length)// Use string equality for ISO 8601 timestamps\nreturn t.timestampValue===e.timestampValue;var n=oe(t.timestampValue),r=oe(e.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos;}(t,e);case 5/* StringValue */:return t.stringValue===e.stringValue;case 6/* BlobValue */:return function(t,e){return ue(t.bytesValue).isEqual(ue(e.bytesValue));}(t,e);case 7/* RefValue */:return t.referenceValue===e.referenceValue;case 8/* GeoPointValue */:return function(t,e){return se(t.geoPointValue.latitude)===se(e.geoPointValue.latitude)&&se(t.geoPointValue.longitude)===se(e.geoPointValue.longitude);}(t,e);case 2/* NumberValue */:return function(t,e){if(\"integerValue\"in t&&\"integerValue\"in e)return se(t.integerValue)===se(e.integerValue);if(\"doubleValue\"in t&&\"doubleValue\"in e){var n=se(t.doubleValue),r=se(e.doubleValue);return n===r?at(n)===at(r):isNaN(n)&&isNaN(r);}return!1;}(t,e);case 9/* ArrayValue */:return Y(t.arrayValue.values||[],e.arrayValue.values||[],Zt);case 10/* ObjectValue */:return function(t,e){var n=t.mapValue.fields||{},r=e.mapValue.fields||{};if(w(n)!==w(r))return!1;for(var i in n)if(n.hasOwnProperty(i)&&(void 0===r[i]||!Zt(n[i],r[i])))return!1;return!0;}(t,e);default:return y();}}function te(t,e){return void 0!==(t.values||[]).find(function(t){return Zt(t,e);});}function ee(t,e){var n=Jt(t),r=Jt(e);if(n!==r)return H(n,r);switch(n){case 0/* NullValue */:return 0;case 1/* BooleanValue */:return H(t.booleanValue,e.booleanValue);case 2/* NumberValue */:return function(t,e){var n=se(t.integerValue||t.doubleValue),r=se(e.integerValue||e.doubleValue);return nr?1:n===r?0:// one or both are NaN.\nisNaN(n)?isNaN(r)?0:-1:1;}(t,e);case 3/* TimestampValue */:return ne(t.timestampValue,e.timestampValue);case 4/* ServerTimestampValue */:return ne($t(t),$t(e));case 5/* StringValue */:return H(t.stringValue,e.stringValue);case 6/* BlobValue */:return function(t,e){var n=ue(t),r=ue(e);return n.L(r);}(t.bytesValue,e.bytesValue);case 7/* RefValue */:return function(t,e){for(var n=t.split(\"/\"),r=e.split(\"/\"),i=0;i\":\"GREATER_THAN\",\">=\":\"GREATER_THAN_OR_EQUAL\",\"==\":\"EQUAL\",\"!=\":\"NOT_EQUAL\",\"array-contains\":\"ARRAY_CONTAINS\",in:\"IN\",\"not-in\":\"NOT_IN\",\"array-contains-any\":\"ARRAY_CONTAINS_ANY\"},ye=function(t,e){this.U=t,this.Qe=e;};/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */ /**\n * Returns an IntegerValue for `value`.\n */function ge(t){return{integerValue:\"\"+t};}/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */function me(t,e){if(t.Qe){if(isNaN(e))return{doubleValue:\"NaN\"};if(e===1/0)return{doubleValue:\"Infinity\"};if(e===-1/0)return{doubleValue:\"-Infinity\"};}return{doubleValue:at(e)?\"-0\":e};}/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */function we(t,e){return ct(e)?ge(e):me(t,e);}/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */function _e(t,e){return t.Qe?new Date(1e3*e.seconds).toISOString().replace(/\\.\\d*/,\"\").replace(\"Z\",\"\")+\".\"+(\"000000000\"+e.nanoseconds).slice(-9)+\"Z\":{seconds:\"\"+e.seconds,nanos:e.nanoseconds};}/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */function be(t,e){return t.Qe?e.toBase64():e.toUint8Array();}/**\n * Returns a ByteString based on the proto string value.\n */function Ie(t,e){return _e(t,e.Z());}function Ee(t){return g(!!t),st.J(function(t){var e=oe(t);return new ot(e.seconds,e.nanos);}(t));}function Te(t,e){return function(t){return new E([\"projects\",t.projectId,\"databases\",t.database]);}(t).child(\"documents\").child(e).R();}function Ne(t){var e=E.g(t);return g(He(e)),e;}function Ae(t,e){return Te(t.U,e.path);}function Se(t,e){var n=Ne(e);return g(n.get(1)===t.U.projectId),g(!n.get(3)&&!t.U.database||n.get(3)===t.U.database),new A(ke(n));}function De(t,e){return Te(t.U,e);}function xe(t){var e=Ne(t);// In v1beta1 queries for collections at the root did not have a trailing\n// \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n// ability to read the v1beta1 form for compatibility with queries persisted\n// in the local target cache.\nreturn 4===e.length?E.P():ke(e);}function Le(t){return new E([\"projects\",t.U.projectId,\"databases\",t.U.database]).R();}function ke(t){return g(t.length>4&&\"documents\"===t.get(4)),t.u(5)/** Creates a Document proto from key and fields (but no create/update time) */;}function Re(t,e,n){return{name:Ae(t,e),fields:n.proto.mapValue.fields};}function Oe(t,e){var n;if(e instanceof wn)n={update:Re(t,e.key,e.value)};else if(e instanceof Nn)n={delete:Ae(t,e.key)};else if(e instanceof _n)n={update:Re(t,e.key,e.data),updateMask:Qe(e.We)};else if(e instanceof In)n={transform:{document:Ae(t,e.key),fieldTransforms:e.fieldTransforms.map(function(t){return function(t,e){var n=e.transform;if(n instanceof Ze)return{fieldPath:e.field.R(),setToServerValue:\"REQUEST_TIME\"};if(n instanceof tn)return{fieldPath:e.field.R(),appendMissingElements:{values:n.elements}};if(n instanceof nn)return{fieldPath:e.field.R(),removeAllFromArray:{values:n.elements}};if(n instanceof on)return{fieldPath:e.field.R(),increment:n.je};throw y();}(0,t);})}};else{if(!(e instanceof An))return y();n={verify:Ae(t,e.key)};}return e.Ge.Ke||(n.currentDocument=function(t,e){return void 0!==e.updateTime?{updateTime:Ie(t,e.updateTime)}:void 0!==e.exists?{exists:e.exists}:y();}(t,e.Ge)),n;}function Pe(t,e){var n=e.currentDocument?function(t){return void 0!==t.updateTime?fn.updateTime(Ee(t.updateTime)):void 0!==t.exists?fn.exists(t.exists):fn.ze();}(e.currentDocument):fn.ze();if(e.update){e.update.name;var r=Se(t,e.update.name),i=new Sn({mapValue:{fields:e.update.fields}});if(e.updateMask){var o=function(t){var e=t.fieldPaths||[];return new an(e.map(function(t){return N.S(t);}));}(e.updateMask);return new _n(r,i,o,n);}return new wn(r,i,n);}if(e.delete){var s=Se(t,e.delete);return new Nn(s,n);}if(e.transform){var u=Se(t,e.transform.document),a=e.transform.fieldTransforms.map(function(e){return function(t,e){var n=null;if(\"setToServerValue\"in e)g(\"REQUEST_TIME\"===e.setToServerValue),n=new Ze();else if(\"appendMissingElements\"in e){var r=e.appendMissingElements.values||[];n=new tn(r);}else if(\"removeAllFromArray\"in e){var i=e.removeAllFromArray.values||[];n=new nn(i);}else\"increment\"in e?n=new on(t,e.increment):y();var o=N.S(e.fieldPath);return new cn(o,n);}(t,e);});return g(!0===n.exists),new In(u,a);}if(e.verify){var c=Se(t,e.verify);return new An(c,n);}return y();}function Ve(t,e){return{documents:[De(t,e.path)]};}function Ue(t,e){// Dissect the path into parent, collectionId, and optional key filter.\nvar n={structuredQuery:{}},r=e.path;null!==e.collectionGroup?(n.parent=De(t,r),n.structuredQuery.from=[{collectionId:e.collectionGroup,allDescendants:!0}]):(n.parent=De(t,r.h()),n.structuredQuery.from=[{collectionId:r._()}]);var i=function(t){if(0!==t.length){var e=t.map(function(t){// visible for testing\nreturn function(t){if(\"==\"/* EQUAL */===t.op){if(le(t.value))return{unaryFilter:{field:ze(t.field),op:\"IS_NAN\"}};if(fe(t.value))return{unaryFilter:{field:ze(t.field),op:\"IS_NULL\"}};}else if(\"!=\"/* NOT_EQUAL */===t.op){if(le(t.value))return{unaryFilter:{field:ze(t.field),op:\"IS_NOT_NAN\"}};if(fe(t.value))return{unaryFilter:{field:ze(t.field),op:\"IS_NOT_NULL\"}};}return{fieldFilter:{field:ze(t.field),op:Ge(t.op),value:t.value}};}(t);});return 1===e.length?e[0]:{compositeFilter:{op:\"AND\",filters:e}};}}(e.filters);i&&(n.structuredQuery.where=i);var o=function(t){if(0!==t.length)return t.map(function(t){// visible for testing\nreturn function(t){return{field:ze(t.field),direction:je(t.dir)};}(t);});}(e.orderBy);o&&(n.structuredQuery.orderBy=o);var s=function(t,e){return t.Qe||ut(e)?e:{value:e};}(t,e.limit);return null!==s&&(n.structuredQuery.limit=s),e.startAt&&(n.structuredQuery.startAt=Me(e.startAt)),e.endAt&&(n.structuredQuery.endAt=Me(e.endAt)),n;}function Ce(t){var e=xe(t.parent),n=t.structuredQuery,r=n.from?n.from.length:0,i=null;if(r>0){g(1===r);var o=n.from[0];o.allDescendants?i=o.collectionId:e=e.child(o.collectionId);}var s=[];n.where&&(s=Fe(n.where));var u=[];n.orderBy&&(u=n.orderBy.map(function(t){return function(t){return new fr(Be(t.field),// visible for testing\nfunction(t){switch(t){case\"ASCENDING\":return\"asc\"/* ASCENDING */;case\"DESCENDING\":return\"desc\"/* DESCENDING */;default:return;}}(t.direction));}(t);}));var a=null;n.limit&&(a=function(t){var e;return ut(e=\"object\"==typeof t?t.value:t)?null:e;}(n.limit));var c=null;n.startAt&&(c=qe(n.startAt));var h=null;return n.endAt&&(h=qe(n.endAt)),zn(Vn(e,i,u,s,a,\"F\"/* First */,c,h));}function Fe(t){return t?void 0!==t.unaryFilter?[Ke(t)]:void 0!==t.fieldFilter?[We(t)]:void 0!==t.compositeFilter?t.compositeFilter.filters.map(function(t){return Fe(t);}).reduce(function(t,e){return t.concat(e);}):y():[];}function Me(t){return{before:t.before,values:t.position};}function qe(t){var e=!!t.before,n=t.values||[];return new ur(n,e);}// visible for testing\nfunction je(t){return de[t];}function Ge(t){return ve[t];}function ze(t){return{fieldPath:t.R()};}function Be(t){return N.S(t.fieldPath);}function We(t){return Jn.create(Be(t.fieldFilter.field),function(t){switch(t){case\"EQUAL\":return\"==\"/* EQUAL */;case\"NOT_EQUAL\":return\"!=\"/* NOT_EQUAL */;case\"GREATER_THAN\":return\">\"/* GREATER_THAN */;case\"GREATER_THAN_OR_EQUAL\":return\">=\"/* GREATER_THAN_OR_EQUAL */;case\"LESS_THAN\":return\"<\"/* LESS_THAN */;case\"LESS_THAN_OR_EQUAL\":return\"<=\"/* LESS_THAN_OR_EQUAL */;case\"ARRAY_CONTAINS\":return\"array-contains\"/* ARRAY_CONTAINS */;case\"IN\":return\"in\"/* IN */;case\"NOT_IN\":return\"not-in\"/* NOT_IN */;case\"ARRAY_CONTAINS_ANY\":return\"array-contains-any\"/* ARRAY_CONTAINS_ANY */;case\"OPERATOR_UNSPECIFIED\":default:return y();}}(t.fieldFilter.op),t.fieldFilter.value);}function Ke(t){switch(t.unaryFilter.op){case\"IS_NAN\":var e=Be(t.unaryFilter.field);return Jn.create(e,\"==\"/* EQUAL */,{doubleValue:NaN});case\"IS_NULL\":var n=Be(t.unaryFilter.field);return Jn.create(n,\"==\"/* EQUAL */,{nullValue:\"NULL_VALUE\"});case\"IS_NOT_NAN\":var r=Be(t.unaryFilter.field);return Jn.create(r,\"!=\"/* NOT_EQUAL */,{doubleValue:NaN});case\"IS_NOT_NULL\":var i=Be(t.unaryFilter.field);return Jn.create(i,\"!=\"/* NOT_EQUAL */,{nullValue:\"NULL_VALUE\"});case\"OPERATOR_UNSPECIFIED\":default:return y();}}function Qe(t){var e=[];return t.fields.forEach(function(t){return e.push(t.R());}),{fieldPaths:e};}function He(t){// Resource names have at least 4 components (project ID, database ID)\nreturn t.length>=4&&\"projects\"===t.get(0)&&\"databases\"===t.get(2);}/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /** Represents a transform within a TransformMutation. */var Ye=function(){// Make sure that the structural type of `TransformOperation` is unique.\n// See https://github.com/microsoft/TypeScript/issues/5451\nthis.He=void 0;};/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */function $e(t,e,n){return t instanceof Ze?function(t,e){var n={fields:{__type__:{stringValue:\"server_timestamp\"},__local_write_time__:{timestampValue:{seconds:t.seconds,nanos:t.nanoseconds}}}};return e&&(n.fields.__previous_value__=e),{mapValue:n};}(n,e):t instanceof tn?en(t,e):t instanceof nn?rn(t,e):function(t,e){// PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n// precision and resolves overflows by reducing precision, we do not\n// manually cap overflows at 2^63.\nvar n=Je(t,e),r=sn(n)+sn(t.je);return ce(n)&&ce(t.je)?ge(r):me(t.serializer,r);}(t,e);}/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */function Xe(t,e,n){// The server just sends null as the transform result for array operations,\n// so we have to calculate a result the same as we do for local\n// applications.\nreturn t instanceof tn?en(t,e):t instanceof nn?rn(t,e):n;}/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @return a base value to store along with the mutation, or null for\n * idempotent transforms.\n */function Je(t,e){return t instanceof on?ce(n=e)||function(t){return!!t&&\"doubleValue\"in t;}(n)?e:{integerValue:0}:null;var n;}/** Transforms a value into a server-generated timestamp. */var Ze=/** @class */function(e){function n(){return null!==e&&e.apply(this,arguments)||this;}return t.__extends(n,e),n;}(Ye),tn=/** @class */function(e){function n(t){var n=this;return(n=e.call(this)||this).elements=t,n;}return t.__extends(n,e),n;}(Ye);/** Transforms an array value via a union operation. */function en(t,e){for(var n=un(e),r=function(t){n.some(function(e){return Zt(e,t);})||n.push(t);},i=0,o=t.elements;i0?t.on[0].field:null;}function qn(t){for(var e=0,n=t.filters;e0?e.on[e.on.length-1].dir:\"asc\"/* ASCENDING */;e.cn.push(new fr(N.v(),a));}}}return e.cn;}/**\n * Converts this `Query` instance to it's corresponding `Target` representation.\n */function zn(t){var e=m(t);if(!e.un)if(\"F\"/* First */===e.an)e.un=ft(e.path,e.collectionGroup,Gn(e),e.filters,e.limit,e.startAt,e.endAt);else{for(// Flip the orderBy directions since we want the last results\nvar n=[],r=0,i=Gn(e);r0&&(e+=\", filters: [\"+t.filters.map(function(t){return(e=t).field.R()+\" \"+e.op+\" \"+re(e.value);/** Returns a debug description for `filter`. */var e;/** Filter that matches on key fields (i.e. '__name__'). */}).join(\", \")+\"]\"),ut(t.limit)||(e+=\", limit: \"+t.limit),t.orderBy.length>0&&(e+=\", orderBy: [\"+t.orderBy.map(function(t){return(e=t).field.R()+\" (\"+e.dir+\")\";var e;}).join(\", \")+\"]\"),t.startAt&&(e+=\", startAt: \"+ar(t.startAt)),t.endAt&&(e+=\", endAt: \"+ar(t.endAt)),\"Target(\"+e+\")\";}(zn(t))+\"; limitType=\"+t.an+\")\";}/** Returns whether `doc` matches the constraints of `query`. */function $n(t,e){return function(t,e){var n=e.key.path;return null!==t.collectionGroup?e.key.N(t.collectionGroup)&&t.path.T(n):A.F(t.path)?t.path.isEqual(n):t.path.I(n);}(t,e)&&function(t,e){for(var n=0,r=t.on;n= 12.2 and < 13, but for\n// whatever reason it's much harder to hit after 12.2 so we only proactively\n// log on 12.2.\n12.2===e.On(r.getUA())&&p(\"Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.\");}/** Deletes the specified database. */return e.delete=function(t){return l(\"SimpleDb\",\"Removing database:\",t),Er(window.indexedDB.deleteDatabase(t)).Fn();},/** Returns true if IndexedDB is available in the current environment. */e.Ln=function(){if(\"undefined\"==typeof indexedDB)return!1;if(e.Bn())return!0;// We extensively use indexed array values and compound keys,\n// which IE and Edge do not support. However, they still have indexedDB\n// defined on the window, so we need to check for them here and make sure\n// to return that persistence is not enabled for those browsers.\n// For tracking support of this feature, see here:\n// https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n// Check the UA string to find out the browser.\nvar t=r.getUA(),n=e.On(t),i=00||t.indexOf(\"Trident/\")>0||t.indexOf(\"Edge/\")>0||i||s);},/**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */e.Bn=function(){var t;return\"undefined\"!=typeof process&&\"YES\"===(null===(t=Object({\"FIREBASE_UID\":\"177d7e743d4ef19dc6ae00ec61b2848d1e1424b88201806ad975799e38f66faff36072282df28b177081126c30281eb0d9d6736ecbfd25c98b2b8a0f3df1a79101f20468b5a4abd53e17ac74912dec73b9ab3084087efd42b00384ee00fbb625b3b73a50698b942ed7a9b4ec8d\"}))||void 0===t?void 0:t.Un);},/** Helper to get a typed SimpleDbStore from a transaction. */e.Qn=function(t,e){return t.store(e);},// visible for testing\n/** Parse User Agent to determine iOS version. Returns -1 if not found. */e.On=function(t){var e=t.match(/i(?:phone|pad|pod) os ([\\d_]+)/i),n=e?e[1].split(\"_\").slice(0,2).join(\".\"):\"-1\";return Number(n);},// visible for testing\n/** Parse User Agent to determine Android version. Returns -1 if not found. */e.qn=function(t){var e=t.match(/Android ([\\d.]+)/i),n=e?e[1].split(\".\").slice(0,2).join(\".\"):\"-1\";return Number(n);},/**\n * Opens the specified database, creating or upgrading it if necessary.\n */e.prototype.Wn=function(e){return t.__awaiter(this,void 0,void 0,function(){var n,r=this;return t.__generator(this,function(t){switch(t.label){case 0:return this.db?[3/*break*/,2]:(l(\"SimpleDb\",\"Opening database:\",this.name),n=this,[4/*yield*/,new Promise(function(t,n){// TODO(mikelehen): Investigate browser compatibility.\n// https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n// suggests IE9 and older WebKit browsers handle upgrade\n// differently. They expect setVersion, as described here:\n// https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\nvar i=indexedDB.open(r.name,r.version);i.onsuccess=function(e){var n=e.target.result;t(n);},i.onblocked=function(){n(new wr(e,\"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed.\"));},i.onerror=function(t){var r=t.target.error;\"VersionError\"===r.name?n(new c(a.FAILED_PRECONDITION,\"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.\")):n(new wr(e,r));},i.onupgradeneeded=function(t){l(\"SimpleDb\",'Database \"'+r.name+'\" requires upgrade from version:',t.oldVersion);var e=t.target.result;r.Mn.createOrUpgrade(e,i.transaction,t.oldVersion,r.version).next(function(){l(\"SimpleDb\",\"Database upgrade to version \"+r.version+\" complete\");});};})]);case 1:n.db=t.sent(),t.label=2;case 2:return[2/*return*/,(this.jn&&(this.db.onversionchange=function(t){return r.jn(t);}),this.db)];}});});},e.prototype.Kn=function(t){this.jn=t,this.db&&(this.db.onversionchange=function(e){return t(e);});},e.prototype.runTransaction=function(e,n,r,i){return t.__awaiter(this,void 0,void 0,function(){var o,s,u,a,c;return t.__generator(this,function(h){switch(h.label){case 0:o=\"readonly\"===n,s=0,u=function(){var n,u,c,h,f;return t.__generator(this,function(t){switch(t.label){case 0:++s,t.label=1;case 1:return t.trys.push([1,4,,5]),[4/*yield*/,a.Wn(e)];case 2:// Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n// fire), but still return the original transactionFnResult back to the\n// caller.\nreturn a.db=t.sent(),n=br.open(a.db,e,o?\"readonly\":\"readwrite\",r),u=i(n).catch(function(t){// Abort the transaction if there was an error.\nreturn n.abort(t),yr.reject(t);}).Fn(),c={},u.catch(function(){}),[4/*yield*/,n.Gn];case 3:return[2/*return*/,(c.value=(// Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n// fire), but still return the original transactionFnResult back to the\n// caller.\nt.sent(),u),c)];case 4:return h=t.sent(),f=\"FirebaseError\"!==h.name&&s<3,l(\"SimpleDb\",\"Transaction failed with error:\",h.message,\"Retrying:\",f),a.close(),f?[3/*break*/,5]:[2/*return*/,{value:Promise.reject(h)}];case 5:return[2/*return*/];}});},a=this,h.label=1;case 1:return[5/*yield**/,u()];case 2:if(\"object\"==typeof(c=h.sent()))return[2/*return*/,c.value];h.label=3;case 3:return[3/*break*/,1];case 4:return[2/*return*/];}});});},e.prototype.close=function(){this.db&&this.db.close(),this.db=void 0;},e;}(),mr=/** @class */function(){function t(t){this.zn=t,this.Hn=!1,this.Yn=null;}return Object.defineProperty(t.prototype,\"Sn\",{get:function(){return this.Hn;},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,\"Jn\",{get:function(){return this.Yn;},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,\"cursor\",{set:function(t){this.zn=t;},enumerable:!1,configurable:!0}),/**\n * This function can be called to stop iteration at any point.\n */t.prototype.done=function(){this.Hn=!0;},/**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */t.prototype.Xn=function(t){this.Yn=t;},/**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */t.prototype.delete=function(){return Er(this.zn.delete());},t;}(),wr=/** @class */function(e){function n(t,n){var r=this;return(r=e.call(this,a.UNAVAILABLE,\"IndexedDB transaction '\"+t+\"' failed: \"+n)||this).name=\"IndexedDbTransactionError\",r;}return t.__extends(n,e),n;}(c);/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */ /** Verifies whether `e` is an IndexedDbTransactionError. */function _r(t){// Use name equality, as instanceof checks on errors don't work with errors\n// that wrap other errors.\nreturn\"IndexedDbTransactionError\"===t.name;}/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */var br=/** @class */function(){function t(t,e){var n=this;this.action=t,this.transaction=e,this.aborted=!1,/**\n * A promise that resolves with the result of the IndexedDb transaction.\n */this.Zn=new dr(),this.transaction.oncomplete=function(){n.Zn.resolve();},this.transaction.onabort=function(){e.error?n.Zn.reject(new wr(t,e.error)):n.Zn.resolve();},this.transaction.onerror=function(e){var r=Nr(e.target.error);n.Zn.reject(new wr(t,r));};}return t.open=function(e,n,r,i){try{return new t(n,e.transaction(i,r));}catch(e){throw new wr(n,e);}},Object.defineProperty(t.prototype,\"Gn\",{get:function(){return this.Zn.promise;},enumerable:!1,configurable:!0}),t.prototype.abort=function(t){t&&this.Zn.reject(t),this.aborted||(l(\"SimpleDb\",\"Aborting transaction:\",t?t.message:\"Client-initiated abort\"),this.aborted=!0,this.transaction.abort());},/**\n * Returns a SimpleDbStore for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */t.prototype.store=function(t){var e=this.transaction.objectStore(t);return new Ir(e);},t;}(),Ir=/** @class */function(){function t(t){this.store=t;}return t.prototype.put=function(t,e){var n;return void 0!==e?(l(\"SimpleDb\",\"PUT\",this.store.name,t,e),n=this.store.put(e,t)):(l(\"SimpleDb\",\"PUT\",this.store.name,\"\",t),n=this.store.put(t)),Er(n);},/**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value The object to write.\n * @return The key of the value to add.\n */t.prototype.add=function(t){return l(\"SimpleDb\",\"ADD\",this.store.name,t,t),Er(this.store.add(t));},/**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @return The object with the specified key or null if no object exists.\n */t.prototype.get=function(t){var e=this;// We're doing an unsafe cast to ValueType.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nreturn Er(this.store.get(t)).next(function(n){// Normalize nonexistence to null.\nreturn void 0===n&&(n=null),l(\"SimpleDb\",\"GET\",e.store.name,t,n),n;});},t.prototype.delete=function(t){return l(\"SimpleDb\",\"DELETE\",this.store.name,t),Er(this.store.delete(t));},/**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */t.prototype.count=function(){return l(\"SimpleDb\",\"COUNT\",this.store.name),Er(this.store.count());},t.prototype.ts=function(t,e){var n=this.cursor(this.options(t,e)),r=[];return this.es(n,function(t,e){r.push(e);}).next(function(){return r;});},t.prototype.ns=function(t,e){l(\"SimpleDb\",\"DELETE ALL\",this.store.name);var n=this.options(t,e);n.ss=!1;var r=this.cursor(n);return this.es(r,function(t,e,n){return n.delete();});},t.prototype.rs=function(t,e){var n;e?n=t:(n={},e=t);var r=this.cursor(n);return this.es(r,e);},/**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */t.prototype.os=function(t){var e=this.cursor({});return new yr(function(n,r){e.onerror=function(t){var e=Nr(t.target.error);r(e);},e.onsuccess=function(e){var r=e.target.result;r?t(r.primaryKey,r.value).next(function(t){t?r.continue():n();}):n();};});},t.prototype.es=function(t,e){var n=[];return new yr(function(r,i){t.onerror=function(t){i(t.target.error);},t.onsuccess=function(t){var i=t.target.result;if(i){var o=new mr(i),s=e(i.primaryKey,i.value,o);if(s instanceof yr){var u=s.catch(function(t){return o.done(),yr.reject(t);});n.push(u);}o.Sn?r():null===o.Jn?i.continue():i.continue(o.Jn);}else r();};}).next(function(){return yr.$n(n);});},t.prototype.options=function(t,e){var n=void 0;return void 0!==t&&(\"string\"==typeof t?n=t: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.ss?n.openKeyCursor(t.range,e):n.openCursor(t.range,e);}return this.store.openCursor(t.range,e);},t;}();/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */ /**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */function Er(t){return new yr(function(e,n){t.onsuccess=function(t){var n=t.target.result;e(n);},t.onerror=function(t){var e=Nr(t.target.error);n(e);};});}// Guard so we only report the error once.\nvar Tr=!1;function Nr(t){var e=gr.On(r.getUA());if(e>=12.2&&e<13){var n=\"An internal error was encountered in the Indexed Database server\";if(t.message.indexOf(n)>=0){// Wrap error in a more descriptive one.\nvar i=new c(\"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 Tr||(Tr=!0,// Throw a global exception outside of this promise chain, for the user to\n// potentially catch.\nsetTimeout(function(){throw i;},0)),i;}}return t;}/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /** The Platform's 'window' implementation or null if not available. */function Ar(){// `window` is not always available, e.g. in ReactNative and WebWorkers.\n// eslint-disable-next-line no-restricted-globals\nreturn\"undefined\"!=typeof window?window:null;}/** The Platform's 'document' implementation or null if not available. */function Sr(){// `document` is not always available, e.g. in ReactNative and WebWorkers.\n// eslint-disable-next-line no-restricted-globals\nreturn\"undefined\"!=typeof document?document:null;}/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */var Dr=/** @class */function(){function t(t,e,n,r,i){this.cs=t,this.dn=e,this.us=n,this.op=r,this.hs=i,this.ls=new dr(),this.then=this.ls.promise.then.bind(this.ls.promise),// It's normal for the deferred promise to be canceled (due to cancellation)\n// and so we attach a dummy catch callback to avoid\n// 'UnhandledPromiseRejectionWarning' log spam.\nthis.ls.promise.catch(function(t){})/**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue The queue to schedule the operation on.\n * @param id A Timer ID identifying the type of operation this is.\n * @param delayMs The delay (ms) before the operation should be scheduled.\n * @param op The operation to run.\n * @param removalCallback A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */;}return t._s=function(e,n,r,i,o){var s=new t(e,n,Date.now()+r,i,o);return s.start(r),s;},/**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */t.prototype.start=function(t){var e=this;this.fs=setTimeout(function(){return e.ds();},t);},/**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */t.prototype.pn=function(){return this.ds();},/**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */t.prototype.cancel=function(t){null!==this.fs&&(this.clearTimeout(),this.ls.reject(new c(a.CANCELLED,\"Operation cancelled\"+(t?\": \"+t:\"\"))));},t.prototype.ds=function(){var t=this;this.cs.ws(function(){return null!==t.fs?(t.clearTimeout(),t.op().then(function(e){return t.ls.resolve(e);})):Promise.resolve();});},t.prototype.clearTimeout=function(){null!==this.fs&&(this.hs(this),clearTimeout(this.fs),this.fs=null);},t;}(),xr=/** @class */function(){function e(){var t=this;// The last promise in the queue.\nthis.Ts=Promise.resolve(),// A list of retryable operations. Retryable operations are run in order and\n// retried with backoff.\nthis.Es=[],// Is this AsyncQueue being shut down? Once it is set to true, it will not\n// be changed again.\nthis.Is=!1,// Operations scheduled to be queued in the future. Operations are\n// automatically removed after they are run or canceled.\nthis.As=[],// visible for testing\nthis.Rs=null,// Flag set while there's an outstanding AsyncQueue operation, used for\n// assertion sanity-checks.\nthis.gs=!1,// List of TimerIds to fast-forward delays for.\nthis.Ps=[],// Backoff timer used to schedule retries for retryable operations\nthis.ys=new vr(this,\"async_queue_retry\"/* AsyncQueueRetry */),// Visibility handler that triggers an immediate retry of all retryable\n// operations. Meant to speed up recovery when we regain file system access\n// after page comes into foreground.\nthis.Vs=function(){var e=Sr();e&&l(\"AsyncQueue\",\"Visibility state changed to \",e.visibilityState),t.ys.Vn();};var e=Sr();e&&\"function\"==typeof e.addEventListener&&e.addEventListener(\"visibilitychange\",this.Vs);}return Object.defineProperty(e.prototype,\"ps\",{// Is this AsyncQueue being shut down? If true, this instance will not enqueue\n// any new operations, Promises from enqueue requests will not resolve.\nget:function(){return this.Is;},enumerable:!1,configurable:!0}),/**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */e.prototype.ws=function(t){// eslint-disable-next-line @typescript-eslint/no-floating-promises\nthis.enqueue(t);},/**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue without waiting for it to complete (i.e. we ignore the Promise result).\n */e.prototype.bs=function(t){this.vs(),// eslint-disable-next-line @typescript-eslint/no-floating-promises\nthis.Ss(t);},/**\n * Initialize the shutdown of this queue. Once this method is called, the\n * only possible way to request running an operation is through\n * `enqueueEvenWhileRestricted()`.\n */e.prototype.Ds=function(){if(!this.Is){this.Is=!0;var t=Sr();t&&\"function\"==typeof t.removeEventListener&&t.removeEventListener(\"visibilitychange\",this.Vs);}},/**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */e.prototype.enqueue=function(t){return this.vs(),this.Is?new Promise(function(t){}):this.Ss(t);},/**\n * Enqueue a retryable operation.\n *\n * A retryable operation is rescheduled with backoff if it fails with a\n * IndexedDbTransactionError (the error type used by SimpleDb). All\n * retryable operations are executed in order and only run if all prior\n * operations were retried successfully.\n */e.prototype.Cs=function(t){var e=this;this.ws(function(){return e.Es.push(t),e.Ns();});},/**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */e.prototype.Ns=function(){return t.__awaiter(this,void 0,void 0,function(){var e,n=this;return t.__generator(this,function(t){switch(t.label){case 0:if(0===this.Es.length)return[3/*break*/,5];t.label=1;case 1:return t.trys.push([1,3,,4]),[4/*yield*/,this.Es[0]()];case 2:return t.sent(),this.Es.shift(),this.ys.reset(),[3/*break*/,4];case 3:if(!_r(e=t.sent()))throw e;// Failure will be handled by AsyncQueue\nreturn l(\"AsyncQueue\",\"Operation failed with retryable error: \"+e),[3/*break*/,4];case 4:this.Es.length>0&&// If there are additional operations, we re-schedule `retryNextOp()`.\n// This is necessary to run retryable operations that failed during\n// their initial attempt since we don't know whether they are already\n// enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n// needs to be re-run, we will run `op1`, `op1`, `op2` using the\n// already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n// call scheduled here.\n// Since `backoffAndRun()` cancels an existing backoff and schedules a\n// new backoff on every call, there is only ever a single additional\n// operation in the queue.\nthis.ys.gn(function(){return n.Ns();}),t.label=5;case 5:return[2/*return*/];}});});},e.prototype.Ss=function(t){var e=this,n=this.Ts.then(function(){return e.gs=!0,t().catch(function(t){// Re-throw the error so that this.tail becomes a rejected Promise and\n// all further attempts to chain (via .then) will just short-circuit\n// and return the rejected Promise.\nthrow e.Rs=t,e.gs=!1,p(\"INTERNAL UNHANDLED ERROR: \",/**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error Error or FirestoreError\n */function(t){var e=t.message||\"\";return t.stack&&(e=t.stack.includes(t.message)?t.stack:t.message+\"\\n\"+t.stack),e;}(t)),t;}).then(function(t){return e.gs=!1,t;});});return this.Ts=n,n;},/**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel\n * or fast-forward the operation prior to its running.\n */e.prototype.yn=function(t,e,n){var r=this;this.vs(),// Fast-forward delays for timerIds that have been overriden.\nthis.Ps.indexOf(t)>-1&&(e=0);var i=Dr._s(this,t,e,n,function(t){return r.Fs(t);});return this.As.push(i),i;},e.prototype.vs=function(){this.Rs&&y();},/**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */e.prototype.xs=function(){},/**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */e.prototype.$s=function(){return t.__awaiter(this,void 0,void 0,function(){var e;return t.__generator(this,function(t){switch(t.label){case 0:return[4/*yield*/,e=this.Ts];case 1:t.sent(),t.label=2;case 2:if(e!==this.Ts)return[3/*break*/,0];t.label=3;case 3:return[2/*return*/];}});});},/**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */e.prototype.ks=function(t){for(var e=0,n=this.As;e=0&&(s.listeners.splice(u,1),o=0===s.listeners.length),o?[2/*return*/,(r.Bs.delete(i),r.js(i))]:[2/*return*/];});});}function Vr(t,e){for(var n=m(t),r=!1,i=0,o=e;i0)return!0;var e=this.zs&&this.zs.hasPendingWrites!==t.hasPendingWrites;return!(!t.jt&&!e)&&!0===this.options.includeMetadataChanges;// Generally we should have hit one of the cases above, but it's possible\n// to get here if there were only metadata docChanges and they got\n// stripped out.\n},t.prototype.Js=function(t){t=Ft.Gt(t.query,t.docs,t.Wt,t.fromCache),this.Gs=!0,this.Ks.next(t);},t;}(),Mr=/** @class */function(){function t(t){this.uid=t;}return t.prototype.Zs=function(){return null!=this.uid;},/**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */t.prototype.ti=function(){return this.Zs()?\"uid:\"+this.uid:\"anonymous-user\";},t.prototype.isEqual=function(t){return t.uid===this.uid;},t;}();/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */ /** A user with a null UID. */Mr.UNAUTHENTICATED=new Mr(null),// TODO(mikelehen): Look into getting a proper uid-equivalent for\n// non-FirebaseAuth providers.\nMr.ei=new Mr(\"google-credentials-uid\"),Mr.ni=new Mr(\"first-party-uid\");/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */var qr=/** @class */function(){function t(t,e){var n=this;this.previousValue=t,e&&(e.si=function(t){return n.ii(t);},this.ri=function(t){return e.oi(t);});}return t.prototype.ii=function(t){return this.previousValue=Math.max(t,this.previousValue),this.previousValue;},t.prototype.next=function(){var t=++this.previousValue;return this.ri&&this.ri(t),t;},t;}();/** Assembles the key for a client state in WebStorage */function jr(t,e){return\"firestore_clients_\"+t+\"_\"+e;}// The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations__\n// (for unauthenticated users)\n// or: firestore_mutations___\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\n/** Assembles the key for a mutation batch in WebStorage */function Gr(t,e,n){var r=\"firestore_mutations_\"+t+\"_\"+n;return e.Zs()&&(r+=\"_\"+e.uid),r;}// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets__\n/** Assembles the key for a query state in WebStorage */function zr(t,e){return\"firestore_targets_\"+t+\"_\"+e;}// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_\n/**\n * Holds the state of a mutation batch, including its user ID, batch ID and\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\n */ // Visible for testing\nqr.ai=-1;var Br=/** @class */function(){function t(t,e,n,r){this.user=t,this.batchId=e,this.state=n,this.error=r/**\n * Parses a MutationMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */;}return t.ci=function(e,n,r){var i=JSON.parse(r),o=\"object\"==typeof i&&-1!==[\"pending\",\"acknowledged\",\"rejected\"].indexOf(i.state)&&(void 0===i.error||\"object\"==typeof i.error),s=void 0;return o&&i.error&&(o=\"string\"==typeof i.error.message&&\"string\"==typeof i.error.code)&&(s=new c(i.error.code,i.error.message)),o?new t(e,n,i.state,s):(p(\"SharedClientState\",\"Failed to parse mutation state for ID '\"+n+\"': \"+r),null);},t.prototype.ui=function(){var t={state:this.state,updateTimeMs:Date.now()};return this.error&&(t.error={code:this.error.code,message:this.error.message}),JSON.stringify(t);},t;}(),Wr=/** @class */function(){function t(t,e,n){this.targetId=t,this.state=e,this.error=n/**\n * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */;}return t.ci=function(e,n){var r=JSON.parse(n),i=\"object\"==typeof r&&-1!==[\"not-current\",\"current\",\"rejected\"].indexOf(r.state)&&(void 0===r.error||\"object\"==typeof r.error),o=void 0;return i&&r.error&&(i=\"string\"==typeof r.error.message&&\"string\"==typeof r.error.code)&&(o=new c(r.error.code,r.error.message)),i?new t(e,r.state,o):(p(\"SharedClientState\",\"Failed to parse target state for ID '\"+e+\"': \"+n),null);},t.prototype.ui=function(){var t={state:this.state,updateTimeMs:Date.now()};return this.error&&(t.error={code:this.error.code,message:this.error.message}),JSON.stringify(t);},t;}(),Kr=/** @class */function(){function t(t,e){this.clientId=t,this.activeTargetIds=e/**\n * Parses a RemoteClientState from the JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */;}return t.ci=function(e,n){for(var r=JSON.parse(n),i=\"object\"==typeof r&&r.activeTargetIds instanceof Array,o=Vt(),s=0;i&&sversion mapping (docVersions).\n */;}return t.from=function(e,n,r){g(e.mutations.length===r.length);for(var i=kt,o=e.mutations,s=0;sh.params.oo?(l(\"LruGarbageCollector\",\"Capping sequence numbers to collect down to the maximum of \"+h.params.oo+\" from \"+e),i=h.params.oo):i=e,s=Date.now(),h.yo(t,i);}).next(function(n){return r=n,u=Date.now(),h.po(t,r,e);}).next(function(e){return o=e,a=Date.now(),h.bo(t,r);}).next(function(t){return c=Date.now(),f()<=n.LogLevel.DEBUG&&l(\"LruGarbageCollector\",\"LRU Garbage Collection\\n\\tCounted targets in \"+(s-p)+\"ms\\n\\tDetermined least recently used \"+i+\" in \"+(u-s)+\"ms\\n\\tRemoved \"+o+\" targets in \"+(a-u)+\"ms\\n\\tRemoved \"+t+\" documents in \"+(c-a)+\"ms\\nTotal Duration: \"+(c-p)+\"ms\"),yr.resolve({Zr:!0,eo:i,no:o,so:t});});},t;}();/** Implements the steps for LRU garbage collection. */ /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */function hi(t){for(var e=\"\",n=0;n0&&(e=li(e)),e=fi(t.get(n),e);return li(e);}/** Encodes a single segment of a resource path into the given result */function fi(t,e){for(var n=e,r=t.length,i=0;i=2),2===e)return g(\"\u0001\"===t.charAt(0)&&\"\u0001\"===t.charAt(1)),E.P();// Escape characters cannot exist past the second-to-last position in the\n// source value.\nfor(var n=e-2,r=[],i=\"\",o=0;on)&&y(),t.charAt(s+1)){case\"\u0001\":var u=t.substring(o,s),a=void 0;0===i.length?// Avoid copying for the common case of a segment that excludes \\0\n// and \\001\na=u:(a=i+=u,i=\"\"),r.push(a);break;case\"\u0010\":i+=t.substring(o,s),i+=\"\\0\";break;case\"\u0011\":// The escape character can be used in the output to encode itself.\ni+=t.substring(o,s+1);break;default:y();}o=s+2;}return new E(r);}/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /** Serializer for values stored in the LocalStore. */var di=function(t){this.Co=t;};/** Decodes a remote document from storage locally to a Document. */function vi(t,e){if(e.document)return function(t,e,n){var r=Se(t,e.name),i=Ee(e.updateTime),o=new Sn({mapValue:{fields:e.fields}});return new kn(r,i,o,{hasCommittedMutations:!!n});}(t.Co,e.document,!!e.hasCommittedMutations);if(e.noDocument){var n=A.$(e.noDocument.path),r=_i(e.noDocument.readTime);return new Rn(n,r,{hasCommittedMutations:!!e.hasCommittedMutations});}if(e.unknownDocument){var i=A.$(e.unknownDocument.path),o=_i(e.unknownDocument.version);return new On(i,o);}return y();}/** Encodes a document for storage locally. */function yi(t,e,n){var r=gi(n),i=e.key.path.h().A();if(e instanceof kn){var o=function(t,e){return{name:Ae(t,e.key),fields:e.rn().mapValue.fields,updateTime:_e(t,e.version.Z())};}(t.Co,e),s=e.hasCommittedMutations;return new Ki(/* unknownDocument= */null,/* noDocument= */null,o,s,r,i);}if(e instanceof Rn){var u=e.key.path.A(),a=wi(e.version),c=e.hasCommittedMutations;return new Ki(/* unknownDocument= */null,new Bi(u,a),/* document= */null,c,r,i);}if(e instanceof On){var h=e.key.path.A(),f=wi(e.version);return new Ki(new Wi(h,f),/* noDocument= */null,/* document= */null,/* hasCommittedMutations= */!0,r,i);}return y();}function gi(t){var e=t.Z();return[e.seconds,e.nanoseconds];}function mi(t){var e=new ot(t[0],t[1]);return st.J(e);}function wi(t){var e=t.Z();return new Mi(e.seconds,e.nanoseconds);}function _i(t){var e=new ot(t.seconds,t.nanoseconds);return st.J(e);}/** Encodes a batch of mutations into a DbMutationBatch for local storage. */ /** Decodes a DbMutationBatch into a MutationBatch */function bi(t,e){var n=(e.baseMutations||[]).map(function(e){return Pe(t.Co,e);}),r=e.mutations.map(function(e){return Pe(t.Co,e);}),i=ot.fromMillis(e.localWriteTimeMs);return new Xr(e.batchId,i,n,r);}/** Decodes a DbTarget into TargetData */function Ii(t){var e,n,r=_i(t.readTime),i=void 0!==t.lastLimboFreeSnapshotVersion?_i(t.lastLimboFreeSnapshotVersion):st.min();return void 0!==t.query.documents?(g(1===(n=t.query).documents.length),e=zn(Un(xe(n.documents[0])))):e=Ce(t.query),new gt(e,t.targetId,0/* Listen */,t.lastListenSequenceNumber,r,i,X.fromBase64String(t.resumeToken))/** Encodes TargetData into a DbTarget for storage locally. */;}function Ei(t,e){var n,r=wi(e.nt),i=wi(e.lastLimboFreeSnapshotVersion);n=dt(e.target)?Ve(t.Co,e.target):Ue(t.Co,e.target);// We can't store the resumeToken as a ByteString in IndexedDb, so we\n// convert it to a base64 string for storage.\nvar o=e.resumeToken.toBase64();// lastListenSequenceNumber is always 0 until we do real GC.\nreturn new Hi(e.targetId,lt(e.target),r,o,e.sequenceNumber,i,n);}/**\n * A helper function for figuring out what kind of query has been stored.\n */ /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /** A mutation queue for a specific user, backed by IndexedDB. */var Ti=/** @class */function(){function t(/**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */t,e,n,r){this.userId=t,this.serializer=e,this.Dr=n,this.No=r,/**\n * Caches the document keys for pending mutation batches. If the mutation\n * has been removed from IndexedDb, the cached value may continue to\n * be used to retrieve the batch's document keys. To remove a cached value\n * locally, `removeCachedMutationKeys()` should be invoked either directly\n * or through `removeMutationBatches()`.\n *\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\n * this cache is used by secondary clients to invalidate the local\n * view of the documents that were previously affected by the mutation.\n */ // PORTING NOTE: Multi-tab only.\nthis.Fo={}/**\n * Creates a new mutation queue for the given user.\n * @param user The user for which to create a mutation queue.\n * @param serializer The serializer to use when persisting to IndexedDb.\n */;}return t.xo=function(e,n,r,i){// TODO(mcg): Figure out what constraints there are on userIDs\n// In particular, are there any reserved characters? are empty ids allowed?\n// For the moment store these together in the same mutations table assuming\n// that empty userIDs aren't allowed.\nreturn g(\"\"!==e.uid),new t(e.Zs()?e.uid:\"\",n,r,i);},t.prototype.$o=function(t){var e=!0,n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return Si(t).rs({index:Gi.userMutationsIndex,range:n},function(t,n,r){e=!1,r.done();}).next(function(){return e;});},t.prototype.ko=function(t,e,n,r){var i=this,o=Di(t),s=Si(t);// The IndexedDb implementation in Chrome (and Firefox) does not handle\n// compound indices that include auto-generated keys correctly. To ensure\n// that the index entry is added correctly in all browsers, we perform two\n// writes: The first write is used to retrieve the next auto-generated Batch\n// ID, and the second write populates the index and stores the actual\n// mutation batch.\n// See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n// We write an empty object to obtain key\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nreturn s.add({}).next(function(u){g(\"number\"==typeof u);for(var a=new Xr(u,e,n,r),c=function(t,e,n){var r=n.baseMutations.map(function(e){return Oe(t.Co,e);}),i=n.mutations.map(function(e){return Oe(t.Co,e);});return new Gi(e,n.batchId,n.ar.toMillis(),r,i);}(i.serializer,i.userId,a),h=[],f=new Tt(function(t,e){return H(t.R(),e.R());}),l=0,p=r;l=r),o=bi(n.serializer,e)),i.done();}).next(function(){return o;});},t.prototype.qo=function(t){var e=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]),n=-1;return Si(t).rs({index:Gi.userMutationsIndex,range:e,reverse:!0},function(t,e,r){n=e.batchId,r.done();}).next(function(){return n;});},t.prototype.Uo=function(t){var e=this,n=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return Si(t).ts(Gi.userMutationsIndex,n).next(function(t){return t.map(function(t){return bi(e.serializer,t);});});},t.prototype.Nr=function(t,e){var n=this,r=zi.prefixForPath(this.userId,e.path),i=IDBKeyRange.lowerBound(r),o=[];// Scan the document-mutation index starting with a prefix starting with\n// the given documentKey.\nreturn Di(t).rs({range:i},function(r,i,s){var u=r[0],a=r[1],c=r[2],h=pi(a);// Only consider rows matching exactly the specific key of\n// interest. Note that because we order by path first, and we\n// order terminators before path separators, we'll encounter all\n// the index rows for documentKey contiguously. In particular, all\n// the rows for documentKey will occur before any rows for\n// documents nested in a subcollection beneath documentKey so we\n// can stop as soon as we hit any such row.\nif(u===n.userId&&e.path.isEqual(h))// Look up the mutation batch in the store.\nreturn Si(t).get(c).next(function(t){if(!t)throw y();g(t.userId===n.userId),o.push(bi(n.serializer,t));});s.done();}).next(function(){return o;});},t.prototype.Or=function(t,e){var n=this,r=new Tt(H),i=[];return e.forEach(function(e){var o=zi.prefixForPath(n.userId,e.path),s=IDBKeyRange.lowerBound(o),u=Di(t).rs({range:s},function(t,i,o){var s=t[0],u=t[1],a=t[2],c=pi(u);// Only consider rows matching exactly the specific key of\n// interest. Note that because we order by path first, and we\n// order terminators before path separators, we'll encounter all\n// the index rows for documentKey contiguously. In particular, all\n// the rows for documentKey will occur before any rows for\n// documents nested in a subcollection beneath documentKey so we\n// can stop as soon as we hit any such row.\ns===n.userId&&e.path.isEqual(c)?r=r.add(a):o.done();});i.push(u);}),yr.$n(i).next(function(){return n.Qo(t,r);});},t.prototype.Wr=function(t,e){var n=this,r=e.path,i=r.length+1,o=zi.prefixForPath(this.userId,r),s=IDBKeyRange.lowerBound(o),u=new Tt(H);return Di(t).rs({range:s},function(t,e,o){var s=t[0],a=t[1],c=t[2],h=pi(a);s===n.userId&&r.T(h)?// Rows with document keys more than one segment longer than the\n// query path can't be matches. For example, a query on 'rooms'\n// can't match the document /rooms/abc/messages/xyx.\n// TODO(mcg): we'll need a different scanner when we implement\n// ancestor queries.\nh.length===i&&(u=u.add(c)):o.done();}).next(function(){return n.Qo(t,u);});},t.prototype.Qo=function(t,e){var n=this,r=[],i=[];// TODO(rockwood): Implement this using iterate.\nreturn e.forEach(function(e){i.push(Si(t).get(e).next(function(t){if(null===t)throw y();g(t.userId===n.userId),r.push(bi(n.serializer,t));}));}),yr.$n(i).next(function(){return r;});},t.prototype.Wo=function(t,e){var n=this;return Ai(t.jo,this.userId,e).next(function(r){return t.pr(function(){n.Ko(e.batchId);}),yr.forEach(r,function(e){return n.No.Go(t,e);});});},/**\n * Clears the cached keys for a mutation batch. This method should be\n * called by secondary clients after they process mutation updates.\n *\n * Note that this method does not have to be called from primary clients as\n * the corresponding cache entries are cleared when an acknowledged or\n * rejected batch is removed from the mutation queue.\n */ // PORTING NOTE: Multi-tab only\nt.prototype.Ko=function(t){delete this.Fo[t];},t.prototype.zo=function(t){var e=this;return this.$o(t).next(function(n){if(!n)return yr.resolve();// Verify that there are no entries in the documentMutations index if\n// the queue is empty.\nvar r=IDBKeyRange.lowerBound(zi.prefixForUser(e.userId)),i=[];return Di(t).rs({range:r},function(t,n,r){if(t[0]===e.userId){var o=pi(t[1]);i.push(o);}else r.done();}).next(function(){g(0===i.length);});});},t.prototype.Ho=function(t,e){return Ni(t,this.userId,e);},// PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n/** Returns the mutation queue's metadata from IndexedDb. */t.prototype.Yo=function(t){var e=this;return xi(t).get(this.userId).next(function(t){return t||new ji(e.userId,-1,/*lastStreamToken=*/\"\");});},t;}();/**\n * @return true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */function Ni(t,e,n){var r=zi.prefixForPath(e,n.path),i=r[1],o=IDBKeyRange.lowerBound(r),s=!1;return Di(t).rs({range:o,ss:!0},function(t,n,r){var o=t[0],u=t[1];t[2];o===e&&u===i&&(s=!0),r.done();}).next(function(){return s;});}/** Returns true if any mutation queue contains the given document. */ /**\n * Delete a mutation batch and the associated document mutations.\n * @return A PersistencePromise of the document mutations that were removed.\n */function Ai(t,e,n){var r=t.store(Gi.store),i=t.store(zi.store),o=[],s=IDBKeyRange.only(n.batchId),u=0,a=r.rs({range:s},function(t,e,n){return u++,n.delete();});o.push(a.next(function(){g(1===u);}));for(var c=[],h=0,f=n.mutations;h=0&&r<=10);var o=new br(\"createOrUpgrade\",e);n<1&&r>=1&&(function(t){t.createObjectStore(qi.store);}(t),function(t){t.createObjectStore(ji.store,{keyPath:ji.keyPath}),t.createObjectStore(Gi.store,{keyPath:Gi.keyPath,autoIncrement:!0}).createIndex(Gi.userMutationsIndex,Gi.userMutationsKeyPath,{unique:!0}),t.createObjectStore(zi.store);}(t),Ji(t),function(t){t.createObjectStore(Ki.store);}(t));// Migration 2 to populate the targetGlobal object no longer needed since\n// migration 3 unconditionally clears it.\nvar s=yr.resolve();return n<3&&r>=3&&(// Brand new clients don't need to drop and recreate--only clients that\n// potentially have corrupt data.\n0!==n&&(function(t){t.deleteObjectStore(Yi.store),t.deleteObjectStore(Hi.store),t.deleteObjectStore($i.store);}(t),Ji(t)),s=s.next(function(){/**\n * Creates the target global singleton row.\n *\n * @param {IDBTransaction} txn The version upgrade transaction for indexeddb\n */return function(t){var e=t.store($i.store),n=new $i(/*highestTargetId=*/0,/*lastListenSequenceNumber=*/0,st.min().Z(),/*targetCount=*/0);return e.put($i.key,n);}(o);})),n<4&&r>=4&&(0!==n&&(// Schema version 3 uses auto-generated keys to generate globally unique\n// mutation batch IDs (this was previously ensured internally by the\n// client). To migrate to the new schema, we have to read all mutations\n// and write them back out. We preserve the existing batch IDs to guarantee\n// consistency with other object stores. Any further mutation batch IDs will\n// be auto-generated.\ns=s.next(function(){return function(t,e){return e.store(Gi.store).ts().next(function(n){t.deleteObjectStore(Gi.store),t.createObjectStore(Gi.store,{keyPath:Gi.keyPath,autoIncrement:!0}).createIndex(Gi.userMutationsIndex,Gi.userMutationsKeyPath,{unique:!0});var r=e.store(Gi.store),i=n.map(function(t){return r.put(t);});return yr.$n(i);});}(t,o);})),s=s.next(function(){!function(t){t.createObjectStore(Zi.store,{keyPath:Zi.keyPath});}(t);})),n<5&&r>=5&&(s=s.next(function(){return i.removeAcknowledgedMutations(o);})),n<6&&r>=6&&(s=s.next(function(){return function(t){t.createObjectStore(Qi.store);}(t),i.addDocumentGlobal(o);})),n<7&&r>=7&&(s=s.next(function(){return i.ensureSequenceNumbers(o);})),n<8&&r>=8&&(s=s.next(function(){return i.createCollectionParentIndex(t,o);})),n<9&&r>=9&&(s=s.next(function(){// Multi-Tab used to manage its own changelog, but this has been moved\n// to the DbRemoteDocument object store itself. Since the previous change\n// log only contained transient data, we can drop its object store.\n!function(t){t.objectStoreNames.contains(\"remoteDocumentChanges\")&&t.deleteObjectStore(\"remoteDocumentChanges\");}(t),function(t){var e=t.objectStore(Ki.store);e.createIndex(Ki.readTimeIndex,Ki.readTimeIndexPath,{unique:!1}),e.createIndex(Ki.collectionReadTimeIndex,Ki.collectionReadTimeIndexPath,{unique:!1});}(e);})),n<10&&r>=10&&(s=s.next(function(){return i.rewriteCanonicalIds(o);})),s;},t.prototype.addDocumentGlobal=function(t){var e=0;return t.store(Ki.store).rs(function(t,n){e+=Vi(n);}).next(function(){var n=new Qi(e);return t.store(Qi.store).put(Qi.key,n);});},t.prototype.removeAcknowledgedMutations=function(t){var e=this,n=t.store(ji.store),r=t.store(Gi.store);return n.ts().next(function(n){return yr.forEach(n,function(n){var i=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return r.ts(Gi.userMutationsIndex,i).next(function(r){return yr.forEach(r,function(r){g(r.userId===n.userId);var i=bi(e.serializer,r);return Ai(t,n.userId,i).next(function(){});});});});});},/**\n * Ensures that every document in the remote document cache has a corresponding sentinel row\n * with a sequence number. Missing rows are given the most recently used sequence number.\n */t.prototype.ensureSequenceNumbers=function(t){var e=t.store(Yi.store),n=t.store(Ki.store);return t.store($i.store).get($i.key).next(function(t){var r=[];return n.rs(function(n,i){var o=new E(n),s=function(t){return[0,hi(t)];}(o);r.push(e.get(s).next(function(n){return n?yr.resolve():function(n){return e.put(new Yi(0,hi(n),t.highestListenSequenceNumber));}(o);}));}).next(function(){return yr.$n(r);});});},t.prototype.createCollectionParentIndex=function(t,e){// Create the index.\nt.createObjectStore(Xi.store,{keyPath:Xi.keyPath});var n=e.store(Xi.store),r=new Ci(),i=function(t){if(r.add(t)){var e=t._(),i=t.h();return n.put({collectionId:e,parent:hi(i)});}};// Helper to add an index entry iff we haven't already written it.\n// Index existing remote documents.\nreturn e.store(Ki.store).rs({ss:!0},function(t,e){var n=new E(t);return i(n.h());}).next(function(){return e.store(zi.store).rs({ss:!0},function(t,e){t[0];var n=t[1],r=(t[2],pi(n));return i(r.h());});});},t.prototype.rewriteCanonicalIds=function(t){var e=this,n=t.store(Hi.store);return n.rs(function(t,r){var i=Ii(r),o=Ei(e.serializer,i);return n.put(o);});},t;}(),Mi=function(t,e){this.seconds=t,this.nanoseconds=e;},qi=function(t,/** Whether to allow shared access from multiple tabs. */e,n){this.ownerId=t,this.allowTabSynchronization=e,this.leaseTimestampMs=n;};/**\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\n * in indexeddb_schema.ts\n */ /**\n * Name of the IndexedDb object store.\n *\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\n * older clients that only supported single locked access to the persistence\n * layer.\n */qi.store=\"owner\",/**\n * The key string used for the single object that exists in the\n * DbPrimaryClient store.\n */qi.key=\"owner\";var ji=function(/**\n * The normalized user ID to which this queue belongs.\n */t,/**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */e,/**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */n){this.userId=t,this.lastAcknowledgedBatchId=e,this.lastStreamToken=n;};/** Name of the IndexedDb object store. */ji.store=\"mutationQueues\",/** Keys are automatically assigned via the userId property. */ji.keyPath=\"userId\";/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */var Gi=function(/**\n * The normalized user ID to which this batch belongs.\n */t,/**\n * An identifier for this batch, allocated using an auto-generated key.\n */e,/**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */n,/**\n * A list of \"mutations\" that represent a partial base state from when this\n * write batch was initially created. During local application of the write\n * batch, these baseMutations are applied prior to the real writes in order\n * to override certain document fields from the remote document cache. This\n * is necessary in the case of non-idempotent writes (e.g. `increment()`\n * transforms) to make sure that the local view of the modified documents\n * doesn't flicker if the remote document cache receives the result of the\n * non-idempotent write before the write is removed from the queue.\n *\n * These mutations are never sent to the backend.\n */r,/**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via toMutation().\n */i){this.userId=t,this.batchId=e,this.localWriteTimeMs=n,this.baseMutations=r,this.mutations=i;};/** Name of the IndexedDb object store. */Gi.store=\"mutations\",/** Keys are automatically assigned via the userId, batchId properties. */Gi.keyPath=\"batchId\",/** The index name for lookup of mutations by user. */Gi.userMutationsIndex=\"userMutationsIndex\",/** The user mutations index is keyed by [userId, batchId] pairs. */Gi.userMutationsKeyPath=[\"userId\",\"batchId\"];var zi=/** @class */function(){function t(){}/**\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\n * over all of a user's document mutations.\n */return t.prefixForUser=function(t){return[t];},/**\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\n * index to iterate over all at document mutations for a given path or lower.\n */t.prefixForPath=function(t,e){return[t,hi(e)];},/**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */t.key=function(t,e,n){return[t,hi(e),n];},t;}();zi.store=\"documentMutations\",/**\n * Because we store all the useful information for this store in the key,\n * there is no useful information to store as the value. The raw (unencoded)\n * path cannot be stored because IndexedDb doesn't store prototype\n * information.\n */zi.PLACEHOLDER=new zi();var Bi=function(t,e){this.path=t,this.readTime=e;},Wi=function(t,e){this.path=t,this.version=e;},Ki=// TODO: We are currently storing full document keys almost three times\n// (once as part of the primary key, once - partly - as `parentPath` and once\n// inside the encoded documents). During our next migration, we should\n// rewrite the primary key as parentPath + document ID which would allow us\n// to drop one value.\nfunction(/**\n * Set to an instance of DbUnknownDocument if the data for a document is\n * not known, but it is known that a document exists at the specified\n * version (e.g. it had a successful update applied to it)\n */t,/**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */e,/**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */n,/**\n * Documents that were written to the remote document store based on\n * a write acknowledgment are marked with `hasCommittedMutations`. These\n * documents are potentially inconsistent with the backend's copy and use\n * the write's commit version as their document version.\n */r,/**\n * When the document was read from the backend. Undefined for data written\n * prior to schema version 9.\n */i,/**\n * The path of the collection this document is part of. Undefined for data\n * written prior to schema version 9.\n */o){this.unknownDocument=t,this.noDocument=e,this.document=n,this.hasCommittedMutations=r,this.readTime=i,this.parentPath=o;};/**\n * Represents a document that is known to exist but whose data is unknown.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */Ki.store=\"remoteDocuments\",/**\n * An index that provides access to all entries sorted by read time (which\n * corresponds to the last modification time of each row).\n *\n * This index is used to provide a changelog for Multi-Tab.\n */Ki.readTimeIndex=\"readTimeIndex\",Ki.readTimeIndexPath=\"readTime\",/**\n * An index that provides access to documents in a collection sorted by read\n * time.\n *\n * This index is used to allow the RemoteDocumentCache to fetch newly changed\n * documents in a collection.\n */Ki.collectionReadTimeIndex=\"collectionReadTimeIndex\",Ki.collectionReadTimeIndexPath=[\"parentPath\",\"readTime\"];/**\n * Contains a single entry that has metadata about the remote document cache.\n */var Qi=/**\n * @param byteSize Approximately the total size in bytes of all the documents in the document\n * cache.\n */function(t){this.byteSize=t;};Qi.store=\"remoteDocumentGlobal\",Qi.key=\"remoteDocumentGlobalKey\";var Hi=function(/**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */t,/**\n * The canonical string representing this query. This is not unique.\n */e,/**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */n,/**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */r,/**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */i,/**\n * Denotes the maximum snapshot version at which the associated query view\n * contained no limbo documents. Undefined for data written prior to\n * schema version 9.\n */o,/**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */s){this.targetId=t,this.canonicalId=e,this.readTime=n,this.resumeToken=r,this.lastListenSequenceNumber=i,this.lastLimboFreeSnapshotVersion=o,this.query=s;};Hi.store=\"targets\",/** Keys are automatically assigned via the targetId property. */Hi.keyPath=\"targetId\",/** The name of the queryTargets index. */Hi.queryTargetsIndexName=\"queryTargetsIndex\",/**\n * The index of all canonicalIds to the targets that they match. This is not\n * a unique mapping because canonicalId does not promise a unique name for all\n * possible queries, so we append the targetId to make the mapping unique.\n */Hi.queryTargetsKeyPath=[\"canonicalId\",\"targetId\"];/**\n * An object representing an association between a target and a document, or a\n * sentinel row marking the last sequence number at which a document was used.\n * Each document cached must have a corresponding sentinel row before lru\n * garbage collection is enabled.\n *\n * The target associations and sentinel rows are co-located so that orphaned\n * documents and their sequence numbers can be identified efficiently via a scan\n * of this store.\n */var Yi=function(/**\n * The targetId identifying a target or 0 for a sentinel row.\n */t,/**\n * The path to the document, as encoded in the key.\n */e,/**\n * If this is a sentinel row, this should be the sequence number of the last\n * time the document specified by `path` was used. Otherwise, it should be\n * `undefined`.\n */n){this.targetId=t,this.path=e,this.sequenceNumber=n;};/** Name of the IndexedDb object store. */Yi.store=\"targetDocuments\",/** Keys are automatically assigned via the targetId, path properties. */Yi.keyPath=[\"targetId\",\"path\"],/** The index name for the reverse index. */Yi.documentTargetsIndex=\"documentTargetsIndex\",/** We also need to create the reverse index for these properties. */Yi.documentTargetsKeyPath=[\"path\",\"targetId\"];/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */var $i=function(/**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */t,/**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */e,/**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */n,/**\n * The number of targets persisted.\n */r){this.highestTargetId=t,this.highestListenSequenceNumber=e,this.lastRemoteSnapshotVersion=n,this.targetCount=r;};/**\n * The key string used for the single object that exists in the\n * DbTargetGlobal store.\n */$i.key=\"targetGlobalKey\",$i.store=\"targetGlobal\";/**\n * An object representing an association between a Collection id (e.g. 'messages')\n * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection.\n * This is used to efficiently find all collections to query when performing\n * a Collection Group query.\n */var Xi=function(/**\n * The collectionId (e.g. 'messages')\n */t,/**\n * The path to the parent (either a document location or an empty path for\n * a root-level collection).\n */e){this.collectionId=t,this.parent=e;};/** Name of the IndexedDb object store. */function Ji(t){t.createObjectStore(Yi.store,{keyPath:Yi.keyPath}).createIndex(Yi.documentTargetsIndex,Yi.documentTargetsKeyPath,{unique:!0}),// NOTE: This is unique only because the TargetId is the suffix.\nt.createObjectStore(Hi.store,{keyPath:Hi.keyPath}).createIndex(Hi.queryTargetsIndexName,Hi.queryTargetsKeyPath,{unique:!0}),t.createObjectStore($i.store);}Xi.store=\"collectionParents\",/** Keys are automatically assigned via the collectionId, parent properties. */Xi.keyPath=[\"collectionId\",\"parent\"];var Zi=function(// Note: Previous schema versions included a field\n// \"lastProcessedDocumentChangeId\". Don't use anymore.\n/** The auto-generated client id assigned at client startup. */t,/** The last time this state was updated. */e,/** Whether the client's network connection is enabled. */n,/** Whether this client is running in a foreground tab. */r){this.clientId=t,this.updateTimeMs=e,this.networkEnabled=n,this.inForeground=r;};/** Name of the IndexedDb object store. */Zi.store=\"clientMetadata\",/** Keys are automatically assigned via the clientId properties. */Zi.keyPath=\"clientId\";var to=t.__spreadArrays(t.__spreadArrays(t.__spreadArrays([ji.store,Gi.store,zi.store,Ki.store,Hi.store,qi.store,$i.store,Yi.store],[Zi.store]),[Qi.store]),[Xi.store]),eo=/** @class */function(){function t(){/**\n * An in-memory copy of the index entries we've already written since the SDK\n * launched. Used to avoid re-writing the same entry repeatedly.\n *\n * This is *NOT* a complete cache of what's in persistence and so can never be used to\n * satisfy reads.\n */this.la=new Ci();}/**\n * Adds a new entry to the collection parent index.\n *\n * Repeated calls for the same collectionPath should be avoided within a\n * transaction as IndexedDbIndexManager only caches writes once a transaction\n * has been committed.\n */return t.prototype.Mo=function(t,e){var n=this;if(!this.la.has(e)){var r=e._(),i=e.h();t.pr(function(){// Add the collection to the in memory cache only if the transaction was\n// successfully committed.\nn.la.add(e);});var o={collectionId:r,parent:hi(i)};return no(t).put(o);}return yr.resolve();},t.prototype.Qr=function(t,e){var n=[],r=IDBKeyRange.bound([e,\"\"],[$(e),\"\"],/*lowerOpen=*/!1,/*upperOpen=*/!0);return no(t).ts(r).next(function(t){for(var r=0,i=t;ri.highestListenSequenceNumber&&(i.highestListenSequenceNumber=e),r.Ta(t,i);});},t.prototype.Ra=function(t,e){var n=this;return this.ga(t,e).next(function(){return n.ma(t).next(function(r){return r.targetCount+=1,n.Pa(e,r),n.Ta(t,r);});});},t.prototype.ya=function(t,e){return this.ga(t,e);},t.prototype.Va=function(t,e){var n=this;return this.pa(t,e.targetId).next(function(){return oo(t).delete(e.targetId);}).next(function(){return n.ma(t);}).next(function(e){return g(e.targetCount>0),e.targetCount-=1,n.Ta(t,e);});},/**\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n * Returns the number of targets removed.\n */t.prototype.po=function(t,e,n){var r=this,i=0,o=[];return oo(t).rs(function(s,u){var a=Ii(u);a.sequenceNumber<=e&&null===n.get(a.targetId)&&(i++,o.push(r.Va(t,a)));}).next(function(){return yr.$n(o);}).next(function(){return i;});},/**\n * Call provided function with each `TargetData` that we have cached.\n */t.prototype.Ce=function(t,e){return oo(t).rs(function(t,n){var r=Ii(n);e(r);});},t.prototype.ma=function(t){return so(t).get($i.key).next(function(t){return g(null!==t),t;});},t.prototype.Ta=function(t,e){return so(t).put($i.key,e);},t.prototype.ga=function(t,e){return oo(t).put(Ei(this.serializer,e));},/**\n * In-place updates the provided metadata to account for values in the given\n * TargetData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */t.prototype.Pa=function(t,e){var n=!1;return t.targetId>e.highestTargetId&&(e.highestTargetId=t.targetId,n=!0),t.sequenceNumber>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=t.sequenceNumber,n=!0),n;},t.prototype.ba=function(t){return this.ma(t).next(function(t){return t.targetCount;});},t.prototype.va=function(t,e){// Iterating by the canonicalId may yield more than one result because\n// canonicalId values are not required to be unique per target. This query\n// depends on the queryTargets index to be efficient.\nvar n=lt(e),r=IDBKeyRange.bound([n,Number.NEGATIVE_INFINITY],[n,Number.POSITIVE_INFINITY]),i=null;return oo(t).rs({range:r,index:Hi.queryTargetsIndexName},function(t,n,r){var o=Ii(n);// After finding a potential match, check that the target is\n// actually equal to the requested target.\npt(e,o.target)&&(i=o,r.done());}).next(function(){return i;});},t.prototype.Sa=function(t,e,n){var r=this,i=[],o=uo(t);// PORTING NOTE: The reverse index (documentsTargets) is maintained by\n// IndexedDb.\nreturn e.forEach(function(e){var s=hi(e.path);i.push(o.put(new Yi(n,s))),i.push(r.No.Da(t,n,e));}),yr.$n(i);},t.prototype.Ca=function(t,e,n){var r=this,i=uo(t);// PORTING NOTE: The reverse index (documentsTargets) is maintained by\n// IndexedDb.\nreturn yr.forEach(e,function(e){var o=hi(e.path);return yr.$n([i.delete([n,o]),r.No.Na(t,n,e)]);});},t.prototype.pa=function(t,e){var n=uo(t),r=IDBKeyRange.bound([e],[e+1],/*lowerOpen=*/!1,/*upperOpen=*/!0);return n.delete(r);},t.prototype.Fa=function(t,e){var n=IDBKeyRange.bound([e],[e+1],/*lowerOpen=*/!1,/*upperOpen=*/!0),r=uo(t),i=Ot();return r.rs({range:n,ss:!0},function(t,e,n){var r=pi(t[1]),o=new A(r);i=i.add(o);}).next(function(){return i;});},t.prototype.Ho=function(t,e){var n=hi(e.path),r=IDBKeyRange.bound([n],[$(n)],/*lowerOpen=*/!1,/*upperOpen=*/!0),i=0;return uo(t).rs({index:Yi.documentTargetsIndex,ss:!0,range:r},function(t,e,n){var r=t[0];// Having a sentinel row for a document does not count as containing that document;\n// For the target cache, containing the document means the document is part of some\n// target.\nt[1];0!==r&&(i++,n.done());}).next(function(){return i>0;});},/**\n * Looks up a TargetData entry by target ID.\n *\n * @param targetId The target ID of the TargetData entry to look up.\n * @return The cached TargetData entry, or null if the cache has no entry for\n * the target.\n */ // PORTING NOTE: Multi-tab only.\nt.prototype.Ue=function(t,e){return oo(t).get(e).next(function(t){return t?Ii(t):null;});},t;}();/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */function oo(t){return ho.Qn(t,Hi.store);}/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */function so(t){return ho.Qn(t,$i.store);}/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */function uo(t){return ho.Qn(t,Yi.store);}/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */var ao=\"Failed to obtain exclusive access to the persistence layer. To allow shared access, make sure to invoke `enablePersistence()` with `synchronizeTabs:true` in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.\",co=/** @class */function(e){function n(t,n){var r=this;return(r=e.call(this)||this).jo=t,r.xa=n,r;}return t.__extends(n,e),n;}(ei),ho=/** @class */function(){function e(/**\n * Whether to synchronize the in-memory state of multiple tabs and share\n * access to local persistence.\n */t,n,r,i,o,s,u,h,f,/**\n * If set to true, forcefully obtains database access. Existing tabs will\n * no longer be able to access IndexedDB.\n */l){if(this.allowTabSynchronization=t,this.persistenceKey=n,this.clientId=r,this.fn=o,this.window=s,this.document=u,this.$a=f,this.ka=l,this.Ma=null,this.Oa=!1,this.isPrimary=!1,this.networkEnabled=!0,/** Our window.unload handler, if registered. */this.La=null,this.inForeground=!1,/** Our 'visibilitychange' listener if registered. */this.Ba=null,/** The client metadata refresh task. */this.qa=null,/** The last time we garbage collected the client metadata object store. */this.Ua=Number.NEGATIVE_INFINITY,/** A listener to notify on primary state changes. */this.Qa=function(t){return Promise.resolve();},!e.Ln())throw new c(a.UNIMPLEMENTED,\"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.\");this.No=new po(this,i),this.Wa=n+\"main\",this.serializer=new di(h),this.ja=new gr(this.Wa,10,new Fi(this.serializer)),this.Ka=new io(this.No,this.serializer),this.Dr=new eo(),this.vr=function(t,e){return new Li(t,e);}(this.serializer,this.Dr),this.window&&this.window.localStorage?this.Ga=this.window.localStorage:(this.Ga=null,!1===l&&p(\"IndexedDbPersistence\",\"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page.\"));}return e.Qn=function(t,e){if(t instanceof co)return gr.Qn(t.jo,e);throw y();},/**\n * Attempt to start IndexedDb persistence.\n *\n * @return {Promise} Whether persistence was enabled.\n */e.prototype.start=function(){var t=this;// NOTE: This is expected to fail sometimes (in the case of another tab\n// already having the persistence lock), so it's the first thing we should\n// do.\nreturn this.za().then(function(){if(!t.isPrimary&&!t.allowTabSynchronization)// Fail `start()` if `synchronizeTabs` is disabled and we cannot\n// obtain the primary lease.\nthrow new c(a.FAILED_PRECONDITION,ao);return t.Ha(),t.Ya(),t.Ja(),t.runTransaction(\"getHighestListenSequenceNumber\",\"readonly\",function(e){return t.Ka.Ia(e);});}).then(function(e){t.Ma=new qr(e,t.$a);}).then(function(){t.Oa=!0;}).catch(function(e){return t.ja&&t.ja.close(),Promise.reject(e);});},/**\n * Registers a listener that gets called when the primary state of the\n * instance changes. Upon registering, this listener is invoked immediately\n * with the current primary state.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */e.prototype.Xa=function(e){var n=this;return this.Qa=function(r){return t.__awaiter(n,void 0,void 0,function(){return t.__generator(this,function(t){return this.Ei?[2/*return*/,e(r)]:[2/*return*/];});});},e(this.isPrimary);},/**\n * Registers a listener that gets called when the database receives a\n * version change event indicating that it has deleted.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */e.prototype.Za=function(e){var n=this;this.ja.Kn(function(r){return t.__awaiter(n,void 0,void 0,function(){return t.__generator(this,function(t){switch(t.label){case 0:return null===r.newVersion?[4/*yield*/,e()]:[3/*break*/,2];case 1:t.sent(),t.label=2;case 2:return[2/*return*/];}});});});},/**\n * Adjusts the current network state in the client's metadata, potentially\n * affecting the primary lease.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */e.prototype.tc=function(e){var n=this;this.networkEnabled!==e&&(this.networkEnabled=e,// Schedule a primary lease refresh for immediate execution. The eventual\n// lease update will be propagated via `primaryStateListener`.\nthis.fn.ws(function(){return t.__awaiter(n,void 0,void 0,function(){return t.__generator(this,function(t){switch(t.label){case 0:return this.Ei?[4/*yield*/,this.za()]:[3/*break*/,2];case 1:t.sent(),t.label=2;case 2:return[2/*return*/];}});});}));},/**\n * Updates the client metadata in IndexedDb and attempts to either obtain or\n * extend the primary lease for the local client. Asynchronously notifies the\n * primary state listener if the client either newly obtained or released its\n * primary lease.\n */e.prototype.za=function(){var t=this;return this.runTransaction(\"updateClientMetadataAndTryBecomePrimary\",\"readwrite\",function(e){return lo(e).put(new Zi(t.clientId,Date.now(),t.networkEnabled,t.inForeground)).next(function(){if(t.isPrimary)return t.ec(e).next(function(e){e||(t.isPrimary=!1,t.fn.Cs(function(){return t.Qa(!1);}));});}).next(function(){return t.nc(e);}).next(function(n){return t.isPrimary&&!n?t.sc(e).next(function(){return!1;}):!!n&&t.ic(e).next(function(){return!0;});});}).catch(function(e){if(_r(e))// Proceed with the existing state. Any subsequent access to\n// IndexedDB will verify the lease.\nreturn l(\"IndexedDbPersistence\",\"Failed to extend owner lease: \",e),t.isPrimary;if(!t.allowTabSynchronization)throw e;return l(\"IndexedDbPersistence\",\"Releasing owner lease after error during lease refresh\",e),/* isPrimary= */!1;}).then(function(e){t.isPrimary!==e&&t.fn.Cs(function(){return t.Qa(e);}),t.isPrimary=e;});},e.prototype.ec=function(t){var e=this;return fo(t).get(qi.key).next(function(t){return yr.resolve(e.rc(t));});},e.prototype.oc=function(t){return lo(t).delete(this.clientId);},/**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */e.prototype.ac=function(){return t.__awaiter(this,void 0,void 0,function(){var n,r,i,o,s=this;return t.__generator(this,function(t){switch(t.label){case 0:return!this.isPrimary||this.cc(this.Ua,18e5)?[3/*break*/,2]:(this.Ua=Date.now(),[4/*yield*/,this.runTransaction(\"maybeGarbageCollectMultiClientState\",\"readwrite-primary\",function(t){var n=e.Qn(t,Zi.store);return n.ts().next(function(t){var e=s.uc(t,18e5),r=t.filter(function(t){return-1===e.indexOf(t);});// Delete metadata for clients that are no longer considered active.\nreturn yr.forEach(r,function(t){return n.delete(t.clientId);}).next(function(){return r;});});}).catch(function(){return[];})]);case 1:// Delete potential leftover entries that may continue to mark the\n// inactive clients as zombied in LocalStorage.\n// Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n// the client atomically, but we can't. So we opt to delete the IndexedDb\n// entries first to avoid potentially reviving a zombied client.\nif(n=t.sent(),this.Ga)for(r=0,i=n;rn&&(p(\"Detected an update time that is in the future: \"+t+\" > \"+n),1));},e.prototype.Ha=function(){var t=this;null!==this.document&&\"function\"==typeof this.document.addEventListener&&(this.Ba=function(){t.fn.ws(function(){return t.inForeground=\"visible\"===t.document.visibilityState,t.za();});},this.document.addEventListener(\"visibilitychange\",this.Ba),this.inForeground=\"visible\"===this.document.visibilityState);},e.prototype.fc=function(){this.Ba&&(this.document.removeEventListener(\"visibilitychange\",this.Ba),this.Ba=null);},/**\n * Attaches a window.unload handler that will synchronously write our\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n * by tabs trying to acquire the primary lease to determine that the lease\n * is no longer valid even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the\n * primary lease). LocalStorage is used for this rather than IndexedDb because\n * it is a synchronous API and so can be used reliably from an unload\n * handler.\n */e.prototype.Ya=function(){var t,e=this;\"function\"==typeof(null===(t=this.window)||void 0===t?void 0:t.addEventListener)&&(this.La=function(){// Note: In theory, this should be scheduled on the AsyncQueue since it\n// accesses internal state. We execute this code directly during shutdown\n// to make sure it gets a chance to run.\ne._c(),e.fn.ws(function(){return e.Di();});},this.window.addEventListener(\"unload\",this.La));},e.prototype.dc=function(){this.La&&(this.window.removeEventListener(\"unload\",this.La),this.La=null);},/**\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n * Clients become zombied when their tab closes without running all of the\n * cleanup logic in `shutdown()`.\n */e.prototype.lc=function(t){var e;try{var n=null!==(null===(e=this.Ga)||void 0===e?void 0:e.getItem(this.hc(t)));return l(\"IndexedDbPersistence\",\"Client '\"+t+\"' \"+(n?\"is\":\"is not\")+\" zombied in LocalStorage\"),n;}catch(t){// Gracefully handle if LocalStorage isn't working.\nreturn p(\"IndexedDbPersistence\",\"Failed to get zombied client id.\",t),!1;}},/**\n * Record client as zombied (a client that had its tab closed). Zombied\n * clients are ignored during primary tab selection.\n */e.prototype._c=function(){if(this.Ga)try{this.Ga.setItem(this.hc(this.clientId),String(Date.now()));}catch(t){// Gracefully handle if LocalStorage isn't available / working.\np(\"Failed to set zombie client id.\",t);}},/** Removes the zombied client entry if it exists. */e.prototype.wc=function(){if(this.Ga)try{this.Ga.removeItem(this.hc(this.clientId));}catch(t){// Ignore\n}},e.prototype.hc=function(t){return\"firestore_zombie_\"+this.persistenceKey+\"_\"+t;},e;}();/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */ /**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */function fo(t){return ho.Qn(t,qi.store);}/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */function lo(t){return ho.Qn(t,Zi.store);}/** Provides LRU functionality for IndexedDB persistence. */var po=/** @class */function(){function t(t,e){this.db=t,this.wo=new ci(this,e);}return t.prototype.Po=function(t){var e=this.Rc(t);return this.db.Tc().ba(t).next(function(t){return e.next(function(e){return t+e;});});},t.prototype.Rc=function(t){var e=0;return this.Vo(t,function(t){e++;}).next(function(){return e;});},t.prototype.Ce=function(t,e){return this.db.Tc().Ce(t,e);},t.prototype.Vo=function(t,e){return this.gc(t,function(t,n){return e(n);});},t.prototype.Da=function(t,e,n){return vo(t,n);},t.prototype.Na=function(t,e,n){return vo(t,n);},t.prototype.po=function(t,e,n){return this.db.Tc().po(t,e,n);},t.prototype.Go=function(t,e){return vo(t,e);},/**\n * Returns true if anything would prevent this document from being garbage\n * collected, given that the document in question is not present in any\n * targets and has a sequence number less than or equal to the upper bound for\n * the collection run.\n */t.prototype.Pc=function(t,e){return function(t,e){var n=!1;return xi(t).os(function(r){return Ni(t,r,e).next(function(t){return t&&(n=!0),yr.resolve(!t);});}).next(function(){return n;});}(t,e);},t.prototype.bo=function(t,e){var n=this,r=this.db.Ec().ra(),i=[],o=0;return this.gc(t,function(s,u){if(u<=e){var a=n.Pc(t,s).next(function(e){if(!e)// Our size accounting requires us to read all documents before\n// removing them.\nreturn o++,r.Rr(t,s).next(function(){return r.Ar(s),uo(t).delete([0,hi(s.path)]);});});i.push(a);}}).next(function(){return yr.$n(i);}).next(function(){return r.apply(t);}).next(function(){return o;});},t.prototype.removeTarget=function(t,e){var n=e.st(t.xa);return this.db.Tc().ya(t,n);},t.prototype.yc=function(t,e){return vo(t,e);},/**\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n * means not a part of any target, so the only entry in the target-document index for\n * that document will be the sentinel row (targetId 0), which will also have the sequence\n * number for the last time the document was accessed.\n */t.prototype.gc=function(t,e){var n,r=uo(t),i=qr.ai;return r.rs({index:Yi.documentTargetsIndex},function(t,r){var o=t[0],s=(t[1],r.path),u=r.sequenceNumber;0===o?(// if nextToReport is valid, report it, this is a new key so the\n// last one must not be a member of any targets.\ni!==qr.ai&&e(new A(pi(n)),i),// set nextToReport to be this sequence number. It's the next one we\n// might report, if we don't find any targets for this document.\n// Note that the sequence number must be defined when the targetId\n// is 0.\ni=u,n=s):// set nextToReport to be invalid, we know we don't need to report\n// this one since we found a target for it.\ni=qr.ai;}).next(function(){// Since we report sequence numbers after getting to the next key, we\n// need to check if the last key we iterated over was an orphaned\n// document and report it.\ni!==qr.ai&&e(new A(pi(n)),i);});},t.prototype.So=function(t){return this.db.Ec().aa(t);},t;}();function vo(t,e){return uo(t).put(/**\n * @return A value suitable for writing a sentinel row in the target-document\n * store.\n */function(t,e){return new Yi(0,hi(t.path),e);}(e,t.xa));}/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */function yo(t,e){// Use two different prefix formats:\n// * firestore / persistenceKey / projectID . databaseID / ...\n// * firestore / persistenceKey / projectID / ...\n// projectIDs are DNS-compatible names and cannot contain dots\n// so there's no danger of collisions.\nvar n=t.projectId;return t.j||(n+=\".\"+t.database),\"firestore/\"+e+\"/\"+n+\"/\"/**\n * Implements `LocalStore` interface.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */;}var go=/** @class */function(){function t(/** Manages our in-memory or durable persistence. */t,e,n){this.persistence=t,this.Vc=e,/**\n * Maps a targetID to data about its target.\n *\n * PORTING NOTE: We are using an immutable data structure on Web to make re-runs\n * of `applyRemoteEvent()` idempotent.\n */this.bc=new bt(H),/** Maps a target to its targetID. */ // TODO(wuandy): Evaluate if TargetId can be part of Target.\nthis.vc=new it(function(t){return lt(t);},pt),/**\n * The read time of the last entry processed by `getNewDocumentChanges()`.\n *\n * PORTING NOTE: This is only used for multi-tab synchronization.\n */this.Sc=st.min(),this.Sr=t.mc(n),this.Dc=t.Ec(),this.Ka=t.Tc(),this.Cc=new ni(this.Dc,this.Sr,this.persistence.Ic()),this.Vc.Nc(this.Cc);}return t.prototype.Io=function(t){var e=this;return this.persistence.runTransaction(\"Collect garbage\",\"readwrite-primary\",function(n){return t.vo(n,e.bc);});},t;}();/**\n * Acknowledges the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n * + remove the batch from the mutation queue;\n * + apply the changes to the remote document cache;\n * + recalculate the latency compensated view implied by those changes (there\n * may be mutations in the queue that affect the documents but haven't been\n * acknowledged yet); and\n * + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */function mo(t,e){var n=m(t);return n.persistence.runTransaction(\"Acknowledge batch\",\"readwrite-primary\",function(t){var r=e.batch.keys(),i=n.Dc.ra({oa:!0});return function(t,e,n,r){var i=n.batch,o=i.keys(),s=yr.resolve();return o.forEach(function(t){s=s.next(function(){return r.Rr(e,t);}).next(function(e){var o=e,s=n.dr.get(t);g(null!==s),(!o||o.version.L(s)<0)&&(o=i.cr(t,o,n))&&// We use the commitVersion as the readTime rather than the\n// document's updateTime since the updateTime is not advanced\n// for updates that do not modify the underlying document.\nr.Er(o,n._r);});}),s.next(function(){return t.Sr.Wo(e,i);});}(n,t,e,i).next(function(){return i.apply(t);}).next(function(){return n.Sr.zo(t);}).next(function(){return n.Cc.kr(t,r);});});}/**\n * Removes mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */ /**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */function wo(t){var e=m(t);return e.persistence.runTransaction(\"Get last remote snapshot version\",\"readonly\",function(t){return e.Ka.Ea(t);});}/**\n * Updates the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */function _o(t,e){var n=m(t),r=e.nt,i=n.bc;return n.persistence.runTransaction(\"Apply remote event\",\"readwrite-primary\",function(t){var o=n.Dc.ra({oa:!0});// Reset newTargetDataByTargetMap in case this transaction gets re-run.\ni=n.bc;var s=[];e.zt.forEach(function(e,o){var u=i.get(o);if(u){// Only update the remote keys if the target is still active. This\n// ensures that we can persist the updated target data along with\n// the updated assignment.\ns.push(n.Ka.Ca(t,e.se,o).next(function(){return n.Ka.Sa(t,e.ee,o);}));var a=e.resumeToken;// Update the resume token if the change includes one.\nif(a.O()>0){var c=u.it(a,r).st(t.xa);i=i.ot(o,c),// Update the target data if there are target changes (or if\n// sufficient time has passed since the last update).\n/**\n * Returns true if the newTargetData should be persisted during an update of\n * an active target. TargetData should always be persisted when a target is\n * being released and should not call this function.\n *\n * While the target is active, TargetData updates can be omitted when nothing\n * about the target has changed except metadata like the resume token or\n * snapshot version. Occasionally it's worth the extra write to prevent these\n * values from getting too stale after a crash, but this doesn't have to be\n * too frequent.\n */function(t,e,n){// Always persist target data if we don't already have a resume token.\nreturn g(e.resumeToken.O()>0),0===t.resumeToken.O()||// Don't allow resume token changes to be buffered indefinitely. This\n// allows us to be reasonably up-to-date after a crash and avoids needing\n// to loop over all active queries on shutdown. Especially in the browser\n// we may not get time to do anything interesting while the current tab is\n// closing.\ne.nt.X()-t.nt.X()>=3e8||n.ee.size+n.ne.size+n.se.size>0;}(u,c,e)&&s.push(n.Ka.ya(t,c));}}});var u=St(),a=Ot();// HACK: The only reason we allow a null snapshot version is so that we\n// can synthesize remote events when we get permission denied errors while\n// trying to resolve the state of a locally cached document that is in\n// limbo.\nif(e.Yt.forEach(function(t,e){a=a.add(t);}),// Each loop iteration only affects its \"own\" doc, so it's safe to get all the remote\n// documents in advance in a single call.\ns.push(o.getEntries(t,a).next(function(i){e.Yt.forEach(function(a,c){var h=i.get(a);// Note: The order of the steps below is important, since we want\n// to ensure that rejected limbo resolutions (which fabricate\n// NoDocuments with SnapshotVersion.min()) never add documents to\n// cache.\nc instanceof Rn&&c.version.isEqual(st.min())?(// NoDocuments with SnapshotVersion.min() are used in manufactured\n// events. We remove these documents from cache since we lost\n// access.\no.Ar(a,r),u=u.ot(a,c)):null==h||c.version.L(h.version)>0||0===c.version.L(h.version)&&h.hasPendingWrites?(o.Er(c,r),u=u.ot(a,c)):l(\"LocalStore\",\"Ignoring outdated watch update for \",a,\". Current version:\",h.version,\" Watch version:\",c.version),e.Jt.has(a)&&s.push(n.persistence.No.yc(t,a));});})),!r.isEqual(st.min())){var c=n.Ka.Ea(t).next(function(e){return n.Ka.Aa(t,t.xa,r);});s.push(c);}return yr.$n(s).next(function(){return o.apply(t);}).next(function(){return n.Cc.Mr(t,u);});}).then(function(t){return n.bc=i,t;});}/**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */function bo(t,e){var n=m(t);return n.persistence.runTransaction(\"Get next mutation batch\",\"readonly\",function(t){return void 0===e&&(e=-1),n.Sr.Bo(t,e);});}/**\n * Reads the current value of a Document with a given key or null if not\n * found - used for testing.\n */ /**\n * Assigns the given target an internal ID so that its results can be pinned so\n * they don't get GC'd. A target must be allocated in the local store before\n * the store can be used to manage its view.\n *\n * Allocating an already allocated `Target` will return the existing `TargetData`\n * for that `Target`.\n */function Io(t,e){var n=m(t);return n.persistence.runTransaction(\"Allocate target\",\"readwrite\",function(t){var r;return n.Ka.va(t,e).next(function(i){return i?(// This target has been listened to previously, so reuse the\n// previous targetID.\n// TODO(mcg): freshen last accessed date?\nr=i,yr.resolve(r)):n.Ka.wa(t).next(function(i){return r=new gt(e,i,0/* Listen */,t.xa),n.Ka.Ra(t,r).next(function(){return r;});});});}).then(function(t){// If Multi-Tab is enabled, the existing target data may be newer than\n// the in-memory data\nvar r=n.bc.get(t.targetId);return(null===r||t.nt.L(r.nt)>0)&&(n.bc=n.bc.ot(t.targetId,t),n.vc.set(e,t.targetId)),t;});}/**\n * Returns the TargetData as seen by the LocalStore, including updates that may\n * have not yet been persisted to the TargetCache.\n */ // Visible for testing.\n/**\n * Unpins all the documents associated with the given target. If\n * `keepPersistedTargetData` is set to false and Eager GC enabled, the method\n * directly removes the associated target data from the target cache.\n *\n * Releasing a non-existing `Target` is a no-op.\n */ // PORTING NOTE: `keepPersistedTargetData` is multi-tab only.\nfunction Eo(e,n,r){return t.__awaiter(this,void 0,void 0,function(){var i,o,s,u;return t.__generator(this,function(t){switch(t.label){case 0:i=m(e),o=i.bc.get(n),s=r?\"readwrite\":\"readwrite-primary\",t.label=1;case 1:return t.trys.push([1,4,,5]),r?[3/*break*/,3]:[4/*yield*/,i.persistence.runTransaction(\"Release target\",s,function(t){return i.persistence.No.removeTarget(t,o);})];case 2:t.sent(),t.label=3;case 3:return[3/*break*/,5];case 4:if(!_r(u=t.sent()))throw u;// All `releaseTarget` does is record the final metadata state for the\n// target, but we've been recording this periodically during target\n// activity. If we lose this write this could cause a very slight\n// difference in the order of target deletion during GC, but we\n// don't define exact LRU semantics so this is acceptable.\nreturn l(\"LocalStore\",\"Failed to update sequence numbers for target \"+n+\": \"+u),[3/*break*/,5];case 5:return i.bc=i.bc.remove(n),i.vc.delete(o.target),[2/*return*/];}});});}/**\n * Runs the specified query against the local store and returns the results,\n * potentially taking advantage of query data from previous executions (such\n * as the set of remote keys).\n *\n * @param usePreviousResults Whether results from previous executions can\n * be used to optimize this query execution.\n */function To(t,e,n){var r=m(t),i=st.min(),o=Ot();return r.persistence.runTransaction(\"Execute query\",\"readonly\",function(t){return function(t,e,n){var r=m(t),i=r.vc.get(n);return void 0!==i?yr.resolve(r.bc.get(i)):r.Ka.va(e,n);}(r,t,zn(e)).next(function(e){if(e)return i=e.lastLimboFreeSnapshotVersion,r.Ka.Fa(t,e.targetId).next(function(t){o=t;});}).next(function(){return r.Vc.Lr(t,e,n?i:st.min(),n?o:Ot());}).next(function(t){return{documents:t,Fc:o};});});}// PORTING NOTE: Multi-Tab only.\nfunction No(t,e){var n=m(t),r=m(n.Ka),i=n.bc.get(e);return i?Promise.resolve(i.target):n.persistence.runTransaction(\"Get target data\",\"readonly\",function(t){return r.Ue(t,e).next(function(t){return t?t.target:null;});});}/**\n * Returns the set of documents that have been updated since the last call.\n * If this is the first call, returns the set of changes since client\n * initialization. Further invocations will return document that have changed\n * since the prior call.\n */ // PORTING NOTE: Multi-Tab only.\nfunction Ao(t){var e=m(t);return e.persistence.runTransaction(\"Get new document changes\",\"readonly\",function(t){return function(t,e,n){var r=m(t),i=St(),o=gi(n),s=Oi(e),u=IDBKeyRange.lowerBound(o,!0);return s.rs({index:Ki.readTimeIndex,range:u},function(t,e){// Unlike `getEntry()` and others, `getNewDocumentChanges()` parses\n// the documents directly since we want to keep sentinel deletes.\nvar n=vi(r.serializer,e);i=i.ot(n.key,n),o=e.readTime;}).next(function(){return{xc:i,readTime:mi(o)};});}(e.Dc,t,e.Sc);}).then(function(t){var n=t.xc,r=t.readTime;return e.Sc=r,n;});}/**\n * Reads the newest document change from persistence and moves the internal\n * synchronization marker forward so that calls to `getNewDocumentChanges()`\n * only return changes that happened after client initialization.\n */ // PORTING NOTE: Multi-Tab only.\nfunction So(e){return t.__awaiter(this,void 0,void 0,function(){var n;return t.__generator(this,function(t){return[2/*return*/,(n=m(e)).persistence.runTransaction(\"Synchronize last document change read time\",\"readonly\",function(t){return function(t){var e=Oi(t),n=st.min();// If there are no existing entries, we return SnapshotVersion.min().\nreturn e.rs({index:Ki.readTimeIndex,reverse:!0},function(t,e,r){e.readTime&&(n=mi(e.readTime)),r.done();}).next(function(){return n;});}(t);}).then(function(t){n.Sc=t;})];});});}/**\n * Verifies the error thrown by a LocalStore operation. If a LocalStore\n * operation fails because the primary lease has been taken by another client,\n * we ignore the error (the persistence layer will immediately call\n * `applyPrimaryLease` to propagate the primary state change). All other errors\n * are re-thrown.\n *\n * @param err An error returned by a LocalStore operation.\n * @return A Promise that resolves after we recovered, or the original error.\n */function Do(e){return t.__awaiter(this,void 0,void 0,function(){return t.__generator(this,function(t){if(e.code!==a.FAILED_PRECONDITION||e.message!==ti)throw e;return l(\"LocalStore\",\"Unexpectedly lost primary lease\"),[2/*return*/];});});}/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * A collection of references to a document from some kind of numbered entity\n * (either a target ID or batch ID). As references are added to or removed from\n * the set corresponding events are emitted to a registered garbage collector.\n *\n * Each reference is represented by a DocumentReference object. Each of them\n * contains enough information to uniquely identify the reference. They are all\n * stored primarily in a set sorted by key. A document is considered garbage if\n * there's no references in that set (this can be efficiently checked thanks to\n * sorting by key).\n *\n * ReferenceSet also keeps a secondary set that contains references sorted by\n * IDs. This one is used to efficiently implement removal of all references by\n * some target ID.\n */var xo=/** @class */function(){function t(){// A set of outstanding references to a document sorted by key.\nthis.$c=new Tt(Lo.kc),// A set of outstanding references to a document sorted by target id.\nthis.Mc=new Tt(Lo.Oc)/** Returns true if the reference set contains no references. */;}return t.prototype.m=function(){return this.$c.m();},/** Adds a reference to the given document key for the given ID. */t.prototype.Da=function(t,e){var n=new Lo(t,e);this.$c=this.$c.add(n),this.Mc=this.Mc.add(n);},/** Add references to the given document keys for the given ID. */t.prototype.Lc=function(t,e){var n=this;t.forEach(function(t){return n.Da(t,e);});},/**\n * Removes a reference to the given document key for the given\n * ID.\n */t.prototype.Na=function(t,e){this.Bc(new Lo(t,e));},t.prototype.qc=function(t,e){var n=this;t.forEach(function(t){return n.Na(t,e);});},/**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */t.prototype.Uc=function(t){var e=this,n=new A(new E([])),r=new Lo(n,t),i=new Lo(n,t+1),o=[];return this.Mc.Ft([r,i],function(t){e.Bc(t),o.push(t.key);}),o;},t.prototype.Qc=function(){var t=this;this.$c.forEach(function(e){return t.Bc(e);});},t.prototype.Bc=function(t){this.$c=this.$c.delete(t),this.Mc=this.Mc.delete(t);},t.prototype.Wc=function(t){var e=new A(new E([])),n=new Lo(e,t),r=new Lo(e,t+1),i=Ot();return this.Mc.Ft([n,r],function(t){i=i.add(t.key);}),i;},t.prototype.Ho=function(t){var e=new Lo(t,0),n=this.$c.$t(e);return null!==n&&t.isEqual(n.key);},t;}(),Lo=/** @class */function(){function t(t,e){this.key=t,this.jc=e/** Compare by key then by ID */;}return t.kc=function(t,e){return A.i(t.key,e.key)||H(t.jc,e.jc);},/** Compare by ID then by key */t.Oc=function(t,e){return H(t.jc,e.jc)||A.i(t.key,e.key);},t;}(),ko=function(t,e){this.user=e,this.type=\"OAuth\",this.Kc={},// Set the headers using Object Literal notation to avoid minification\nthis.Kc.Authorization=\"Bearer \"+t;},Ro=/** @class */function(){function t(){/**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */this.Gc=null;}return t.prototype.getToken=function(){return Promise.resolve(null);},t.prototype.zc=function(){},t.prototype.Hc=function(t){this.Gc=t,// Fire with initial user.\nt(Mr.UNAUTHENTICATED);},t.prototype.Yc=function(){this.Gc=null;},t;}(),Oo=/** @class */function(){function t(t){var e=this;/**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */this.Jc=null,/** Tracks the current User. */this.currentUser=Mr.UNAUTHENTICATED,this.Xc=!1,/**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */this.Zc=0,/** The listener registered with setChangeListener(). */this.Gc=null,this.forceRefresh=!1,this.Jc=function(){e.Zc++,e.currentUser=e.tu(),e.Xc=!0,e.Gc&&e.Gc(e.currentUser);},this.Zc=0,this.auth=t.getImmediate({optional:!0}),this.auth?this.auth.addAuthTokenListener(this.Jc):(// if auth is not available, invoke tokenListener once with null token\nthis.Jc(null),t.get().then(function(t){e.auth=t,e.Jc&&// tokenListener can be removed by removeChangeListener()\ne.auth.addAuthTokenListener(e.Jc);},function(){}));}return t.prototype.getToken=function(){var t=this,e=this.Zc,n=this.forceRefresh;// Take note of the current value of the tokenCounter so that this method\n// can fail (with an ABORTED error) if there is a token change while the\n// request is outstanding.\nreturn this.forceRefresh=!1,this.auth?this.auth.getToken(n).then(function(n){// Cancel the request since the token changed while the request was\n// outstanding so the response is potentially for a previous user (which\n// user, we can't be sure).\nreturn t.Zc!==e?(l(\"FirebaseCredentialsProvider\",\"getToken aborted due to token change.\"),t.getToken()):n?(g(\"string\"==typeof n.accessToken),new ko(n.accessToken,t.currentUser)):null;}):Promise.resolve(null);},t.prototype.zc=function(){this.forceRefresh=!0;},t.prototype.Hc=function(t){this.Gc=t,// Fire the initial event\nthis.Xc&&t(this.currentUser);},t.prototype.Yc=function(){this.auth&&this.auth.removeAuthTokenListener(this.Jc),this.Jc=null,this.Gc=null;},// Auth.getUid() can return null even with a user logged in. It is because\n// getUid() is synchronous, but the auth code populating Uid is asynchronous.\n// This method should only be called in the AuthTokenListener callback\n// to guarantee to get the actual user.\nt.prototype.tu=function(){var t=this.auth&&this.auth.getUid();return g(null===t||\"string\"==typeof t),new Mr(t);},t;}(),Po=/** @class */function(){function t(t,e){this.eu=t,this.nu=e,this.type=\"FirstParty\",this.user=Mr.ni;}return Object.defineProperty(t.prototype,\"Kc\",{get:function(){var t={\"X-Goog-AuthUser\":this.nu},e=this.eu.auth.getAuthHeaderValueForFirstParty([]);// Use array notation to prevent minification\nreturn e&&(t.Authorization=e),t;},enumerable:!1,configurable:!0}),t;}(),Vo=/** @class */function(){function t(t,e){this.eu=t,this.nu=e;}return t.prototype.getToken=function(){return Promise.resolve(new Po(this.eu,this.nu));},t.prototype.Hc=function(t){// Fire with initial uid.\nt(Mr.ni);},t.prototype.Yc=function(){},t.prototype.zc=function(){},t;}(),Uo=/** @class */function(){function e(t,e,n,r,i,o){this.fn=t,this.su=n,this.iu=r,this.ru=i,this.listener=o,this.state=0/* Initial */,/**\n * A close count that's incremented every time the stream is closed; used by\n * getCloseGuardedDispatcher() to invalidate callbacks that happen after\n * close.\n */this.ou=0,this.au=null,this.stream=null,this.ys=new vr(t,e)/**\n * Returns true if start() has been called and no error has occurred. True\n * indicates the stream is open or in the process of opening (which\n * encompasses respecting backoff, getting auth tokens, and starting the\n * actual RPC). Use isOpen() to determine if the stream is open and ready for\n * outbound requests.\n */;}return e.prototype.cu=function(){return 1/* Starting */===this.state||2/* Open */===this.state||4/* Backoff */===this.state;},/**\n * Returns true if the underlying RPC is open (the onOpen() listener has been\n * called) and the stream is ready for outbound requests.\n */e.prototype.uu=function(){return 2/* Open */===this.state;},/**\n * Starts the RPC. Only allowed if isStarted() returns false. The stream is\n * not immediately ready for use: onOpen() will be invoked when the RPC is\n * ready for outbound requests, at which point isOpen() will return true.\n *\n * When start returns, isStarted() will return true.\n */e.prototype.start=function(){3/* Error */!==this.state?this.auth():this.hu();},/**\n * Stops the RPC. This call is idempotent and allowed regardless of the\n * current isStarted() state.\n *\n * When stop returns, isStarted() and isOpen() will both return false.\n */e.prototype.stop=function(){return t.__awaiter(this,void 0,void 0,function(){return t.__generator(this,function(t){switch(t.label){case 0:return this.cu()?[4/*yield*/,this.close(0/* Initial */)]:[3/*break*/,2];case 1:t.sent(),t.label=2;case 2:return[2/*return*/];}});});},/**\n * After an error the stream will usually back off on the next attempt to\n * start it. If the error warrants an immediate restart of the stream, the\n * sender can use this to indicate that the receiver should not back off.\n *\n * Each error will call the onClose() listener. That function can decide to\n * inhibit backoff if required.\n */e.prototype.lu=function(){this.state=0/* Initial */,this.ys.reset();},/**\n * Marks this stream as idle. If no further actions are performed on the\n * stream for one minute, the stream will automatically close itself and\n * notify the stream's onClose() handler with Status.OK. The stream will then\n * be in a !isStarted() state, requiring the caller to start the stream again\n * before further use.\n *\n * Only streams that are in state 'Open' can be marked idle, as all other\n * states imply pending network operations.\n */e.prototype._u=function(){var t=this;// Starts the idle time if we are in state 'Open' and are not yet already\n// running a timer (in which case the previous idle timeout still applies).\nthis.uu()&&null===this.au&&(this.au=this.fn.yn(this.su,6e4,function(){return t.fu();}));},/** Sends a message to the underlying stream. */e.prototype.du=function(t){this.wu(),this.stream.send(t);},/** Called by the idle timer when the stream should close due to inactivity. */e.prototype.fu=function(){return t.__awaiter(this,void 0,void 0,function(){return t.__generator(this,function(t){return this.uu()?[2/*return*/,this.close(0/* Initial */)]:[2/*return*/];});});},/** Marks the stream as active again. */e.prototype.wu=function(){this.au&&(this.au.cancel(),this.au=null);},/**\n * Closes the stream and cleans up as necessary:\n *\n * * closes the underlying GRPC stream;\n * * calls the onClose handler with the given 'error';\n * * sets internal stream state to 'finalState';\n * * adjusts the backoff timer based on the error\n *\n * A new stream can be opened by calling start().\n *\n * @param finalState the intended state of the stream after closing.\n * @param error the error the connection was closed with.\n */e.prototype.close=function(e,n){return t.__awaiter(this,void 0,void 0,function(){return t.__generator(this,function(t){switch(t.label){case 0:// Notify the listener that the stream closed.\n// Cancel any outstanding timers (they're guaranteed not to execute).\nreturn this.wu(),this.ys.cancel(),// Invalidates any stream-related callbacks (e.g. from auth or the\n// underlying stream), guaranteeing they won't execute.\nthis.ou++,3/* Error */!==e?// If this is an intentional close ensure we don't delay our next connection attempt.\nthis.ys.reset():n&&n.code===a.RESOURCE_EXHAUSTED?(// Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\np(n.toString()),p(\"Using maximum backoff delay to prevent overloading the backend.\"),this.ys.Rn()):n&&n.code===a.UNAUTHENTICATED&&// \"unauthenticated\" error means the token was rejected. Try force refreshing it in case it\n// just expired.\nthis.ru.zc(),// Clean up the underlying stream because we are no longer interested in events.\nnull!==this.stream&&(this.mu(),this.stream.close(),this.stream=null),// This state must be assigned before calling onClose() to allow the callback to\n// inhibit backoff or otherwise manipulate the state in its non-started state.\nthis.state=e,[4/*yield*/,this.listener.Tu(n)];case 1:// Cancel any outstanding timers (they're guaranteed not to execute).\n// Notify the listener that the stream closed.\nreturn t.sent(),[2/*return*/];}});});},/**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */e.prototype.mu=function(){},e.prototype.auth=function(){var t=this;this.state=1/* Starting */;var e=this.Eu(this.ou),n=this.ou;// TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\nthis.ru.getToken().then(function(e){// Stream can be stopped while waiting for authentication.\n// TODO(mikelehen): We really should just use dispatchIfNotClosed\n// and let this dispatch onto the queue, but that opened a spec test can\n// of worms that I don't want to deal with in this PR.\nt.ou===n&&// Normally we'd have to schedule the callback on the AsyncQueue.\n// However, the following calls are safe to be called outside the\n// AsyncQueue since they don't chain asynchronous calls\nt.Iu(e);},function(n){e(function(){var e=new c(a.UNKNOWN,\"Fetching auth token failed: \"+n.message);return t.Au(e);});});},e.prototype.Iu=function(t){var e=this,n=this.Eu(this.ou);this.stream=this.Ru(t),this.stream.gu(function(){n(function(){return e.state=2/* Open */,e.listener.gu();});}),this.stream.Tu(function(t){n(function(){return e.Au(t);});}),this.stream.onMessage(function(t){n(function(){return e.onMessage(t);});});},e.prototype.hu=function(){var e=this;this.state=4/* Backoff */,this.ys.gn(function(){return t.__awaiter(e,void 0,void 0,function(){return t.__generator(this,function(t){return this.state=0/* Initial */,this.start(),[2/*return*/];});});});},// Visible for tests\ne.prototype.Au=function(t){// In theory the stream could close cleanly, however, in our current model\n// we never expect this to happen because if we stop a stream ourselves,\n// this callback will never be called. To prevent cases where we retry\n// without a backoff accidentally, we set the stream to error in all cases.\nreturn l(\"PersistentStream\",\"close with error: \"+t),this.stream=null,this.close(3/* Error */,t);},/**\n * Returns a \"dispatcher\" function that dispatches operations onto the\n * AsyncQueue but only runs them if closeCount remains unchanged. This allows\n * us to turn auth / stream callbacks into no-ops if the stream is closed /\n * re-opened, etc.\n */e.prototype.Eu=function(t){var e=this;return function(n){e.fn.ws(function(){return e.ou===t?n():(l(\"PersistentStream\",\"stream callback skipped by getCloseGuardedDispatcher.\"),Promise.resolve());});};},e;}(),Co=/** @class */function(e){function n(t,n,r,i,o){var s=this;return(s=e.call(this,t,\"listen_stream_connection_backoff\"/* ListenStreamConnectionBackoff */,\"listen_stream_idle\"/* ListenStreamIdle */,n,r,o)||this).serializer=i,s;}return t.__extends(n,e),n.prototype.Ru=function(t){return this.iu.Pu(\"Listen\",t);},n.prototype.onMessage=function(t){// A successful response means the stream is healthy\nthis.ys.reset();var e=function(t,e){var n;if(\"targetChange\"in e){e.targetChange;// proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n// if unset\nvar r=function(t){return\"NO_CHANGE\"===t?0/* NoChange */:\"ADD\"===t?1/* Added */:\"REMOVE\"===t?2/* Removed */:\"CURRENT\"===t?3/* Current */:\"RESET\"===t?4/* Reset */:y();}(e.targetChange.targetChangeType||\"NO_CHANGE\"),i=e.targetChange.targetIds||[],o=function(t,e){return t.Qe?(g(void 0===e||\"string\"==typeof e),X.fromBase64String(e||\"\")):(g(void 0===e||e instanceof Uint8Array),X.fromUint8Array(e||new Uint8Array()));}(t,e.targetChange.resumeToken),s=e.targetChange.cause,u=s&&function(t){var e=void 0===t.code?a.UNKNOWN:_t(t.code);return new c(e,t.message||\"\");}(s);n=new zt(r,i,o,u||null);}else if(\"documentChange\"in e){e.documentChange;var h=e.documentChange;h.document,h.document.name,h.document.updateTime;var f=Se(t,h.document.name),l=Ee(h.document.updateTime),p=new Sn({mapValue:{fields:h.document.fields}}),d=new kn(f,l,p,{}),v=h.targetIds||[],m=h.removedTargetIds||[];n=new jt(v,m,d.key,d);}else if(\"documentDelete\"in e){e.documentDelete;var w=e.documentDelete;w.document;var _=Se(t,w.document),b=w.readTime?Ee(w.readTime):st.min(),I=new Rn(_,b),E=w.removedTargetIds||[];n=new jt([],E,I.key,I);}else if(\"documentRemove\"in e){e.documentRemove;var T=e.documentRemove;T.document;var N=Se(t,T.document),A=T.removedTargetIds||[];n=new jt([],A,N,null);}else{if(!(\"filter\"in e))return y();e.filter;var S=e.filter;S.targetId;var D=S.count||0,x=new mt(D),L=S.targetId;n=new Gt(L,x);}return n;}(this.serializer,t),n=function(t){// We have only reached a consistent snapshot for the entire stream if there\n// is a read_time set and it applies to all targets (i.e. the list of\n// targets is empty). The backend is guaranteed to send such responses.\nif(!(\"targetChange\"in t))return st.min();var e=t.targetChange;return e.targetIds&&e.targetIds.length?st.min():e.readTime?Ee(e.readTime):st.min();}(t);return this.listener.yu(e,n);},/**\n * Registers interest in the results of the given target. If the target\n * includes a resumeToken it will be included in the request. Results that\n * affect the target will be streamed back as WatchChange messages that\n * reference the targetId.\n */n.prototype.Vu=function(t){var e={};e.database=Le(this.serializer),e.addTarget=function(t,e){var n,r=e.target;return(n=dt(r)?{documents:Ve(t,r)}:{query:Ue(t,r)}).targetId=e.targetId,e.resumeToken.O()>0&&(n.resumeToken=be(t,e.resumeToken)),n;}(this.serializer,t);var n=function(t,e){var n=function(t,e){switch(e){case 0/* Listen */:return null;case 1/* ExistenceFilterMismatch */:return\"existence-filter-mismatch\";case 2/* LimboResolution */:return\"limbo-document\";default:return y();}}(0,e.et);return null==n?null:{\"goog-listen-tags\":n};}(this.serializer,t);n&&(e.labels=n),this.du(e);},/**\n * Unregisters interest in the results of the target associated with the\n * given targetId.\n */n.prototype.pu=function(t){var e={};e.database=Le(this.serializer),e.removeTarget=t,this.du(e);},n;}(Uo),Fo=/** @class */function(e){function n(t,n,r,i,o){var s=this;return(s=e.call(this,t,\"write_stream_connection_backoff\"/* WriteStreamConnectionBackoff */,\"write_stream_idle\"/* WriteStreamIdle */,n,r,o)||this).serializer=i,s.bu=!1,s;}return t.__extends(n,e),Object.defineProperty(n.prototype,\"vu\",{/**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */get:function(){return this.bu;},enumerable:!1,configurable:!0}),// Override of PersistentStream.start\nn.prototype.start=function(){this.bu=!1,this.lastStreamToken=void 0,e.prototype.start.call(this);},n.prototype.mu=function(){this.bu&&this.Su([]);},n.prototype.Ru=function(t){return this.iu.Pu(\"Write\",t);},n.prototype.onMessage=function(t){if(// Always capture the last stream token.\ng(!!t.streamToken),this.lastStreamToken=t.streamToken,this.bu){// A successful first write response means the stream is healthy,\n// Note, that we could consider a successful handshake healthy, however,\n// the write itself might be causing an error we want to back off from.\nthis.ys.reset();var e=function(t,e){return t&&t.length>0?(g(void 0!==e),t.map(function(t){return function(t,e){// NOTE: Deletes don't have an updateTime.\nvar n=t.updateTime?Ee(t.updateTime):Ee(e);n.isEqual(st.min())&&(// The Firestore Emulator currently returns an update time of 0 for\n// deletes of non-existing documents (rather than null). This breaks the\n// test \"get deleted doc while offline with source=cache\" as NoDocuments\n// with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n// TODO(#2149): Remove this when Emulator is fixed\nn=Ee(e));var r=null;return t.transformResults&&t.transformResults.length>0&&(r=t.transformResults),new hn(n,r);}(t,e);})):[];}(t.writeResults,t.commitTime),n=Ee(t.commitTime);return this.listener.Du(n,e);}// The first response is always the handshake response\nreturn g(!t.writeResults||0===t.writeResults.length),this.bu=!0,this.listener.Cu();},/**\n * Sends an initial streamToken to the server, performing the handshake\n * required to make the StreamingWrite RPC work. Subsequent\n * calls should wait until onHandshakeComplete was called.\n */n.prototype.Nu=function(){// TODO(dimond): Support stream resumption. We intentionally do not set the\n// stream token on the handshake, ignoring any stream token we might have.\nvar t={};t.database=Le(this.serializer),this.du(t);},/** Sends a group of mutations to the Firestore backend to apply. */n.prototype.Su=function(t){var e=this,n={streamToken:this.lastStreamToken,writes:t.map(function(t){return Oe(e.serializer,t);})};this.du(n);},n;}(Uo),Mo=/** @class */function(e){function n(t,n,r){var i=this;return(i=e.call(this)||this).credentials=t,i.iu=n,i.serializer=r,i.Fu=!1,i;}return t.__extends(n,e),n.prototype.xu=function(){if(this.Fu)throw new c(a.FAILED_PRECONDITION,\"The client has already been terminated.\");},/** Gets an auth token and invokes the provided RPC. */n.prototype.$u=function(t,e,n){var r=this;return this.xu(),this.credentials.getToken().then(function(i){return r.iu.$u(t,e,n,i);}).catch(function(t){throw t.code===a.UNAUTHENTICATED&&r.credentials.zc(),t;});},/** Gets an auth token and invokes the provided RPC with streamed results. */n.prototype.ku=function(t,e,n){var r=this;return this.xu(),this.credentials.getToken().then(function(i){return r.iu.ku(t,e,n,i);}).catch(function(t){throw t.code===a.UNAUTHENTICATED&&r.credentials.zc(),t;});},n.prototype.terminate=function(){this.Fu=!1;},n;}(function(){}),qo=/** @class */function(){function t(t,e){this.cs=t,this.di=e,/** The current OnlineState. */this.state=\"Unknown\"/* Unknown */,/**\n * A count of consecutive failures to open the stream. If it reaches the\n * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\n * Offline.\n */this.Mu=0,/**\n * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\n * transition from OnlineState.Unknown to OnlineState.Offline without waiting\n * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\n */this.Ou=null,/**\n * Whether the client should log a warning message if it fails to connect to\n * the backend (initially true, cleared after a successful stream, or if we've\n * logged the message already).\n */this.Lu=!0/**\n * Called by RemoteStore when a watch stream is started (including on each\n * backoff attempt).\n *\n * If this is the first attempt, it sets the OnlineState to Unknown and starts\n * the onlineStateTimer.\n */;}return t.prototype.Bu=function(){var t=this;0===this.Mu&&(this.qu(\"Unknown\"/* Unknown */),this.Ou=this.cs.yn(\"online_state_timeout\"/* OnlineStateTimeout */,1e4,function(){return t.Ou=null,t.Uu(\"Backend didn't respond within 10 seconds.\"),t.qu(\"Offline\"/* Offline */),Promise.resolve();}));},/**\n * Updates our OnlineState as appropriate after the watch stream reports a\n * failure. The first failure moves us to the 'Unknown' state. We then may\n * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\n * actually transition to the 'Offline' state.\n */t.prototype.Qu=function(t){\"Online\"/* Online */===this.state?this.qu(\"Unknown\"/* Unknown */):(this.Mu++,this.Mu>=1&&(this.Wu(),this.Uu(\"Connection failed 1 times. Most recent error: \"+t.toString()),this.qu(\"Offline\"/* Offline */)));},/**\n * Explicitly sets the OnlineState to the specified state.\n *\n * Note that this resets our timers / failure counters, etc. used by our\n * Offline heuristics, so must not be used in place of\n * handleWatchStreamStart() and handleWatchStreamFailure().\n */t.prototype.set=function(t){this.Wu(),this.Mu=0,\"Online\"/* Online */===t&&(// We've connected to watch at least once. Don't warn the developer\n// about being offline going forward.\nthis.Lu=!1),this.qu(t);},t.prototype.qu=function(t){t!==this.state&&(this.state=t,this.di(t));},t.prototype.Uu=function(t){var e=\"Could not reach Cloud Firestore backend. \"+t+\"\\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.\";this.Lu?(p(e),this.Lu=!1):l(\"OnlineStateTracker\",e);},t.prototype.Wu=function(){null!==this.Ou&&(this.Ou.cancel(),this.Ou=null);},t;}(),jo=function(/**\n * The local store, used to fill the write pipeline with outbound mutations.\n */e,/** The client-side proxy for interacting with the backend. */n,r,i,o){var s=this;this.ju=e,this.Ku=n,this.cs=r,this.Gu={},/**\n * A list of up to MAX_PENDING_WRITES writes that we have fetched from the\n * LocalStore via fillWritePipeline() and have or will send to the write\n * stream.\n *\n * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or\n * restart the write stream. When the stream is established the writes in the\n * pipeline will be sent in order.\n *\n * Writes remain in writePipeline until they are acknowledged by the backend\n * and thus will automatically be re-sent if the stream is interrupted /\n * restarted before they're acknowledged.\n *\n * Write responses from the backend are linked to their originating request\n * purely based on order, and so we can just shift() writes from the front of\n * the writePipeline as we receive responses.\n */this.zu=[],/**\n * A mapping of watched targets that the client cares about tracking and the\n * user has explicitly called a 'listen' for this target.\n *\n * These targets may or may not have been sent to or acknowledged by the\n * server. On re-establishing the listen stream, these targets should be sent\n * to the server. The targets removed with unlistens are removed eagerly\n * without waiting for confirmation from the listen stream.\n */this.Hu=new Map(),/**\n * A set of reasons for why the RemoteStore may be offline. If empty, the\n * RemoteStore may start its network connections.\n */this.Yu=new Set(),/**\n * Event handlers that get called when the network is disabled or enabled.\n *\n * PORTING NOTE: These functions are used on the Web client to create the\n * underlying streams (to support tree-shakeable streams). On Android and iOS,\n * the streams are created during construction of RemoteStore.\n */this.Ju=[],this.Xu=o,this.Xu.Zu(function(e){r.ws(function(){return t.__awaiter(s,void 0,void 0,function(){return t.__generator(this,function(e){switch(e.label){case 0:return Xo(this)?(l(\"RemoteStore\",\"Restarting streams for network reachability change.\"),[4/*yield*/,function(e){return t.__awaiter(this,void 0,void 0,function(){var n;return t.__generator(this,function(t){switch(t.label){case 0:return(n=m(e)).Yu.add(4/* ConnectivityChange */),[4/*yield*/,zo(n)];case 1:return t.sent(),n.th.set(\"Unknown\"/* Unknown */),n.Yu.delete(4/* ConnectivityChange */),[4/*yield*/,Go(n)];case 2:return t.sent(),[2/*return*/];}});});}(this)]):[3/*break*/,2];case 1:e.sent(),e.label=2;case 2:return[2/*return*/];}});});});}),this.th=new qo(r,i);};function Go(e){return t.__awaiter(this,void 0,void 0,function(){var n,r;return t.__generator(this,function(t){switch(t.label){case 0:if(!Xo(e))return[3/*break*/,4];n=0,r=e.Ju,t.label=1;case 1:return n0;}function Xo(t){return 0===m(t).Yu.size;}function Jo(t){t.eh=void 0;}function Zo(e){return t.__awaiter(this,void 0,void 0,function(){return t.__generator(this,function(t){return e.Hu.forEach(function(t,n){Qo(e,t);}),[2/*return*/];});});}function ts(e,n){return t.__awaiter(this,void 0,void 0,function(){return t.__generator(this,function(t){return Jo(e),// If we still need the watch stream, retry the connection.\n$o(e)?(e.th.Qu(n),Yo(e)):// No need to restart watch stream because there are no active targets.\n// The online state is set to unknown because there is no active attempt\n// at establishing a connection\ne.th.set(\"Unknown\"/* Unknown */),[2/*return*/];});});}function es(e,n,r){return t.__awaiter(this,void 0,void 0,function(){var i,o,s;return t.__generator(this,function(u){switch(u.label){case 0:if(e.th.set(\"Online\"/* Online */),!(n instanceof zt&&2/* Removed */===n.state&&n.cause))// Mark the client as online since we got a message from the server\nreturn[3/*break*/,6];u.label=1;case 1:return u.trys.push([1,3,,5]),[4/*yield*/,/** Handles an error on a target */function(e,n){return t.__awaiter(this,void 0,void 0,function(){var r,i,o,s;return t.__generator(this,function(t){switch(t.label){case 0:r=n.cause,i=0,o=n.targetIds,t.label=1;case 1:return i=0?[4/*yield*/,/**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */function(t,e){var n=t.eh.Oe(e);// Update in-memory resume tokens. LocalStore will update the\n// persistent view of these when applying the completed RemoteEvent.\nreturn n.zt.forEach(function(n,r){if(n.resumeToken.O()>0){var i=t.Hu.get(r);// A watched target might have been removed already.\ni&&t.Hu.set(r,i.it(n.resumeToken,e));}}),// Re-establish listens for the targets that have been invalidated by\n// existence filter mismatches.\nn.Ht.forEach(function(e){var n=t.Hu.get(e);if(n){// Clear the resume token for the target, since we're in a known mismatch\n// state.\nt.Hu.set(e,n.it(X.B,n.nt)),// Cause a hard reset by unwatching and rewatching immediately, but\n// deliberately don't send a resume token so that we get a full update.\nHo(t,e);// Mark the target we send as being on behalf of an existence filter\n// mismatch, but don't actually retain that in listenTargets. This ensures\n// that we flag the first re-listen this way without impacting future\n// listens of this target (that might happen e.g. on reconnect).\nvar r=new gt(n.target,e,1/* ExistenceFilterMismatch */,n.sequenceNumber);Qo(t,r);}}),t.Gu.sh(n);}(e,r)]:[3/*break*/,10];// We have received a target change with a global snapshot if the snapshot\n// version is not equal to SnapshotVersion.min().\ncase 9:// We have received a target change with a global snapshot if the snapshot\n// version is not equal to SnapshotVersion.min().\nu.sent(),u.label=10;case 10:return[3/*break*/,13];case 11:return l(\"RemoteStore\",\"Failed to raise snapshot:\",s=u.sent()),[4/*yield*/,ns(e,s)];case 12:return u.sent(),[3/*break*/,13];case 13:return[2/*return*/];}});});}/**\n * Recovery logic for IndexedDB errors that takes the network offline until\n * `op` succeeds. Retries are scheduled with backoff using\n * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is\n * validated via a generic operation.\n *\n * The returned Promise is resolved once the network is disabled and before\n * any retry attempt.\n */function ns(e,n,r){return t.__awaiter(this,void 0,void 0,function(){var i=this;return t.__generator(this,function(o){switch(o.label){case 0:if(!_r(n))throw n;// Disable network and raise offline snapshots\nreturn e.Yu.add(1/* IndexedDbFailed */),[4/*yield*/,zo(e)];case 1:// Disable network and raise offline snapshots\nreturn o.sent(),e.th.set(\"Offline\"/* Offline */),r||(// Use a simple read operation to determine if IndexedDB recovered.\n// Ideally, we would expose a health check directly on SimpleDb, but\n// RemoteStore only has access to persistence through LocalStore.\nr=function(){return wo(e.ju);}),// Probe IndexedDB periodically and re-enable network\ne.cs.Cs(function(){return t.__awaiter(i,void 0,void 0,function(){return t.__generator(this,function(t){switch(t.label){case 0:return l(\"RemoteStore\",\"Retrying IndexedDB access\"),[4/*yield*/,r()];case 1:return t.sent(),e.Yu.delete(1/* IndexedDbFailed */),[4/*yield*/,Go(e)];case 2:return t.sent(),[2/*return*/];}});});}),[2/*return*/];}});});}/**\n * Executes `op`. If `op` fails, takes the network offline until `op`\n * succeeds. Returns after the first attempt.\n */function rs(t,e){return e().catch(function(n){return ns(t,n,e);});}function is(e){return t.__awaiter(this,void 0,void 0,function(){var n,r,i,o,s;return t.__generator(this,function(t){switch(t.label){case 0:n=m(e),r=ps(n),i=n.zu.length>0?n.zu[n.zu.length-1].batchId:-1,t.label=1;case 1:if(!/**\n * Returns true if we can add to the write pipeline (i.e. the network is\n * enabled and the write pipeline is not full).\n */function(t){return Xo(t)&&t.zu.length<10;}/**\n * Queues additional writes to be sent to the write stream, sending them\n * immediately if the write stream is established.\n */(n))return[3/*break*/,7];t.label=2;case 2:return t.trys.push([2,4,,6]),[4/*yield*/,bo(n.ju,i)];case 3:return null===(o=t.sent())?(0===n.zu.length&&r._u(),[3/*break*/,7]):(i=o.batchId,function(t,e){t.zu.push(e);var n=ps(t);n.uu()&&n.vu&&n.Su(e.mutations);}(n,o),[3/*break*/,6]);case 4:return s=t.sent(),[4/*yield*/,ns(n,s)];case 5:return t.sent(),[3/*break*/,6];case 6:return[3/*break*/,1];case 7:return os(n)&&ss(n),[2/*return*/];}});});}function os(t){return Xo(t)&&!ps(t).cu()&&t.zu.length>0;}function ss(t){ps(t).start();}function us(e){return t.__awaiter(this,void 0,void 0,function(){return t.__generator(this,function(t){return ps(e).Nu(),[2/*return*/];});});}function as(e){return t.__awaiter(this,void 0,void 0,function(){var n,r,i,o;return t.__generator(this,function(t){// Send the write pipeline now that the stream is established.\nfor(n=ps(e),r=0,i=e.zu;r0&&(l(\"RemoteStore\",\"Stopping write stream with \"+e.zu.length+\" pending writes\"),e.zu=[]),t.label=4;case 4:return[2/*return*/];}});});})),e.ah/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */;}var ds=function(t){this.key=t;},vs=function(t){this.key=t;},ys=/** @class */function(){function t(t,/** Documents included in the remote target */e){this.query=t,this.uh=e,this.hh=null,/**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */this.te=!1,/** Documents in the view but not in the remote target */this.lh=Ot(),/** Document Keys that have local changes */this.Wt=Ot(),this._h=Xn(t),this.fh=new Ut(this._h);}return Object.defineProperty(t.prototype,\"dh\",{/**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */get:function(){return this.uh;},enumerable:!1,configurable:!0}),/**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges The doc changes to apply to this view.\n * @param previousChanges If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @return a new set of docs, changes, and refill flag.\n */t.prototype.wh=function(t,e){var n=this,r=e?e.mh:new Ct(),i=e?e.fh:this.fh,o=e?e.Wt:this.Wt,s=i,u=!1,a=Cn(this.query)&&i.size===this.query.limit?i.last():null,c=Fn(this.query)&&i.size===this.query.limit?i.first():null;// Drop documents out to meet limit/limitToLast requirement.\nif(t.ht(function(t,e){var h=i.get(t),f=e instanceof kn?e:null;f&&(f=$n(n.query,f)?f:null);var l=!!h&&n.Wt.has(h.key),p=!!f&&(f.Je||// We only consider committed mutations for documents that were\n// mutated during the lifetime of the view.\nn.Wt.has(f.key)&&f.hasCommittedMutations),d=!1;// Calculate change\nh&&f?h.data().isEqual(f.data())?l!==p&&(r.track({type:3/* Metadata */,doc:f}),d=!0):n.Th(h,f)||(r.track({type:2/* Modified */,doc:f}),d=!0,(a&&n._h(f,a)>0||c&&n._h(f,c)<0)&&(// This doc moved from inside the limit to outside the limit.\n// That means there may be some other doc in the local cache\n// that should be included instead.\nu=!0)):!h&&f?(r.track({type:0/* Added */,doc:f}),d=!0):h&&!f&&(r.track({type:1/* Removed */,doc:h}),d=!0,(a||c)&&(// A doc was removed from a full limit query. We'll need to\n// requery from the local cache to see if we know about some other\n// doc that should be in the results.\nu=!0)),d&&(f?(s=s.add(f),o=p?o.add(t):o.delete(t)):(s=s.delete(t),o=o.delete(t)));}),Cn(this.query)||Fn(this.query))for(;s.size>this.query.limit;){var h=Cn(this.query)?s.last():s.first();s=s.delete(h.key),o=o.delete(h.key),r.track({type:1/* Removed */,doc:h});}return{fh:s,mh:r,Eh:u,Wt:o};},t.prototype.Th=function(t,e){// We suppress the initial change event for documents that were modified as\n// part of a write acknowledgment (e.g. when the value of a server transform\n// is applied) as Watch will send us the same document again.\n// By suppressing the event, we only raise two user visible events (one with\n// `hasPendingWrites` and the final state of the document) instead of three\n// (one with `hasPendingWrites`, the modified document with\n// `hasPendingWrites` and the final state of the document).\nreturn t.Je&&e.hasCommittedMutations&&!e.Je;},/**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges The set of changes to make to the view's docs.\n * @param updateLimboDocuments Whether to update limbo documents based on this\n * change.\n * @param targetChange A target change to apply for computing limbo docs and\n * sync state.\n * @return A new ViewChange with the given docs, changes, and sync state.\n */ // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\nt.prototype.yr=function(t,e,n){var r=this,i=this.fh;this.fh=t.fh,this.Wt=t.Wt;// Sort changes based on type and query comparator\nvar o=t.mh.Ut();o.sort(function(t,e){return function(t,e){var n=function(t){switch(t){case 0/* Added */:return 1;case 2/* Modified */:case 3/* Metadata */:// A metadata change is converted to a modified change at the public\n// api layer. Since we sort by document key and then change type,\n// metadata and modified changes must be sorted equivalently.\nreturn 2;case 1/* Removed */:return 0;default:return y();}};return n(t)-n(e);}(t.type,e.type)||r._h(t.doc,e.doc);}),this.Ih(n);var s=e?this.Ah():[],u=0===this.lh.size&&this.te?1/* Synced */:0/* Local */,a=u!==this.hh;return this.hh=u,0!==o.length||a?{snapshot:new Ft(this.query,t.fh,i,o,t.Wt,0/* Local */===u,a,/* excludesMetadataChanges= */!1),Rh:s}:{Rh:s};// no changes\n},/**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */t.prototype.Qs=function(t){return this.te&&\"Offline\"/* Offline */===t?(// If we're offline, set `current` to false and then call applyChanges()\n// to refresh our syncState and generate a ViewChange as appropriate. We\n// are guaranteed to get a new TargetChange that sets `current` back to\n// true once the client is back online.\nthis.te=!1,this.yr({fh:this.fh,mh:new Ct(),Wt:this.Wt,Eh:!1},/* updateLimboDocuments= */!1)):{Rh:[]};},/**\n * Returns whether the doc for the given key should be in limbo.\n */t.prototype.gh=function(t){// If the remote end says it's part of this query, it's not in limbo.\nreturn!this.uh.has(t)&&// The local store doesn't think it's a result, so it shouldn't be in limbo.\n!!this.fh.has(t)&&!this.fh.get(t).Je;},/**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */t.prototype.Ih=function(t){var e=this;t&&(t.ee.forEach(function(t){return e.uh=e.uh.add(t);}),t.ne.forEach(function(t){}),t.se.forEach(function(t){return e.uh=e.uh.delete(t);}),this.te=t.te);},t.prototype.Ah=function(){var t=this;// We can only determine limbo documents when we're in-sync with the server.\nif(!this.te)return[];// TODO(klimt): Do this incrementally so that it's not quadratic when\n// updating many documents.\nvar e=this.lh;this.lh=Ot(),this.fh.forEach(function(e){t.gh(e.key)&&(t.lh=t.lh.add(e.key));});// Diff the new limbo docs with the old limbo docs.\nvar n=[];return e.forEach(function(e){t.lh.has(e)||n.push(new vs(e));}),this.lh.forEach(function(t){e.has(t)||n.push(new ds(t));}),n;},/**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @return The ViewChange that resulted from this synchronization.\n */ // PORTING NOTE: Multi-tab only.\nt.prototype.Ph=function(t){this.uh=t.Fc,this.lh=Ot();var e=this.wh(t.documents);return this.yr(e,/*updateLimboDocuments=*/!0);},/**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */ // PORTING NOTE: Multi-tab only.\nt.prototype.yh=function(){return Ft.Gt(this.query,this.fh,this.Wt,0/* Local */===this.hh);},t;}(),gs=function(/**\n * The query itself.\n */t,/**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */e,/**\n * The view is responsible for computing the final merged truth of what\n * docs are in the query. It gets notified of local and remote changes,\n * and applies the query filters and limits to determine the most correct\n * possible results.\n */n){this.query=t,this.targetId=e,this.view=n;},ms=function(t){this.key=t,/**\n * Set to true once we've received a document. This is used in\n * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to\n * decide whether it needs to manufacture a delete event for the target once\n * the target is CURRENT.\n */this.Vh=!1;},ws=/** @class */function(){function t(t,e,n,// PORTING NOTE: Manages state synchronization in multi-tab environments.\nr,i,o){this.ju=t,this.ph=e,this.bh=n,this.Sh=r,this.currentUser=i,this.Dh=o,this.Ch={},this.Nh=new it(function(t){return Hn(t);},Qn),this.Fh=new Map(),/**\n * The keys of documents that are in limbo for which we haven't yet started a\n * limbo resolution query.\n */this.xh=[],/**\n * Keeps track of the target ID for each document that is in limbo with an\n * active target.\n */this.$h=new bt(A.i),/**\n * Keeps track of the information about an active limbo resolution for each\n * active target ID that was started for the purpose of limbo resolution.\n */this.kh=new Map(),this.Mh=new xo(),/** Stores user completion handlers, indexed by User and BatchId. */this.Oh={},/** Stores user callbacks waiting for all pending writes to be acknowledged. */this.Lh=new Map(),this.Bh=ro.da(),this.onlineState=\"Unknown\"/* Unknown */,// The primary state is set to `true` or `false` immediately after Firestore\n// startup. In the interim, a client should only be considered primary if\n// `isPrimary` is true.\nthis.qh=void 0;}return Object.defineProperty(t.prototype,\"Uh\",{get:function(){return!0===this.qh;},enumerable:!1,configurable:!0}),t;}();/**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the initial snapshot.\n */function _s(e,n){return t.__awaiter(this,void 0,void 0,function(){var r,i,o,s,u,a;return t.__generator(this,function(t){switch(t.label){case 0:return r=Ks(e),(s=r.Nh.get(n))?(// PORTING NOTE: With Multi-Tab Web, it is possible that a query view\n// already exists when EventManager calls us for the first time. This\n// happens when the primary tab is already listening to this query on\n// behalf of another tab and the user of the primary also starts listening\n// to the query. EventManager will not have an assigned target ID in this\n// case and calls `listen` to obtain this ID.\ni=s.targetId,r.Sh.Oi(i),o=s.view.yh(),[3/*break*/,4]):[3/*break*/,1];case 1:return[4/*yield*/,Io(r.ju,zn(n))];case 2:return u=t.sent(),a=r.Sh.Oi(u.targetId),i=u.targetId,[4/*yield*/,bs(r,n,i,\"current\"===a)];case 3:o=t.sent(),r.Uh&&Wo(r.ph,u),t.label=4;case 4:return[2/*return*/,o];}});});}/**\n * Registers a view for a previously unknown query and computes its initial\n * snapshot.\n */function bs(e,n,r,i){return t.__awaiter(this,void 0,void 0,function(){var o,s,u,a,c,h;return t.__generator(this,function(f){switch(f.label){case 0:// PORTING NOTE: On Web only, we inject the code that registers new Limbo\n// targets based on view changes. This allows us to only depend on Limbo\n// changes when user code includes queries.\nreturn e.Qh=function(n,r,i){return function(e,n,r,i){return t.__awaiter(this,void 0,void 0,function(){var o,s,u;return t.__generator(this,function(t){switch(t.label){case 0:return o=n.view.wh(r),o.Eh?[4/*yield*/,To(e.ju,n.query,/* usePreviousResults= */!1).then(function(t){var e=t.documents;return n.view.wh(e,o);})]:[3/*break*/,2];case 1:// The query has a limit and some docs were removed, so we need\n// to re-run the query against the local store to make sure we\n// didn't lose any good docs that had been past the limit.\no=t.sent(),t.label=2;case 2:return s=i&&i.zt.get(n.targetId),u=n.view.yr(o,/* updateLimboDocuments= */e.Uh,s),[2/*return*/,(Rs(e,n.targetId,u.Rh),u.snapshot)];}});});}(e,n,r,i);},[4/*yield*/,To(e.ju,n,/* usePreviousResults= */!0)];case 1:return o=f.sent(),s=new ys(n,o.Fc),u=s.wh(o.documents),a=qt.Zt(r,i&&\"Offline\"/* Offline */!==e.onlineState),c=s.yr(u,/* updateLimboDocuments= */e.Uh,a),Rs(e,r,c.Rh),h=new gs(n,r,s),[2/*return*/,(e.Nh.set(n,h),e.Fh.has(r)?e.Fh.get(r).push(n):e.Fh.set(r,[n]),c.snapshot)];}});});}/** Stops listening to the query. */function Is(e,n){return t.__awaiter(this,void 0,void 0,function(){var r,i,o;return t.__generator(this,function(t){switch(t.label){case 0:return r=m(e),i=r.Nh.get(n),(o=r.Fh.get(i.targetId)).length>1?[2/*return*/,(r.Fh.set(i.targetId,o.filter(function(t){return!Qn(t,n);})),void r.Nh.delete(n))]:r.Uh?(// We need to remove the local query target first to allow us to verify\n// whether any other client is still interested in this target.\nr.Sh.Bi(i.targetId),r.Sh.Fi(i.targetId)?[3/*break*/,2]:[4/*yield*/,Eo(r.ju,i.targetId,/*keepPersistedTargetData=*/!1).then(function(){r.Sh.Ui(i.targetId),Ko(r.ph,i.targetId),Ls(r,i.targetId);}).catch(Do)]):[3/*break*/,3];case 1:t.sent(),t.label=2;case 2:return[3/*break*/,5];case 3:return Ls(r,i.targetId),[4/*yield*/,Eo(r.ju,i.targetId,/*keepPersistedTargetData=*/!0)];case 4:t.sent(),t.label=5;case 5:return[2/*return*/];}});});}/**\n * Initiates the write of local mutation batch which involves adding the\n * writes to the mutation queue, notifying the remote store about new\n * mutations and raising events for any changes this write caused.\n *\n * The promise returned by this call is resolved when the above steps\n * have completed, *not* when the write was acked by the backend. The\n * userCallback is resolved once the write was acked/rejected by the\n * backend (or failed locally for any other reason).\n */ /**\n * Applies one remote event to the sync engine, notifying any views of the\n * changes, and releasing any pending mutation batches that would become\n * visible because of the snapshot version the remote event contains.\n */function Es(e,n){return t.__awaiter(this,void 0,void 0,function(){var r,i;return t.__generator(this,function(t){switch(t.label){case 0:r=m(e),t.label=1;case 1:return t.trys.push([1,4,,6]),[4/*yield*/,_o(r.ju,n)];case 2:return i=t.sent(),// Update `receivedDocument` as appropriate for any limbo targets.\nn.zt.forEach(function(t,e){var n=r.kh.get(e);n&&(// Since this is a limbo resolution lookup, it's for a single document\n// and it could be added, modified, or removed, but not a combination.\ng(t.ee.size+t.ne.size+t.se.size<=1),t.ee.size>0?n.Vh=!0:t.ne.size>0?g(n.Vh):t.se.size>0&&(g(n.Vh),n.Vh=!1));}),[4/*yield*/,Vs(r,i,n)];case 3:// Update `receivedDocument` as appropriate for any limbo targets.\nreturn t.sent(),[3/*break*/,6];case 4:return[4/*yield*/,Do(t.sent())];case 5:return t.sent(),[3/*break*/,6];case 6:return[2/*return*/];}});});}/**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */function Ts(t,e,n){var r=m(t);// If we are the secondary client, we explicitly ignore the remote store's\n// online state (the local client may go offline, even though the primary\n// tab remains online) and only apply the primary tab's online state from\n// SharedClientState.\nif(r.Uh&&0/* RemoteStore */===n||!r.Uh&&1/* SharedClientState */===n){var i=[];r.Nh.forEach(function(t,n){var r=n.view.Qs(e);r.snapshot&&i.push(r.snapshot);}),function(t,e){var n=m(t);n.onlineState=e;var r=!1;n.Bs.forEach(function(t,n){for(var i=0,o=n.listeners;i0&&t.$h.size0);},t.prototype.Hh=function(t,e){return f()<=n.LogLevel.DEBUG&&l(\"IndexFreeQueryEngine\",\"Using full collection scan to execute query:\",Yn(e)),this.zh.Lr(t,e,st.min());},t;}(),Ys=/** @class */function(){function t(t,e){this.Dr=t,this.No=e,/**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */this.Sr=[],/** Next value to use when assigning sequential IDs to each mutation batch. */this.Jh=1,/** An ordered mapping between documents and the mutations batch IDs. */this.Xh=new Tt(Lo.kc);}return t.prototype.$o=function(t){return yr.resolve(0===this.Sr.length);},t.prototype.ko=function(t,e,n,r){var i=this.Jh;this.Jh++,this.Sr.length>0&&this.Sr[this.Sr.length-1];var o=new Xr(i,e,n,r);this.Sr.push(o);// Track references by document key and index collection parents.\nfor(var s=0,u=r;si?this.Sr[i]:null);},t.prototype.qo=function(){return yr.resolve(0===this.Sr.length?-1:this.Jh-1);},t.prototype.Uo=function(t){return yr.resolve(this.Sr.slice());},t.prototype.Nr=function(t,e){var n=this,r=new Lo(e,0),i=new Lo(e,Number.POSITIVE_INFINITY),o=[];return this.Xh.Ft([r,i],function(t){var e=n.Zh(t.jc);o.push(e);}),yr.resolve(o);},t.prototype.Or=function(t,e){var n=this,r=new Tt(H);return e.forEach(function(t){var e=new Lo(t,0),i=new Lo(t,Number.POSITIVE_INFINITY);n.Xh.Ft([e,i],function(t){r=r.add(t.jc);});}),yr.resolve(this.el(r));},t.prototype.Wr=function(t,e){// Use the query path as a prefix for testing if a document matches the\n// query.\nvar n=e.path,r=n.length+1,i=n;// Construct a document reference for actually scanning the index. Unlike\n// the prefix the document key in this reference must have an even number of\n// segments. The empty segment can be used a suffix of the query path\n// because it precedes all other segments in an ordered traversal.\nA.F(i)||(i=i.child(\"\"));var o=new Lo(new A(i),0),s=new Tt(H);// Find unique batchIDs referenced by all documents potentially matching the\n// query.\nreturn this.Xh.xt(function(t){var e=t.key.path;return!!n.T(e)&&(// Rows with document keys more than one segment longer than the query\n// path can't be matches. For example, a query on 'rooms' can't match\n// the document /rooms/abc/messages/xyx.\n// TODO(mcg): we'll need a different scanner when we implement\n// ancestor queries.\ne.length===r&&(s=s.add(t.jc)),!0);},o),yr.resolve(this.el(s));},t.prototype.el=function(t){var e=this,n=[];// Construct an array of matching batches, sorted by batchID to ensure that\n// multiple mutations affecting the same document key are applied in order.\nreturn t.forEach(function(t){var r=e.Zh(t);null!==r&&n.push(r);}),n;},t.prototype.Wo=function(t,e){var n=this;g(0===this.nl(e.batchId,\"removed\")),this.Sr.shift();var r=this.Xh;return yr.forEach(e.mutations,function(i){var o=new Lo(i.key,e.batchId);return r=r.delete(o),n.No.Go(t,i.key);}).next(function(){n.Xh=r;});},t.prototype.Ko=function(t){// No-op since the memory mutation queue does not maintain a separate cache.\n},t.prototype.Ho=function(t,e){var n=new Lo(e,0),r=this.Xh.$t(n);return yr.resolve(e.isEqual(r&&r.key));},t.prototype.zo=function(t){return this.Sr.length,yr.resolve();},/**\n * Finds the index of the given batchId in the mutation queue and asserts that\n * the resulting index is within the bounds of the queue.\n *\n * @param batchId The batchId to search for\n * @param action A description of what the caller is doing, phrased in passive\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n */t.prototype.nl=function(t,e){return this.tl(t);},/**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @return The computed index of the batch with the given batchId, based on\n * the state of the queue. Note this index can be negative if the requested\n * batchId has already been remvoed from the queue or past the end of the\n * queue if the batchId is larger than the last added batch.\n */t.prototype.tl=function(t){return 0===this.Sr.length?0:t-this.Sr[0].batchId;// Examine the front of the queue to figure out the difference between the\n// batchId and indexes in the array. Note that since the queue is ordered\n// by batchId, if the first batch has a larger batchId then the requested\n// batchId doesn't exist in the queue.\n},/**\n * A version of lookupMutationBatch that doesn't return a promise, this makes\n * other functions that uses this code easier to read and more efficent.\n */t.prototype.Zh=function(t){var e=this.tl(t);return e<0||e>=this.Sr.length?null:this.Sr[e];},t;}(),$s=/** @class */function(){/**\n * @param sizer Used to assess the size of a document. For eager GC, this is expected to just\n * return 0 to avoid unnecessarily doing the work of calculating the size.\n */function t(t,e){this.Dr=t,this.sl=e,/** Underlying cache of documents and their read times. */this.docs=new bt(A.i),/** Size of all cached documents. */this.size=0/**\n * Adds the supplied entry to the cache and updates the cache size as appropriate.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */;}return t.prototype.Er=function(t,e,n){var r=e.key,i=this.docs.get(r),o=i?i.size:0,s=this.sl(e);return this.docs=this.docs.ot(r,{ta:e,size:s,readTime:n}),this.size+=s-o,this.Dr.Mo(t,r.path.h());},/**\n * Removes the specified entry from the cache and updates the cache size as appropriate.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */t.prototype.Ar=function(t){var e=this.docs.get(t);e&&(this.docs=this.docs.remove(t),this.size-=e.size);},t.prototype.Rr=function(t,e){var n=this.docs.get(e);return yr.resolve(n?n.ta:null);},t.prototype.getEntries=function(t,e){var n=this,r=Dt();return e.forEach(function(t){var e=n.docs.get(t);r=r.ot(t,e?e.ta:null);}),yr.resolve(r);},t.prototype.Lr=function(t,e,n){for(var r=Lt(),i=new A(e.path.child(\"\")),o=this.docs.ft(i)// Documents are ordered by key, so we can use a prefix scan to narrow down\n// the documents we need to match the query against.\n;o.At();){var s=o.It(),u=s.key,a=s.value,c=a.ta,h=a.readTime;if(!e.path.T(u.path))break;h.L(n)<=0||c instanceof kn&&$n(e,c)&&(r=r.ot(c.key,c));}return yr.resolve(r);},t.prototype.il=function(t,e){return yr.forEach(this.docs,function(t){return e(t);});},t.prototype.ra=function(t){// `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps\n// a separate changelog and does not need special handling for removals.\nreturn new Xs(this);},t.prototype.aa=function(t){return yr.resolve(this.size);},t;}(),Xs=/** @class */function(e){function n(t){var n=this;return(n=e.call(this)||this).ca=t,n;}return t.__extends(n,e),n.prototype.yr=function(t){var e=this,n=[];return this.wr.forEach(function(r,i){i?n.push(e.ca.Er(t,i,e.readTime)):e.ca.Ar(r);}),yr.$n(n);},n.prototype.gr=function(t,e){return this.ca.Rr(t,e);},n.prototype.Pr=function(t,e){return this.ca.getEntries(t,e);},n;}(Zr),Js=/** @class */function(){function t(t){this.persistence=t,/**\n * Maps a target to the data about that target\n */this.rl=new it(function(t){return lt(t);},pt),/** The last received snapshot version. */this.lastRemoteSnapshotVersion=st.min(),/** The highest numbered target ID encountered. */this.highestTargetId=0,/** The highest sequence number encountered. */this.ol=0,/**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */this.al=new xo(),this.targetCount=0,this.cl=ro.fa();}return t.prototype.Ce=function(t,e){return this.rl.forEach(function(t,n){return e(n);}),yr.resolve();},t.prototype.Ea=function(t){return yr.resolve(this.lastRemoteSnapshotVersion);},t.prototype.Ia=function(t){return yr.resolve(this.ol);},t.prototype.wa=function(t){return this.highestTargetId=this.cl.next(),yr.resolve(this.highestTargetId);},t.prototype.Aa=function(t,e,n){return n&&(this.lastRemoteSnapshotVersion=n),e>this.ol&&(this.ol=e),yr.resolve();},t.prototype.ga=function(t){this.rl.set(t.target,t);var e=t.targetId;e>this.highestTargetId&&(this.cl=new ro(e),this.highestTargetId=e),t.sequenceNumber>this.ol&&(this.ol=t.sequenceNumber);},t.prototype.Ra=function(t,e){return this.ga(e),this.targetCount+=1,yr.resolve();},t.prototype.ya=function(t,e){return this.ga(e),yr.resolve();},t.prototype.Va=function(t,e){return this.rl.delete(e.target),this.al.Uc(e.targetId),this.targetCount-=1,yr.resolve();},t.prototype.po=function(t,e,n){var r=this,i=0,o=[];return this.rl.forEach(function(s,u){u.sequenceNumber<=e&&null===n.get(u.targetId)&&(r.rl.delete(s),o.push(r.pa(t,u.targetId)),i++);}),yr.$n(o).next(function(){return i;});},t.prototype.ba=function(t){return yr.resolve(this.targetCount);},t.prototype.va=function(t,e){var n=this.rl.get(e)||null;return yr.resolve(n);},t.prototype.Sa=function(t,e,n){return this.al.Lc(e,n),yr.resolve();},t.prototype.Ca=function(t,e,n){this.al.qc(e,n);var r=this.persistence.No,i=[];return r&&e.forEach(function(e){i.push(r.Go(t,e));}),yr.$n(i);},t.prototype.pa=function(t,e){return this.al.Uc(e),yr.resolve();},t.prototype.Fa=function(t,e){var n=this.al.Wc(e);return yr.resolve(n);},t.prototype.Ho=function(t,e){return yr.resolve(this.al.Ho(e));},t;}(),Zs=/** @class */function(){/**\n * The constructor accepts a factory for creating a reference delegate. This\n * allows both the delegate and this instance to have strong references to\n * each other without having nullable fields that would then need to be\n * checked or asserted on every access.\n */function t(t){var e=this;this.ul={},this.Ma=new qr(0),this.Oa=!1,this.Oa=!0,this.No=t(this),this.Ka=new Js(this),this.Dr=new Ui(),this.vr=function(t,n){return new $s(t,function(t){return e.No.hl(t);});}(this.Dr);}return t.prototype.start=function(){return Promise.resolve();},t.prototype.Di=function(){// No durable state to ensure is closed on shutdown.\nreturn this.Oa=!1,Promise.resolve();},Object.defineProperty(t.prototype,\"Ei\",{get:function(){return this.Oa;},enumerable:!1,configurable:!0}),t.prototype.Za=function(){// No op.\n},t.prototype.tc=function(){// No op.\n},t.prototype.Ic=function(){return this.Dr;},t.prototype.mc=function(t){var e=this.ul[t.ti()];return e||(e=new Ys(this.Dr,this.No),this.ul[t.ti()]=e),e;},t.prototype.Tc=function(){return this.Ka;},t.prototype.Ec=function(){return this.vr;},t.prototype.runTransaction=function(t,e,n){var r=this;l(\"MemoryPersistence\",\"Starting transaction:\",t);var i=new tu(this.Ma.next());return this.No.ll(),n(i).next(function(t){return r.No._l(i).next(function(){return t;});}).Fn().then(function(t){return i.br(),t;});},t.prototype.fl=function(t,e){return yr.kn(Object.values(this.ul).map(function(n){return function(){return n.Ho(t,e);};}));},t;}(),tu=/** @class */function(e){function n(t){var n=this;return(n=e.call(this)||this).xa=t,n;}return t.__extends(n,e),n;}(ei),eu=/** @class */function(){function t(t){this.persistence=t,/** Tracks all documents that are active in Query views. */this.dl=new xo(),/** The list of documents that are potentially GCed after each transaction. */this.wl=null;}return t.ml=function(e){return new t(e);},Object.defineProperty(t.prototype,\"Tl\",{get:function(){if(this.wl)return this.wl;throw y();},enumerable:!1,configurable:!0}),t.prototype.Da=function(t,e,n){return this.dl.Da(n,e),this.Tl.delete(n.toString()),yr.resolve();},t.prototype.Na=function(t,e,n){return this.dl.Na(n,e),this.Tl.add(n.toString()),yr.resolve();},t.prototype.Go=function(t,e){return this.Tl.add(e.toString()),yr.resolve();},t.prototype.removeTarget=function(t,e){var n=this;this.dl.Uc(e.targetId).forEach(function(t){return n.Tl.add(t.toString());});var r=this.persistence.Tc();return r.Fa(t,e.targetId).next(function(t){t.forEach(function(t){return n.Tl.add(t.toString());});}).next(function(){return r.Va(t,e);});},t.prototype.ll=function(){this.wl=new Set();},t.prototype._l=function(t){var e=this,n=this.persistence.Ec().ra();// Remove newly orphaned documents.\nreturn yr.forEach(this.Tl,function(r){var i=A.D(r);return e.El(t,i).next(function(t){t||n.Ar(i);});}).next(function(){return e.wl=null,n.apply(t);});},t.prototype.yc=function(t,e){var n=this;return this.El(t,e).next(function(t){t?n.Tl.delete(e.toString()):n.Tl.add(e.toString());});},t.prototype.hl=function(t){// For eager GC, we don't care about the document size, there are no size thresholds.\nreturn 0;},t.prototype.El=function(t,e){var n=this;return yr.kn([function(){return yr.resolve(n.dl.Ho(e));},function(){return n.persistence.Tc().Ho(t,e);},function(){return n.persistence.fl(t,e);}]);},t;}(),nu=/** @class */function(){function t(t){this.Il=t.Il,this.Al=t.Al;}return t.prototype.gu=function(t){this.Rl=t;},t.prototype.Tu=function(t){this.gl=t;},t.prototype.onMessage=function(t){this.Pl=t;},t.prototype.close=function(){this.Al();},t.prototype.send=function(t){this.Il(t);},t.prototype.yl=function(){this.Rl();},t.prototype.Vl=function(t){this.gl(t);},t.prototype.pl=function(t){this.Pl(t);},t;}(),ru={BatchGetDocuments:\"batchGet\",Commit:\"commit\",RunQuery:\"runQuery\"},iu=/** @class */function(e){function n(t){var n=this;return(n=e.call(this,t)||this).forceLongPolling=t.forceLongPolling,n.W=t.W,n;}/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */return t.__extends(n,e),n.prototype.Nl=function(t,e,n,r){return new Promise(function(o,s){var u=new i.XhrIo();u.listenOnce(i.EventType.COMPLETE,function(){try{switch(u.getLastErrorCode()){case i.ErrorCode.NO_ERROR:var e=u.getResponseJson();l(\"Connection\",\"XHR received:\",JSON.stringify(e)),o(e);break;case i.ErrorCode.TIMEOUT:l(\"Connection\",'RPC \"'+t+'\" timed out'),s(new c(a.DEADLINE_EXCEEDED,\"Request time out\"));break;case i.ErrorCode.HTTP_ERROR:var n=u.getStatus();if(l(\"Connection\",'RPC \"'+t+'\" failed with status:',n,\"response text:\",u.getResponseText()),n>0){var r=u.getResponseJson().error;if(r&&r.status&&r.message){var h=function(t){var e=t.toLowerCase().replace(\"_\",\"-\");return Object.values(a).indexOf(e)>=0?e:a.UNKNOWN;}(r.status);s(new c(h,r.message));}else s(new c(a.UNKNOWN,\"Server responded with status \"+u.getStatus()));}else// If we received an HTTP_ERROR but there's no status code,\n// it's most probably a connection issue\ns(new c(a.UNAVAILABLE,\"Connection failed.\"));break;default:y();}}finally{l(\"Connection\",'RPC \"'+t+'\" completed.');}});var h=JSON.stringify(r);u.send(e,\"POST\",h,n,15);});},n.prototype.Pu=function(t,e){var n=[this.vl,\"/\",\"google.firestore.v1.Firestore\",\"/\",t,\"/channel\"],o=i.createWebChannelTransport(),s={// Required for backend stickiness, routing behavior is based on this\n// parameter.\nhttpSessionIdParam:\"gsessionid\",initMessageHeaders:{},messageUrlParams:{// This param is used to improve routing and project isolation by the\n// backend and must be included in every request.\ndatabase:\"projects/\"+this.U.projectId+\"/databases/\"+this.U.database},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{// Override the default timeout (randomized between 10-20 seconds) since\n// a large write batch on a slow internet connection may take a long\n// time to send to the backend. Rather than have WebChannel impose a\n// tight timeout which could lead to infinite timeouts and retries, we\n// set it very large (5-10 minutes) and rely on the browser's builtin\n// timeouts to kick in if the request isn't working.\nforwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.W};this.Cl(s.initMessageHeaders,e),// Sending the custom headers we just added to request.initMessageHeaders\n// (Authorization, etc.) will trigger the browser to make a CORS preflight\n// request because the XHR will no longer meet the criteria for a \"simple\"\n// CORS request:\n// https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests\n// Therefore to avoid the CORS preflight request (an extra network\n// roundtrip), we use the httpHeadersOverwriteParam option to specify that\n// the headers should instead be encoded into a special \"$httpHeaders\" query\n// parameter, which is recognized by the webchannel backend. This is\n// formally defined here:\n// https://github.com/google/closure-library/blob/b0e1815b13fb92a46d7c9b3c30de5d6a396a3245/closure/goog/net/rpc/httpcors.js#L32\n// TODO(b/145624756): There is a backend bug where $httpHeaders isn't respected if the request\n// doesn't have an Origin header. So we have to exclude a few browser environments that are\n// known to (sometimes) not include an Origin. See\n// https://github.com/firebase/firebase-js-sdk/issues/1491.\nr.isMobileCordova()||r.isReactNative()||r.isElectron()||r.isIE()||r.isUWP()||r.isBrowserExtension()||(s.httpHeadersOverwriteParam=\"$httpHeaders\");var u=n.join(\"\");l(\"Connection\",\"Creating WebChannel: \"+u,s);var h=o.createWebChannel(u,s),f=!1,p=!1,v=new nu({Il:function(t){p?l(\"Connection\",\"Not sending because WebChannel is closed:\",t):(f||(l(\"Connection\",\"Opening WebChannel transport.\"),h.open(),f=!0),l(\"Connection\",\"WebChannel sending:\",t),h.send(t));},Al:function(){return h.close();}}),y=function(t,e){// TODO(dimond): closure typing seems broken because WebChannel does\n// not implement goog.events.Listenable\nh.listen(t,function(t){try{e(t);}catch(t){setTimeout(function(){throw t;},0);}});};// WebChannel supports sending the first message with the handshake - saving\n// a network round trip. However, it will have to call send in the same\n// JS event loop as open. In order to enforce this, we delay actually\n// opening the WebChannel until send is called. Whether we have called\n// open is tracked with this variable.\n// Closure events are guarded and exceptions are swallowed, so catch any\n// exception and rethrow using a setTimeout so they become visible again.\n// Note that eventually this function could go away if we are confident\n// enough the code is exception free.\nreturn y(i.WebChannel.EventType.OPEN,function(){p||l(\"Connection\",\"WebChannel transport opened.\");}),y(i.WebChannel.EventType.CLOSE,function(){p||(p=!0,l(\"Connection\",\"WebChannel transport closed\"),v.Vl());}),y(i.WebChannel.EventType.ERROR,function(t){p||(p=!0,d(\"Connection\",\"WebChannel transport errored:\",t),v.Vl(new c(a.UNAVAILABLE,\"The operation could not be completed\")));}),y(i.WebChannel.EventType.MESSAGE,function(t){var e;if(!p){var n=t.data[0];g(!!n);// TODO(b/35143891): There is a bug in One Platform that caused errors\n// (and only errors) to be wrapped in an extra array. To be forward\n// compatible with the bug we need to check either condition. The latter\n// can be removed once the fix has been rolled out.\n// Use any because msgData.error is not typed.\nvar r=n,i=r.error||(null===(e=r[0])||void 0===e?void 0:e.error);if(i){l(\"Connection\",\"WebChannel received error:\",i);// error.status will be a string like 'OK' or 'NOT_FOUND'.\nvar o=i.status,s=function(t){// lookup by string\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nvar e=vt[t];if(void 0!==e)return _t(e);}(o),u=i.message;void 0===s&&(s=a.INTERNAL,u=\"Unknown error status: \"+o+\" with message \"+i.message),// Mark closed so no further events are propagated\np=!0,v.Vl(new c(s,u)),h.close();}else l(\"Connection\",\"WebChannel received:\",n),v.pl(n);}}),setTimeout(function(){// Technically we could/should wait for the WebChannel opened event,\n// but because we want to send the first message with the WebChannel\n// handshake we pretend the channel opened here (asynchronously), and\n// then delay the actual open until the first message is sent.\nv.yl();},0),v;},n;}(/** @class */function(){function t(t){this.bl=t,this.U=t.U;var e=t.ssl?\"https\":\"http\";this.vl=e+\"://\"+t.host,this.Sl=\"projects/\"+this.U.projectId+\"/databases/\"+this.U.database+\"/documents\";}return t.prototype.$u=function(t,e,n,r){var i=this.Dl(t,e);l(\"RestConnection\",\"Sending: \",i,n);var o={};return this.Cl(o,r),this.Nl(t,i,o,n).then(function(t){return l(\"RestConnection\",\"Received: \",t),t;},function(e){throw d(\"RestConnection\",t+\" failed with error: \",e,\"url: \",i,\"request:\",n),e;});},t.prototype.ku=function(t,e,n,r){// The REST API automatically aggregates all of the streamed results, so we\n// can just use the normal invoke() method.\nreturn this.$u(t,e,n,r);},/**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */t.prototype.Cl=function(t,e){if(t[\"X-Goog-Api-Client\"]=\"gl-js/ fire/7.24.0\",// Content-Type: text/plain will avoid preflight requests which might\n// mess with CORS and redirects by proxies. If we add custom headers\n// we will need to change this code to potentially use the $httpOverwrite\n// parameter supported by ESF to avoid triggering preflight requests.\nt[\"Content-Type\"]=\"text/plain\",e)for(var n in e.Kc)e.Kc.hasOwnProperty(n)&&(t[n]=e.Kc[n]);},t.prototype.Dl=function(t,e){var n=ru[t];return this.vl+\"/v1/\"+e+\":\"+n;},t;}()),ou=/** @class */function(){function t(){var t=this;this.Fl=function(){return t.xl();},this.$l=function(){return t.kl();},this.Ml=[],this.Ol();}return t.prototype.Zu=function(t){this.Ml.push(t);},t.prototype.Di=function(){window.removeEventListener(\"online\",this.Fl),window.removeEventListener(\"offline\",this.$l);},t.prototype.Ol=function(){window.addEventListener(\"online\",this.Fl),window.addEventListener(\"offline\",this.$l);},t.prototype.xl=function(){l(\"ConnectivityMonitor\",\"Network connectivity changed: AVAILABLE\");for(var t=0,e=this.Ml;t90)throw new c(a.INVALID_ARGUMENT,\"Latitude must be a number between -90 and 90, but was: \"+t);if(!isFinite(e)||e<-180||e>180)throw new c(a.INVALID_ARGUMENT,\"Longitude must be a number between -180 and 180, but was: \"+e);this.u_=t,this.h_=e;}return Object.defineProperty(t.prototype,\"latitude\",{/**\n * The latitude of this `GeoPoint` instance.\n */get:function(){return this.u_;},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,\"longitude\",{/**\n * The longitude of this `GeoPoint` instance.\n */get:function(){return this.h_;},enumerable:!1,configurable:!0}),/**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other The `GeoPoint` to compare against.\n * @return true if this `GeoPoint` is equal to the provided one.\n */t.prototype.isEqual=function(t){return this.u_===t.u_&&this.h_===t.h_;},t.prototype.toJSON=function(){return{latitude:this.u_,longitude:this.h_};},/**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */t.prototype.Y=function(t){return H(this.u_,t.u_)||H(this.h_,t.h_);},t;}(),Tu=function(t){this.l_=t;},Nu=/^__.*__$/,Au=function(t,e,n){this.__=t,this.f_=e,this.d_=n;},Su=/** @class */function(){function t(t,e,n){this.data=t,this.We=e,this.fieldTransforms=n;}return t.prototype.w_=function(t,e){var n=[];return null!==this.We?n.push(new _n(t,this.data,this.We,e)):n.push(new wn(t,this.data,e)),this.fieldTransforms.length>0&&n.push(new In(t,this.fieldTransforms)),n;},t;}(),Du=/** @class */function(){function t(t,e,n){this.data=t,this.We=e,this.fieldTransforms=n;}return t.prototype.w_=function(t,e){var n=[new _n(t,this.data,this.We,e)];return this.fieldTransforms.length>0&&n.push(new In(t,this.fieldTransforms)),n;},t;}();function xu(t){switch(t){case 0/* Set */:// fall through\ncase 2/* MergeSet */:// fall through\ncase 1/* Update */:return!0;case 3/* Argument */:case 4/* ArrayArgument */:return!1;default:throw y();}}/** A \"context\" object passed around while parsing user data. */var Lu=/** @class */function(){/**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings The settings for the parser.\n * @param databaseId The database ID of the Firestore instance.\n * @param serializer The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms A mutable list of field transforms encountered while\n * parsing the data.\n * @param fieldMask A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */function t(t,e,n,r,i,o){this.settings=t,this.U=e,this.serializer=n,this.ignoreUndefinedProperties=r,// Minor hack: If fieldTransforms is undefined, we assume this is an\n// external call and we need to validate the entire path.\nvoid 0===i&&this.m_(),this.fieldTransforms=i||[],this.We=o||[];}return Object.defineProperty(t.prototype,\"path\",{get:function(){return this.settings.path;},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,\"s_\",{get:function(){return this.settings.s_;},enumerable:!1,configurable:!0}),/** Returns a new context with the specified settings overwritten. */t.prototype.T_=function(e){return new t(Object.assign(Object.assign({},this.settings),e),this.U,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.We);},t.prototype.E_=function(t){var e,n=null===(e=this.path)||void 0===e?void 0:e.child(t),r=this.T_({path:n,o_:!1});return r.I_(t),r;},t.prototype.A_=function(t){var e,n=null===(e=this.path)||void 0===e?void 0:e.child(t),r=this.T_({path:n,o_:!1});return r.m_(),r;},t.prototype.R_=function(t){// TODO(b/34871131): We don't support array paths right now; so make path\n// undefined.\nreturn this.T_({path:void 0,o_:!0});},t.prototype.i_=function(t){return Gu(t,this.settings.methodName,this.settings.g_||!1,this.path,this.settings.r_);},/** Returns 'true' if 'fieldPath' was traversed when creating this context. */t.prototype.contains=function(t){return void 0!==this.We.find(function(e){return t.T(e);})||void 0!==this.fieldTransforms.find(function(e){return t.T(e.field);});},t.prototype.m_=function(){// TODO(b/34871131): Remove null check once we have proper paths for fields\n// within arrays.\nif(this.path)for(var t=0;t=0;--d)if(!zu(l,u[d])){var v=u[d],y=h[d],g=s.A_(v);if(y instanceof gu||y instanceof Tu&&y.l_ instanceof gu)// Add it to the field mask, but don't add anything to updateData.\nl.push(v);else{var m=Uu(y,g);null!=m&&(l.push(v),p.set(v,m));}}var w=new an(l);return new Du(p.Xe(),w,s.fieldTransforms);}/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */function Vu(t,e,n,r){return void 0===r&&(r=!1),Uu(n,t.P_(r?4/* ArrayArgument */:3/* Argument */,e));}/**\n * Parses user data to Protobuf Values.\n *\n * @param input Data to be parsed.\n * @param context A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @return The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */function Uu(t,e){if(// Unwrap the API type from the Compat SDK. This will return the API type\n// from firestore-exp.\nt instanceof Tu&&(t=t.l_),Fu(t))return Mu(\"Unsupported field value:\",e,t),Cu(t,e);if(t instanceof yu)// FieldValues usually parse into transforms (except FieldValue.delete())\n// in which case we do not want to include this field in our parsed data\n// (as doing so will overwrite the field directly prior to the transform\n// trying to transform it). So we don't add this location to\n// context.fieldMask and we return null as our parsing result.\n/**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */return function(t,e){// Sentinels are only supported with writes, and not within arrays.\nif(!xu(e.s_))throw e.i_(t.e_+\"() can only be used with update() and set()\");if(!e.path)throw e.i_(t.e_+\"() is not currently supported inside arrays\");var n=t.n_(e);n&&e.fieldTransforms.push(n);}(t,e),null;if(// If context.path is null we are inside an array and we don't support\n// field mask paths more granular than the top-level array.\ne.path&&e.We.push(e.path),t instanceof Array){// TODO(b/34871131): Include the path containing the array in the error\n// message.\n// In the case of IN queries, the parsed data is an array (representing\n// the set of values to be included for the IN query) that may directly\n// contain additional arrays (each representing an individual field\n// value), so we disable this validation.\nif(e.settings.o_&&4/* ArrayArgument */!==e.s_)throw e.i_(\"Nested arrays are not supported\");return function(t,e){for(var n=[],r=0,i=0,o=t;i0&&e.We.push(e.path):_(t,function(t,r){var i=Uu(r,e.E_(t));null!=i&&(n[t]=i);}),{mapValue:{fields:n}};}function Fu(t){return!(\"object\"!=typeof t||null===t||t instanceof Array||t instanceof Date||t instanceof ot||t instanceof Eu||t instanceof J||t instanceof Au||t instanceof yu);}function Mu(t,e,n){if(!Fu(n)||!F(n)){var r=M(n);throw\"an object\"===r?e.i_(t+\" a custom object\"):e.i_(t+\" \"+r);}}/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */function qu(t,e,n){if(e instanceof pu)return e.t_;if(\"string\"==typeof e)return ju(t,e);throw Gu(\"Field path arguments must be of type string or FieldPath.\",t,/* hasConverter= */!1,/* path= */void 0,n);}/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName The publicly visible method name\n * @param path The dot-separated string form of a field path which will be split\n * on dots.\n * @param targetDoc The document against which the field path will be evaluated.\n */function ju(e,n,r){try{return function(e){if(e.search(vu)>=0)throw new c(a.INVALID_ARGUMENT,\"Invalid field path (\"+e+\"). Paths must not contain '~', '*', '/', '[', or ']'\");try{return new(du.bind.apply(du,t.__spreadArrays([void 0],e.split(\".\"))))();}catch(t){throw new c(a.INVALID_ARGUMENT,\"Invalid field path (\"+e+\"). Paths must not be empty, begin with '.', end with '.', or contain '..'\");}}(n).t_;}catch(n){throw Gu((i=n)instanceof Error?i.message:i.toString(),e,/* hasConverter= */!1,/* path= */void 0,r);}/**\n * Extracts the message from a caught exception, which should be an Error object\n * though JS doesn't guarantee that.\n */var i;/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */}function Gu(t,e,n,r,i){var o=r&&!r.m(),s=void 0!==i,u=\"Function \"+e+\"() called with invalid data\";n&&(u+=\" (via `toFirestore()`)\");var h=\"\";return(o||s)&&(h+=\" (found\",o&&(h+=\" in field \"+r),s&&(h+=\" in document \"+i),h+=\")\"),new c(a.INVALID_ARGUMENT,(u+=\". \")+t+h);}function zu(t,e){return t.some(function(t){return t.isEqual(e);});}/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */var Bu=/** @class */function(){function e(t){this.Ku=t,// The version of each document that was read during this transaction.\nthis.y_=new Map(),this.mutations=[],this.V_=!1,/**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */this.p_=null,/**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */this.b_=new Set();}return e.prototype.v_=function(e){return t.__awaiter(this,void 0,void 0,function(){var n,r=this;return t.__generator(this,function(i){switch(i.label){case 0:if(this.S_(),this.mutations.length>0)throw new c(a.INVALID_ARGUMENT,\"Firestore transactions require all reads to be executed before all writes.\");return[4/*yield*/,function(e,n){return t.__awaiter(this,void 0,void 0,function(){var r,i,o,s,u,a;return t.__generator(this,function(t){switch(t.label){case 0:return r=m(e),i=Le(r.serializer)+\"/documents\",o={documents:n.map(function(t){return Ae(r.serializer,t);})},[4/*yield*/,r.ku(\"BatchGetDocuments\",i,o)];case 1:return s=t.sent(),u=new Map(),s.forEach(function(t){var e=function(t,e){return\"found\"in e?function(t,e){g(!!e.found),e.found.name,e.found.updateTime;var n=Se(t,e.found.name),r=Ee(e.found.updateTime),i=new Sn({mapValue:{fields:e.found.fields}});return new kn(n,r,i,{});}(t,e):\"missing\"in e?function(t,e){g(!!e.missing),g(!!e.readTime);var n=Se(t,e.missing),r=Ee(e.readTime);return new Rn(n,r);}(t,e):y();}(r.serializer,t);u.set(e.key.toString(),e);}),a=[],[2/*return*/,(n.forEach(function(t){var e=u.get(t.toString());g(!!e),a.push(e);}),a)];}});});}(this.Ku,e)];case 1:return[2/*return*/,((n=i.sent()).forEach(function(t){t instanceof Rn||t instanceof kn?r.D_(t):y();}),n)];}});});},e.prototype.set=function(t,e){this.write(e.w_(t,this.Ge(t))),this.b_.add(t.toString());},e.prototype.update=function(t,e){try{this.write(e.w_(t,this.C_(t)));}catch(t){this.p_=t;}this.b_.add(t.toString());},e.prototype.delete=function(t){this.write([new Nn(t,this.Ge(t))]),this.b_.add(t.toString());},e.prototype.commit=function(){return t.__awaiter(this,void 0,void 0,function(){var e,n=this;return t.__generator(this,function(r){switch(r.label){case 0:if(this.S_(),this.p_)throw this.p_;return e=this.y_,// For each mutation, note that the doc was written.\nthis.mutations.forEach(function(t){e.delete(t.key.toString());}),// For each document that was read but not written to, we want to perform\n// a `verify` operation.\ne.forEach(function(t,e){var r=A.D(e);n.mutations.push(new An(r,n.Ge(r)));}),[4/*yield*/,function(e,n){return t.__awaiter(this,void 0,void 0,function(){var r,i,o;return t.__generator(this,function(t){switch(t.label){case 0:return r=m(e),i=Le(r.serializer)+\"/documents\",o={writes:n.map(function(t){return Oe(r.serializer,t);})},[4/*yield*/,r.$u(\"Commit\",i,o)];case 1:return t.sent(),[2/*return*/];}});});}(this.Ku,this.mutations)];case 1:// For each mutation, note that the doc was written.\nreturn r.sent(),this.V_=!0,[2/*return*/];}});});},e.prototype.D_=function(t){var e;if(t instanceof kn)e=t.version;else{if(!(t instanceof Rn))throw y();// For deleted docs, we must use baseVersion 0 when we overwrite them.\ne=st.min();}var n=this.y_.get(t.key.toString());if(n){if(!e.isEqual(n))// This transaction will fail no matter what.\nthrow new c(a.ABORTED,\"Document version changed between two reads.\");}else this.y_.set(t.key.toString(),e);},/**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */e.prototype.Ge=function(t){var e=this.y_.get(t.toString());return!this.b_.has(t.toString())&&e?fn.updateTime(e):fn.ze();},/**\n * Returns the precondition for a document if the operation is an update.\n */e.prototype.C_=function(t){var e=this.y_.get(t.toString());// The first time a document is written, we want to take into account the\n// read time and existence\nif(!this.b_.has(t.toString())&&e){if(e.isEqual(st.min()))// The document doesn't exist, so fail the transaction.\n// This has to be validated locally because you can't send a\n// precondition that a document does not exist without changing the\n// semantics of the backend write to be an insert. This is the reverse\n// of what we want, since we want to assert that the document doesn't\n// exist but then send the update and have it fail. Since we can't\n// express that to the backend, we have to validate locally.\n// Note: this can change once we can send separate verify writes in the\n// transaction.\nthrow new c(a.INVALID_ARGUMENT,\"Can't update a document that doesn't exist.\");// Document exists, base precondition on document update time.\nreturn fn.updateTime(e);}// Document was not read, so we just use the preconditions for a blind\n// update.\nreturn fn.exists(!0);},e.prototype.write=function(t){this.S_(),this.mutations=this.mutations.concat(t);},e.prototype.S_=function(){},e;}(),Wu=/** @class */function(){function e(t,e,n,r){this.cs=t,this.Ku=e,this.updateFunction=n,this.ls=r,this.N_=5,this.ys=new vr(this.cs,\"transaction_retry\"/* TransactionRetry */)/** Runs the transaction and sets the result on deferred. */;}return e.prototype.run=function(){this.F_();},e.prototype.F_=function(){var e=this;this.ys.gn(function(){return t.__awaiter(e,void 0,void 0,function(){var e,n,r=this;return t.__generator(this,function(t){return e=new Bu(this.Ku),(n=this.x_(e))&&n.then(function(t){r.cs.ws(function(){return e.commit().then(function(){r.ls.resolve(t);}).catch(function(t){r.k_(t);});});}).catch(function(t){r.k_(t);}),[2/*return*/];});});});},e.prototype.x_=function(t){try{var e=this.updateFunction(t);return!ut(e)&&e.catch&&e.then?e:(this.ls.reject(Error(\"Transaction callback must return a Promise\")),null);}catch(t){// Do not retry errors thrown by user provided updateFunction.\nreturn this.ls.reject(t),null;}},e.prototype.k_=function(t){var e=this;this.N_>0&&this.M_(t)?(this.N_-=1,this.cs.ws(function(){return e.F_(),Promise.resolve();})):this.ls.reject(t);},e.prototype.M_=function(t){if(\"FirebaseError\"===t.name){// In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n// non-matching document versions with ABORTED. These errors should be retried.\nvar e=t.code;return\"aborted\"===e||\"failed-precondition\"===e||!wt(e);}return!1;},e;}(),Ku=/** @class */function(){function e(t,/**\n * Asynchronous queue responsible for all of our internal processing. When\n * we get incoming work from the user (via public API) or the network\n * (incoming GRPC messages), we should always schedule onto this queue.\n * This ensures all of our work is properly serialized (e.g. we don't\n * start processing a new operation while the previous one is waiting for\n * an async I/O to complete).\n */e){this.credentials=t,this.cs=e,this.clientId=Q.k(),// We defer our initialization until we get the current user from\n// setChangeListener(). We block the async queue until we got the initial\n// user and the initialization is completed. This will prevent any scheduled\n// work from happening before initialization is completed.\n// If initializationDone resolved then the FirestoreClient is in a usable\n// state.\nthis.O_=new dr()/**\n * Starts up the FirestoreClient, returning only whether or not enabling\n * persistence succeeded.\n *\n * The intent here is to \"do the right thing\" as far as users are concerned.\n * Namely, in cases where offline persistence is requested and possible,\n * enable it, but otherwise fall back to persistence disabled. For the most\n * part we expect this to succeed one way or the other so we don't expect our\n * users to actually wait on the firestore.enablePersistence Promise since\n * they generally won't care.\n *\n * Of course some users actually do care about whether or not persistence\n * was successfully enabled, so the Promise returned from this method\n * indicates this outcome.\n *\n * This presents a problem though: even before enablePersistence resolves or\n * rejects, users may have made calls to e.g. firestore.collection() which\n * means that the FirestoreClient in there will be available and will be\n * enqueuing actions on the async queue.\n *\n * Meanwhile any failure of an operation on the async queue causes it to\n * panic and reject any further work, on the premise that unhandled errors\n * are fatal.\n *\n * Consequently the fallback is handled internally here in start, and if the\n * fallback succeeds we signal success to the async queue even though the\n * start() itself signals failure.\n *\n * @param databaseInfo The connection information for the current instance.\n * @param offlineComponentProvider Provider that returns all components\n * required for memory-only or IndexedDB persistence.\n * @param onlineComponentProvider Provider that returns all components\n * required for online support.\n * @param persistenceSettings Settings object to configure offline\n * persistence.\n * @returns A deferred result indicating the user-visible result of enabling\n * offline persistence. This method will reject this if IndexedDB fails to\n * start for any reason. If usePersistence is false this is\n * unconditionally resolved.\n */;}return e.prototype.start=function(e,n,r,i){var o=this;this.L_(),this.bl=e;// If usePersistence is true, certain classes of errors while starting are\n// recoverable but only by falling back to persistence disabled.\n// If there's an error in the first case but not in recovery we cannot\n// reject the promise blocking the async queue because this will cause the\n// async queue to panic.\nvar s=new dr(),u=!1;// Return only the result of enabling persistence. Note that this does not\n// need to await the completion of initializationDone because the result of\n// this method should not reflect any other kind of failure to start.\nreturn this.credentials.Hc(function(e){if(!u)return u=!0,l(\"FirestoreClient\",\"Initializing. user=\",e.uid),o.B_(n,r,i,e,s).then(o.O_.resolve,o.O_.reject);o.cs.Cs(function(){return function(e,n){return t.__awaiter(this,void 0,void 0,function(){var r,i;return t.__generator(this,function(t){switch(t.label){case 0:return(r=m(e)).cs.xs(),l(\"RemoteStore\",\"RemoteStore received new credentials\"),i=Xo(r),// Tear down and re-create our network streams. This will ensure we get a\n// fresh auth token for the new user and re-fill the write pipeline with\n// new mutations from the LocalStore (since mutations are per-user).\nr.Yu.add(3/* CredentialChange */),[4/*yield*/,zo(r)];case 1:return t.sent(),i&&// Don't set the network status to Unknown if we are offline.\nr.th.set(\"Unknown\"/* Unknown */),[4/*yield*/,r.Gu.Jl(n)];case 2:return t.sent(),r.Yu.delete(3/* CredentialChange */),[4/*yield*/,Go(r)];case 3:// Tear down and re-create our network streams. This will ensure we get a\n// fresh auth token for the new user and re-fill the write pipeline with\n// new mutations from the LocalStore (since mutations are per-user).\nreturn t.sent(),[2/*return*/];}});});}(o.ph,e);});}),// Block the async queue until initialization is done\nthis.cs.ws(function(){return o.O_.promise;}),s.promise;},/** Enables the network connection and requeues all pending operations. */e.prototype.enableNetwork=function(){var t=this;return this.L_(),this.cs.enqueue(function(){return t.persistence.tc(!0),function(t){var e=m(t);return e.Yu.delete(0/* UserDisabled */),Go(e);}(t.ph);});},/**\n * Initializes persistent storage, attempting to use IndexedDB if\n * usePersistence is true or memory-only if false.\n *\n * If IndexedDB fails because it's already open in another tab or because the\n * platform can't possibly support our implementation then this method rejects\n * the persistenceResult and falls back on memory-only persistence.\n *\n * @param offlineComponentProvider Provider that returns all components\n * required for memory-only or IndexedDB persistence.\n * @param onlineComponentProvider Provider that returns all components\n * required for online support.\n * @param persistenceSettings Settings object to configure offline persistence\n * @param user The initial user\n * @param persistenceResult A deferred result indicating the user-visible\n * result of enabling offline persistence. This method will reject this if\n * IndexedDB fails to start for any reason. If usePersistence is false\n * this is unconditionally resolved.\n * @returns a Promise indicating whether or not initialization should\n * continue, i.e. that one of the persistence implementations actually\n * succeeded.\n */e.prototype.B_=function(e,n,r,i,o){return t.__awaiter(this,void 0,void 0,function(){var s,u,a=this;return t.__generator(this,function(c){switch(c.label){case 0:return c.trys.push([0,3,,4]),s={cs:this.cs,bl:this.bl,clientId:this.clientId,credentials:this.credentials,Wl:i,Dh:100,persistenceSettings:r},[4/*yield*/,e.initialize(s)];case 1:return c.sent(),[4/*yield*/,n.initialize(e,s)];case 2:return c.sent(),this.persistence=e.persistence,this.Sh=e.Sh,this.ju=e.ju,this.ql=e.ql,this.Ku=n.Ku,this.ph=n.ph,this.fi=n.fi,this.q_=n.bh,this.q_.Us=_s.bind(null,this.fi),this.q_.js=Is.bind(null,this.fi),// When a user calls clearPersistence() in one client, all other clients\n// need to be terminated to allow the delete to succeed.\nthis.persistence.Za(function(){return t.__awaiter(a,void 0,void 0,function(){return t.__generator(this,function(t){switch(t.label){case 0:return[4/*yield*/,this.terminate()];case 1:return t.sent(),[2/*return*/];}});});}),o.resolve(),[3/*break*/,4];case 3:// An unknown failure on the first stage shuts everything down.\nif(u=c.sent(),// Regardless of whether or not the retry succeeds, from an user\n// perspective, offline persistence has failed.\no.reject(u),!this.U_(u))throw u;return[2/*return*/,(console.warn(\"Error enabling offline persistence. Falling back to persistence disabled: \"+u),this.B_(new cu(),new fu(),{jl:!1},i,o))];case 4:return[2/*return*/];}});});},/**\n * Decides whether the provided error allows us to gracefully disable\n * persistence (as opposed to crashing the client).\n */e.prototype.U_=function(t){return\"FirebaseError\"===t.name?t.code===a.FAILED_PRECONDITION||t.code===a.UNIMPLEMENTED:!(\"undefined\"!=typeof DOMException&&t instanceof DOMException)||// When the browser is out of quota we could get either quota exceeded\n// or an aborted error depending on whether the error happened during\n// schema migration.\n22===t.code||20===t.code||// Firefox Private Browsing mode disables IndexedDb and returns\n// INVALID_STATE for any usage.\n11===t.code;},/**\n * Checks that the client has not been terminated. Ensures that other methods on\n * this class cannot be called after the client is terminated.\n */e.prototype.L_=function(){if(this.cs.ps)throw new c(a.FAILED_PRECONDITION,\"The client has already been terminated.\");},/** Disables the network connection. Pending operations will not complete. */e.prototype.disableNetwork=function(){var e=this;return this.L_(),this.cs.enqueue(function(){return e.persistence.tc(!1),function(e){return t.__awaiter(this,void 0,void 0,function(){var n;return t.__generator(this,function(t){switch(t.label){case 0:return(n=m(e)).Yu.add(0/* UserDisabled */),[4/*yield*/,zo(n)];case 1:return t.sent(),// Set the OnlineState to Offline so get()s return from cache, etc.\nn.th.set(\"Offline\"/* Offline */),[2/*return*/];}});});}(e.ph);});},e.prototype.terminate=function(){var e=this;this.cs.Ds();var n=new dr();return this.cs.bs(function(){return t.__awaiter(e,void 0,void 0,function(){var e,r;return t.__generator(this,function(t){switch(t.label){case 0:return t.trys.push([0,4,,5]),// PORTING NOTE: LocalStore does not need an explicit shutdown on web.\nthis.ql&&this.ql.stop(),[4/*yield*/,Bo(this.ph)];case 1:return t.sent(),[4/*yield*/,this.Sh.Di()];case 2:return t.sent(),[4/*yield*/,this.persistence.Di()];case 3:// PORTING NOTE: LocalStore does not need an explicit shutdown on web.\nreturn t.sent(),// `removeChangeListener` must be called after shutting down the\n// RemoteStore as it will prevent the RemoteStore from retrieving\n// auth tokens.\nthis.credentials.Yc(),n.resolve(),[3/*break*/,5];case 4:return e=t.sent(),r=Lr(e,\"Failed to shutdown persistence\"),n.reject(r),[3/*break*/,5];case 5:return[2/*return*/];}});});}),n.promise;},/**\n * Returns a Promise that resolves when all writes that were pending at the time this\n * method was called received server acknowledgement. An acknowledgement can be either acceptance\n * or rejection.\n */e.prototype.waitForPendingWrites=function(){var e=this;this.L_();var n=new dr();return this.cs.ws(function(){return function(e,n){return t.__awaiter(this,void 0,void 0,function(){var r,i,o,s,u;return t.__generator(this,function(t){switch(t.label){case 0:Xo((r=m(e)).ph)||l(\"SyncEngine\",\"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.\"),t.label=1;case 1:return t.trys.push([1,3,,4]),[4/*yield*/,function(t){var e=m(t);return e.persistence.runTransaction(\"Get highest unacknowledged batch id\",\"readonly\",function(t){return e.Sr.qo(t);});}(r.ju)];case 2:return-1===(i=t.sent())?[2/*return*/,void n.resolve()]:((o=r.Lh.get(i)||[]).push(n),r.Lh.set(i,o),[3/*break*/,4]);case 3:return s=t.sent(),u=Lr(s,\"Initialization of waitForPendingWrites() operation failed\"),n.reject(u),[3/*break*/,4];case 4:return[2/*return*/];}});});}(e.fi,n);}),n.promise;},e.prototype.listen=function(t,e,n){var r=this;this.L_();var i=new lu(n),o=new Fr(t,i,e);return this.cs.ws(function(){return Or(r.q_,o);}),function(){i.Zl(),r.cs.ws(function(){return Pr(r.q_,o);});};},e.prototype.Q_=function(e){return t.__awaiter(this,void 0,void 0,function(){var n,r=this;return t.__generator(this,function(i){switch(i.label){case 0:return this.L_(),[4/*yield*/,this.O_.promise];case 1:return i.sent(),n=new dr(),[2/*return*/,(this.cs.ws(function(){return function(e,n,r){return t.__awaiter(this,void 0,void 0,function(){var i,o,s;return t.__generator(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4/*yield*/,function(t,e){var n=m(t);return n.persistence.runTransaction(\"read document\",\"readonly\",function(t){return n.Cc.Cr(t,e);});}(e,n)];case 1:return(i=t.sent())instanceof kn?r.resolve(i):i instanceof Rn?r.resolve(null):r.reject(new c(a.UNAVAILABLE,\"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)\")),[3/*break*/,3];case 2:return o=t.sent(),s=Lr(o,\"Failed to get document '\"+n+\" from cache\"),r.reject(s),[3/*break*/,3];case 3:return[2/*return*/];}});});}(r.ju,e,n);}),n.promise)];}});});},e.prototype.W_=function(e,n){return void 0===n&&(n={}),t.__awaiter(this,void 0,void 0,function(){var r,i=this;return t.__generator(this,function(t){switch(t.label){case 0:return this.L_(),[4/*yield*/,this.O_.promise];case 1:return t.sent(),r=new dr(),[2/*return*/,(this.cs.ws(function(){return function(t,e,n,r,i){var o=new lu({next:function(o){// Remove query first before passing event to user to avoid\n// user actions affecting the now stale query.\ne.ws(function(){return Pr(t,s);});var u=o.docs.has(n);!u&&o.fromCache?// TODO(dimond): If we're online and the document doesn't\n// exist then we resolve with a doc.exists set to false. If\n// we're offline however, we reject the Promise in this\n// case. Two options: 1) Cache the negative response from\n// the server so we can deliver that even when you're\n// offline 2) Actually reject the Promise in the online case\n// if the document doesn't exist.\ni.reject(new c(a.UNAVAILABLE,\"Failed to get document because the client is offline.\")):u&&o.fromCache&&r&&\"server\"===r.source?i.reject(new c(a.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to \"server\" to retrieve the cached document.)')):i.resolve(o);},error:function(t){return i.reject(t);}}),s=new Fr(Un(n.path),o,{includeMetadataChanges:!0,Xs:!0});return Or(t,s);}(i.q_,i.cs,e,n,r);}),r.promise)];}});});},e.prototype.j_=function(e){return t.__awaiter(this,void 0,void 0,function(){var n,r=this;return t.__generator(this,function(i){switch(i.label){case 0:return this.L_(),[4/*yield*/,this.O_.promise];case 1:return i.sent(),n=new dr(),[2/*return*/,(this.cs.ws(function(){return function(e,n,r){return t.__awaiter(this,void 0,void 0,function(){var i,o,s,u,a,c;return t.__generator(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4/*yield*/,To(e,n,/* usePreviousResults= */!0)];case 1:return i=t.sent(),o=new ys(n,i.Fc),s=o.wh(i.documents),u=o.yr(s,/* updateLimboDocuments= */!1),r.resolve(u.snapshot),[3/*break*/,3];case 2:return a=t.sent(),c=Lr(a,\"Failed to execute query '\"+n+\" against cache\"),r.reject(c),[3/*break*/,3];case 3:return[2/*return*/];}});});}(r.ju,e,n);}),n.promise)];}});});},e.prototype.K_=function(e,n){return void 0===n&&(n={}),t.__awaiter(this,void 0,void 0,function(){var r,i=this;return t.__generator(this,function(t){switch(t.label){case 0:return this.L_(),[4/*yield*/,this.O_.promise];case 1:return t.sent(),r=new dr(),[2/*return*/,(this.cs.ws(function(){return function(t,e,n,r,i){var o=new lu({next:function(n){// Remove query first before passing event to user to avoid\n// user actions affecting the now stale query.\ne.ws(function(){return Pr(t,s);}),n.fromCache&&\"server\"===r.source?i.reject(new c(a.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to \"server\" to retrieve the cached documents.)')):i.resolve(n);},error:function(t){return i.reject(t);}}),s=new Fr(n,o,{includeMetadataChanges:!0,Xs:!0});return Or(t,s);}(i.q_,i.cs,e,n,r);}),r.promise)];}});});},e.prototype.write=function(e){var n=this;this.L_();var r=new dr();return this.cs.ws(function(){return function(e,n,r){return t.__awaiter(this,void 0,void 0,function(){var i,o,s,u;return t.__generator(this,function(t){switch(t.label){case 0:i=Qs(e),t.label=1;case 1:return t.trys.push([1,5,,6]),[4/*yield*/,/* Accepts locally generated Mutations and commit them to storage. */function(t,e){var n,r=m(t),i=ot.now(),o=e.reduce(function(t,e){return t.add(e.key);},Ot());return r.persistence.runTransaction(\"Locally write mutations\",\"readwrite\",function(t){return r.Cc.kr(t,o).next(function(o){n=o;for(// For non-idempotent mutations (such as `FieldValue.increment()`),\n// we record the base state in a separate patch mutation. This is\n// later used to guarantee consistent values and prevents flicker\n// even if the backend sends us an update that already includes our\n// transform.\nvar s=[],u=0,a=e;u=0)throw new c(a.INVALID_ARGUMENT,\"Invalid collection ID '\"+t+\"' passed to function Firestore.collectionGroup(). Collection IDs must not contain '/'.\");return this.hf(),new ha(/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */function(t){return new Pn(E.P(),t);}(t),this,/* converter= */null);},e.prototype.runTransaction=function(t){var e=this;return D(\"Firestore.runTransaction\",arguments,1),k(\"Firestore.runTransaction\",\"function\",1,t),this.hf().transaction(function(n){return t(new Ju(e,n));});},e.prototype.batch=function(){return this.hf(),new Zu(this);},Object.defineProperty(e,\"logLevel\",{get:function(){switch(f()){case n.LogLevel.DEBUG:return\"debug\";case n.LogLevel.ERROR:return\"error\";case n.LogLevel.SILENT:return\"silent\";case n.LogLevel.WARN:return\"warn\";case n.LogLevel.INFO:return\"info\";case n.LogLevel.VERBOSE:return\"verbose\";default:// The default log level is error\nreturn\"error\";}},enumerable:!1,configurable:!0}),e.setLogLevel=function(t){var e;D(\"Firestore.setLogLevel\",arguments,1),U(\"setLogLevel\",[\"debug\",\"error\",\"silent\",\"warn\",\"info\",\"verbose\"],1,t),e=t,h.setLogLevel(e);},// Note: this is not a property because the minifier can't work correctly with\n// the way TypeScript compiler outputs properties.\ne.prototype.gf=function(){return this.wf.timestampsInSnapshots;},// Visible for testing.\ne.prototype.Pf=function(){return this.wf;},e;}(),Ju=/** @class */function(){function t(t,e){this.yf=t,this.Vf=e;}return t.prototype.get=function(t){var e=this;D(\"Transaction.get\",arguments,1);var n=ya(\"Transaction.get\",t,this.yf);return this.Vf.v_([n.f_]).then(function(t){if(!t||1!==t.length)return y();var r=t[0];if(r instanceof Rn)return new na(e.yf,n.f_,null,/* fromCache= */!1,/* hasPendingWrites= */!1,n.d_);if(r instanceof kn)return new na(e.yf,n.f_,r,/* fromCache= */!1,/* hasPendingWrites= */!1,n.d_);throw y();});},t.prototype.set=function(t,e,n){L(\"Transaction.set\",arguments,2,3);var r=ya(\"Transaction.set\",t,this.yf);n=pa(\"Transaction.set\",n);var i=ma(r.d_,e,n),o=Ru(this.yf.mf,\"Transaction.set\",r.f_,i,null!==r.d_,n);return this.Vf.set(r.f_,o),this;},t.prototype.update=function(t,e,n){for(var r,i,o=[],s=3;s0?this.yf.hf().write(this.pf):Promise.resolve();},t.prototype.vf=function(){if(this.bf)throw new c(a.FAILED_PRECONDITION,\"A write batch can no longer be used after commit() has been called.\");},t;}(),ta=/** @class */function(e){function n(t,n,r){var i=this;return(i=e.call(this,n.__,t,r)||this).f_=t,i.firestore=n,i.d_=r,i.lf=i.firestore.hf(),i;}return t.__extends(n,e),n.Rf=function(t,e,r){if(t.length%2!=0)throw new c(a.INVALID_ARGUMENT,\"Invalid document reference. Document references must have an even number of segments, but \"+t.R()+\" has \"+t.length);return new n(new A(t),e,r);},Object.defineProperty(n.prototype,\"id\",{get:function(){return this.f_.path._();},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,\"parent\",{get:function(){return new la(this.f_.path.h(),this.firestore,this.d_);},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,\"path\",{get:function(){return this.f_.path.R();},enumerable:!1,configurable:!0}),n.prototype.collection=function(t){if(D(\"DocumentReference.collection\",arguments,1),k(\"DocumentReference.collection\",\"non-empty string\",1,t),!t)throw new c(a.INVALID_ARGUMENT,\"Must provide a non-empty collection name to collection()\");var e=E.g(t);return new la(this.f_.path.child(e),this.firestore,/* converter= */null);},n.prototype.isEqual=function(t){if(!(t instanceof n))throw G(\"isEqual\",\"DocumentReference\",1,t);return this.firestore===t.firestore&&this.f_.isEqual(t.f_)&&this.d_===t.d_;},n.prototype.set=function(t,e){L(\"DocumentReference.set\",arguments,1,2),e=pa(\"DocumentReference.set\",e);var n=ma(this.d_,t,e),r=Ru(this.firestore.mf,\"DocumentReference.set\",this.f_,n,null!==this.d_,e);return this.lf.write(r.w_(this.f_,fn.ze()));},n.prototype.update=function(t,e){for(var n,r=[],i=2;i, or >=) must be on the same field. But you have inequality filters on '\"+n.toString()+\"' and '\"+e.field.toString()+\"'\");var r=Mn(t);null!==r&&aa(t,e.field,r);}var i=function(t,e){for(var n=0,r=t.filters;n=0)return i.op;}return null;}(t,/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one array operator is allowed.\n * 2. Only one disjunctive operator is allowed.\n * 3. NOT_EQUAL cannot be used with another NOT_EQUAL operator.\n * 4. NOT_IN cannot be used with array, disjunctive, or NOT_EQUAL operators.\n *\n * Array operators: ARRAY_CONTAINS, ARRAY_CONTAINS_ANY\n * Disjunctive operators: IN, ARRAY_CONTAINS_ANY, NOT_IN\n */function(t){switch(t){case\"!=\"/* NOT_EQUAL */:return[\"!=\"/* NOT_EQUAL */,\"not-in\"/* NOT_IN */];case\"array-contains\"/* ARRAY_CONTAINS */:return[\"array-contains\"/* ARRAY_CONTAINS */,\"array-contains-any\"/* ARRAY_CONTAINS_ANY */,\"not-in\"/* NOT_IN */];case\"in\"/* IN */:return[\"array-contains-any\"/* ARRAY_CONTAINS_ANY */,\"in\"/* IN */,\"not-in\"/* NOT_IN */];case\"array-contains-any\"/* ARRAY_CONTAINS_ANY */:return[\"array-contains\"/* ARRAY_CONTAINS */,\"array-contains-any\"/* ARRAY_CONTAINS_ANY */,\"in\"/* IN */,\"not-in\"/* NOT_IN */];case\"not-in\"/* NOT_IN */:return[\"array-contains\"/* ARRAY_CONTAINS */,\"array-contains-any\"/* ARRAY_CONTAINS_ANY */,\"in\"/* IN */,\"not-in\"/* NOT_IN */,\"!=\"/* NOT_EQUAL */];default:return[];}}(e.op));if(null!==i)// Special case when it's a duplicate op to give a slightly clearer error message.\nthrow i===e.op?new c(a.INVALID_ARGUMENT,\"Invalid query. You cannot use more than one '\"+e.op.toString()+\"' filter.\"):new c(a.INVALID_ARGUMENT,\"Invalid query. You cannot use '\"+e.op.toString()+\"' filters with '\"+i.toString()+\"' filters.\");}(t,d),d;}function oa(t,e,n){if(null!==t.startAt)throw new c(a.INVALID_ARGUMENT,\"Invalid query. You must not call startAt() or startAfter() before calling orderBy().\");if(null!==t.endAt)throw new c(a.INVALID_ARGUMENT,\"Invalid query. You must not call endAt() or endBefore() before calling orderBy().\");var r=new fr(e,n);return function(t,e){if(null===Mn(t)){// This is the first order by. It must match any inequality.\nvar n=qn(t);null!==n&&aa(t,n,e.field);}}(t,r),r/**\n * Create a Bound from a query and a document.\n *\n * Note that the Bound will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */ /**\n * Parses the given documentIdValue into a ReferenceValue, throwing\n * appropriate errors if the value is anything other than a DocumentReference\n * or String, or if the string is malformed.\n */;}function sa(t,e,n){if(\"string\"==typeof n){if(\"\"===n)throw new c(a.INVALID_ARGUMENT,\"Invalid query. When querying with FieldPath.documentId(), you must provide a valid document ID, but it was an empty string.\");if(!jn(e)&&-1!==n.indexOf(\"/\"))throw new c(a.INVALID_ARGUMENT,\"Invalid query. When querying a collection by FieldPath.documentId(), you must provide a plain document ID, but '\"+n+\"' contains a '/' character.\");var r=e.path.child(E.g(n));if(!A.F(r))throw new c(a.INVALID_ARGUMENT,\"Invalid query. When querying a collection group by FieldPath.documentId(), the value provided must result in a valid document path, but '\"+r+\"' is not because it has an odd number of segments (\"+r.length+\").\");return ae(t,new A(r));}if(n instanceof Au)return ae(t,n.f_);throw new c(a.INVALID_ARGUMENT,\"Invalid query. When querying with FieldPath.documentId(), you must provide a valid string or a DocumentReference, but it was: \"+M(n)+\".\");}/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */function ua(t,e){if(!Array.isArray(t)||0===t.length)throw new c(a.INVALID_ARGUMENT,\"Invalid Query. A non-empty array is required for '\"+e.toString()+\"' filters.\");if(t.length>10)throw new c(a.INVALID_ARGUMENT,\"Invalid Query. '\"+e.toString()+\"' filters support a maximum of 10 elements in the value array.\");if(\"in\"/* IN */===e||\"array-contains-any\"/* ARRAY_CONTAINS_ANY */===e){if(t.indexOf(null)>=0)throw new c(a.INVALID_ARGUMENT,\"Invalid Query. '\"+e.toString()+\"' filters cannot contain 'null' in the value array.\");if(t.filter(function(t){return Number.isNaN(t);}).length>0)throw new c(a.INVALID_ARGUMENT,\"Invalid Query. '\"+e.toString()+\"' filters cannot contain 'NaN' in the value array.\");}}function aa(t,e,n){if(!n.isEqual(e))throw new c(a.INVALID_ARGUMENT,\"Invalid query. You have a where filter with an inequality (<, <=, >, or >=) on field '\"+e.toString()+\"' and so you must also use '\"+e.toString()+\"' as your first orderBy(), but your first orderBy() is on field '\"+n.toString()+\"' instead.\");}function ca(t){if(Fn(t)&&0===t.on.length)throw new c(a.UNIMPLEMENTED,\"limitToLast() queries require specifying at least one orderBy() clause\");}var ha=/** @class */function(){function e(t,e,n){this.Ff=t,this.firestore=e,this.d_=n;}return e.prototype.where=function(t,n,r){D(\"Query.where\",arguments,3),q(\"Query.where\",3,r);// Enumerated from the WhereFilterOp type in index.d.ts.\nvar i=U(\"Query.where\",[\"<\"/* LESS_THAN */,\"<=\"/* LESS_THAN_OR_EQUAL */,\"==\"/* EQUAL */,\"!=\"/* NOT_EQUAL */,\">=\"/* GREATER_THAN_OR_EQUAL */,\">\"/* GREATER_THAN */,\"array-contains\"/* ARRAY_CONTAINS */,\"in\"/* IN */,\"array-contains-any\"/* ARRAY_CONTAINS_ANY */,\"not-in\"/* NOT_IN */],2,n),o=qu(\"Query.where\",t),s=ia(this.Ff,\"Query.where\",this.firestore.mf,this.firestore.__,o,i,r);return new e(function(t,e){var n=t.filters.concat([e]);return new Pn(t.path,t.collectionGroup,t.on.slice(),n,t.limit,t.an,t.startAt,t.endAt);}(this.Ff,s),this.firestore,this.d_);},e.prototype.orderBy=function(t,n){var r;if(L(\"Query.orderBy\",arguments,1,2),R(\"Query.orderBy\",\"non-empty string\",2,n),void 0===n||\"asc\"===n)r=\"asc\"/* ASCENDING */;else{if(\"desc\"!==n)throw new c(a.INVALID_ARGUMENT,\"Function Query.orderBy() has unknown direction '\"+n+\"', expected 'asc' or 'desc'.\");r=\"desc\"/* DESCENDING */;}var i=qu(\"Query.orderBy\",t),o=oa(this.Ff,i,r);return new e(function(t,e){// TODO(dimond): validate that orderBy does not list the same key twice.\nvar n=t.on.concat([e]);return new Pn(t.path,t.collectionGroup,n,t.filters.slice(),t.limit,t.an,t.startAt,t.endAt);}(this.Ff,o),this.firestore,this.d_);},e.prototype.limit=function(t){return D(\"Query.limit\",arguments,1),k(\"Query.limit\",\"number\",1,t),z(\"Query.limit\",1,t),new e(Bn(this.Ff,t,\"F\"/* First */),this.firestore,this.d_);},e.prototype.limitToLast=function(t){return D(\"Query.limitToLast\",arguments,1),k(\"Query.limitToLast\",\"number\",1,t),z(\"Query.limitToLast\",1,t),new e(Bn(this.Ff,t,\"L\"/* Last */),this.firestore,this.d_);},e.prototype.startAt=function(t){for(var n=[],r=1;rs.length)throw new c(a.INVALID_ARGUMENT,\"Too many arguments provided to \"+r+\"(). The number of arguments must be less than or equal to the number of orderBy() clauses\");for(var u=[],h=0;h {\n this.$refs.dropArea.addEventListener(e, this.preventDefaults.bind(this), false);\n });\n ['dragenter', 'dragover', 'drop'].forEach(e => {\n this.$refs.dropArea.addEventListener(e, this.highlight.bind(this), false);\n });\n ['dragleave'].forEach(e => {\n this.$refs.dropArea.addEventListener(e, this.unhighlight.bind(this), false);\n });\n this.$refs.dropArea.addEventListener('drop', this.handleDrop.bind(this), false);\n this.$refs.dropArea.addEventListener('click', () => {\n this.onDropAreaClick();\n });\n this.$refs.pictureFile.addEventListener('input', () => {\n this.file = this.$refs.pictureFile.files[0]; // eslint-disable-line prefer-destructuring\n this.$refs.pictureName.innerHTML = this.file.name;\n this.highlight();\n });\n Array.prototype.forEach.call(this.$el.elements, input => {\n input.addEventListener('input', () => {\n this.checkInputs();\n });\n });\n }\n\n // eslint-disable-next-line class-methods-use-this\n onClick() {\n kapla__WEBPACK_IMPORTED_MODULE_0__[\"ee\"].emit('modal:focused');\n }\n onSubmit(e) {\n e.preventDefault();\n if (this.formValidation()) {\n // Check if the form has been completed correctly\n this.$refs.inputs.classList.add('is-hidden');\n kapla__WEBPACK_IMPORTED_MODULE_0__[\"ee\"].emit('spinner:start');\n this.unhighlight();\n Form.uploadFile(this.file) // Store the picture in Firebase Cloud and the info in Firestore\n .then(downloadURL => {\n this.createShowcase(downloadURL);\n })\n // Loader to wait the response\n .then(() => {\n kapla__WEBPACK_IMPORTED_MODULE_0__[\"ee\"].emit('spinner:stop');\n })\n // Handle success with feedback\n .then(() => {\n this.$refs.succeed.classList.add('is-active');\n setTimeout(() => {\n this.$refs.succeed.classList.remove('is-active');\n this.resetValues();\n kapla__WEBPACK_IMPORTED_MODULE_0__[\"ee\"].emit('modal:close');\n this.$refs.inputs.classList.remove('is-hidden');\n }, 2000);\n })\n // Handle error with feedback\n .catch(err => {\n console.error(err);\n kapla__WEBPACK_IMPORTED_MODULE_0__[\"ee\"].emit('spinner:stop');\n this.$refs.failed.classList.add('is-active');\n this.$refs.failed.innerHTML = err.message;\n setTimeout(() => {\n this.$refs.failed.classList.remove('is-active');\n kapla__WEBPACK_IMPORTED_MODULE_0__[\"ee\"].emit('modal:close');\n this.$refs.inputs.classList.remove('is-hidden');\n }, 5000);\n });\n }\n }\n static uploadFile(file) {\n return new Promise((resolve, reject) => {\n const storageRef = firebase_app__WEBPACK_IMPORTED_MODULE_2___default.a.storage().ref().child(`showcases/${file.name}`);\n const uploadTask = storageRef.put(file);\n uploadTask.on('state_changed', snapshot => {\n // Observe state change events such as progress, pause, and resume\n // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded\n // var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;\n // console.log('Upload is ' + progress + '% done');\n switch (snapshot.state) {\n case firebase_app__WEBPACK_IMPORTED_MODULE_2___default.a.storage.TaskState.PAUSED:\n // Or 'paused'\n console.log('Upload is paused');\n break;\n case firebase_app__WEBPACK_IMPORTED_MODULE_2___default.a.storage.TaskState.RUNNING:\n // Or 'running'\n console.log('Upload is running');\n break;\n default:\n }\n }, error => {\n // Handle unsuccessful uploads\n console.error(error);\n reject(error);\n }, () => {\n // Handle successful uploads on complete\n // For instance, get the download URL: https://firebasestorage.googleapis.com/...\n uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {\n // DEV\n // console.log('File available at', downloadURL)\n resolve(downloadURL);\n });\n });\n });\n }\n createShowcase(downloadURL) {\n return _source_js_connectionDB__WEBPACK_IMPORTED_MODULE_1__[\"default\"].collection('showcases').add({\n from: cryptr.decrypt(\"4bd1ec2a5f9c1647619a31340f97e7aa94c298a10a5f3a2f3212004eefbcbdebbca666abe8f935627430dcd79ce19c9e418f627893fd31c74d863923bd5096664d05dab0c8b3db85b6dda13c78418b744f36e42b1a639d7c7035ab31472a332c9a8f5e7ba527a040c8d6256c77\"),\n authorName: this.$refs.authorName.value,\n authorUrl: this.$refs.authorUrl.value,\n isValidated: false,\n pictureUrl: downloadURL,\n siteName: this.$refs.siteName.value,\n siteUrl: this.$refs.siteUrl.value,\n dateCreation: new firebase_app__WEBPACK_IMPORTED_MODULE_2___default.a.firestore.Timestamp.now() // eslint-disable-line new-cap\n });\n }\n resetValues() {\n this.$refs.authorName.value = '';\n this.$refs.authorUrl.value = '';\n this.$refs.dropArea.value = '';\n this.$refs.pictureFile.value = '';\n this.$refs.pictureName.innerHTML = 'No file submitted';\n this.$refs.siteName.value = '';\n this.$refs.siteUrl.value = '';\n this.file = [];\n }\n\n // eslint-disable-next-line class-methods-use-this\n preventDefaults(e) {\n e.preventDefault();\n e.stopPropagation();\n }\n highlight() {\n this.$refs.dropArea.classList.add('highlight');\n }\n unhighlight() {\n this.$refs.dropArea.classList.remove('highlight');\n }\n handleDrop(e) {\n const dt = e.dataTransfer;\n this.file = dt.files[0]; // eslint-disable-line prefer-destructuring\n this.checkInputs();\n this.$refs.pictureName.innerHTML = this.file.name;\n }\n onDropAreaClick() {\n this.$refs.pictureFile.click();\n }\n checkInputs() {\n if (this.$refs.authorName.value && this.$refs.siteName.value && this.$refs.siteUrl.value && this.file.length !== 0) {\n this.$el.classList.remove('is-invalid');\n return true;\n }\n this.$el.classList.add('is-invalid');\n return false;\n }\n formValidation() {\n // eslint-disable-next-line max-len\n const urlPattern = /^(?:(?:https?|ftp):\\/\\/)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:\\/\\S*)?$/;\n\n // Picture\n if (this.file.length === 0 || this.file.size > 2100000 || this.file.type !== 'image/jpeg' && this.file.type !== 'image/png' && this.file.type !== 'image/gif') {\n console.error('Invalid image, please respect indications');\n return false;\n } else if (\n // Site Name\n typeof this.$refs.siteName.value !== 'string' && this.$refs.siteName.value.length < 2 && this.$refs.siteName.value.length > 64) {\n console.error('Invalid site name, it should be between 2 and 64 characters');\n return false;\n } else if (\n // Site Url\n urlPattern.test(this.$refs.siteUrl.value) === false) {\n console.error('Invalid site url');\n return false;\n } else if (\n // Author Name\n typeof this.$refs.authorName.value !== 'string' && this.$refs.authorName.value.length < 2 && this.$refs.authorName.value.length > 64) {\n console.error('Invalid author name, it should be between 2 and 64 characters');\n return false;\n } else if (\n // Author Url\n this.$refs.authorUrl.value && urlPattern.test(this.$refs.authorUrl.value) === false) {\n console.error('Invalid author url');\n return false;\n }\n return true;\n }\n}\n\n//# sourceURL=webpack:///./themes/barba/layout/components/showcase/Form.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return Form; });\n/* harmony import */ var kapla__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! kapla */ \"./node_modules/kapla/dist/kapla.min.js\");\n/* harmony import */ var kapla__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(kapla__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _source_js_connectionDB__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../source/_js/connectionDB */ \"./themes/barba/source/_js/connectionDB.js\");\n/* harmony import */ var firebase_app__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! firebase/app */ \"./node_modules/firebase/app/dist/index.cjs.js\");\n/* harmony import */ var firebase_app__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(firebase_app__WEBPACK_IMPORTED_MODULE_2__);\n\n\n\nconst Cryptr = __webpack_require__(/*! cryptr */ \"./node_modules/cryptr/index.js\");\nconst cryptr = new Cryptr('barba.js');\nclass Form extends kapla__WEBPACK_IMPORTED_MODULE_0__[\"Component\"] {\n load() {\n const dragEvents = ['dragenter', 'dragover', 'dragleave', 'drop'];\n this.file = [];\n dragEvents.forEach(e => {\n this.$refs.dropArea.addEventListener(e, this.preventDefaults.bind(this), false);\n });\n ['dragenter', 'dragover', 'drop'].forEach(e => {\n this.$refs.dropArea.addEventListener(e, this.highlight.bind(this), false);\n });\n ['dragleave'].forEach(e => {\n this.$refs.dropArea.addEventListener(e, this.unhighlight.bind(this), false);\n });\n this.$refs.dropArea.addEventListener('drop', this.handleDrop.bind(this), false);\n this.$refs.dropArea.addEventListener('click', () => {\n this.onDropAreaClick();\n });\n this.$refs.pictureFile.addEventListener('input', () => {\n this.file = this.$refs.pictureFile.files[0]; // eslint-disable-line prefer-destructuring\n this.$refs.pictureName.innerHTML = this.file.name;\n this.highlight();\n });\n Array.prototype.forEach.call(this.$el.elements, input => {\n input.addEventListener('input', () => {\n this.checkInputs();\n });\n });\n }\n\n // eslint-disable-next-line class-methods-use-this\n onClick() {\n kapla__WEBPACK_IMPORTED_MODULE_0__[\"ee\"].emit('modal:focused');\n }\n onSubmit(e) {\n e.preventDefault();\n if (this.formValidation()) {\n // Check if the form has been completed correctly\n this.$refs.inputs.classList.add('is-hidden');\n kapla__WEBPACK_IMPORTED_MODULE_0__[\"ee\"].emit('spinner:start');\n this.unhighlight();\n Form.uploadFile(this.file) // Store the picture in Firebase Cloud and the info in Firestore\n .then(downloadURL => {\n this.createShowcase(downloadURL);\n })\n // Loader to wait the response\n .then(() => {\n kapla__WEBPACK_IMPORTED_MODULE_0__[\"ee\"].emit('spinner:stop');\n })\n // Handle success with feedback\n .then(() => {\n this.$refs.succeed.classList.add('is-active');\n setTimeout(() => {\n this.$refs.succeed.classList.remove('is-active');\n this.resetValues();\n kapla__WEBPACK_IMPORTED_MODULE_0__[\"ee\"].emit('modal:close');\n this.$refs.inputs.classList.remove('is-hidden');\n }, 2000);\n })\n // Handle error with feedback\n .catch(err => {\n console.error(err);\n kapla__WEBPACK_IMPORTED_MODULE_0__[\"ee\"].emit('spinner:stop');\n this.$refs.failed.classList.add('is-active');\n this.$refs.failed.innerHTML = err.message;\n setTimeout(() => {\n this.$refs.failed.classList.remove('is-active');\n kapla__WEBPACK_IMPORTED_MODULE_0__[\"ee\"].emit('modal:close');\n this.$refs.inputs.classList.remove('is-hidden');\n }, 5000);\n });\n }\n }\n static uploadFile(file) {\n return new Promise((resolve, reject) => {\n const storageRef = firebase_app__WEBPACK_IMPORTED_MODULE_2___default.a.storage().ref().child(`showcases/${file.name}`);\n const uploadTask = storageRef.put(file);\n uploadTask.on('state_changed', snapshot => {\n // Observe state change events such as progress, pause, and resume\n // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded\n // var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;\n // console.log('Upload is ' + progress + '% done');\n switch (snapshot.state) {\n case firebase_app__WEBPACK_IMPORTED_MODULE_2___default.a.storage.TaskState.PAUSED:\n // Or 'paused'\n console.log('Upload is paused');\n break;\n case firebase_app__WEBPACK_IMPORTED_MODULE_2___default.a.storage.TaskState.RUNNING:\n // Or 'running'\n console.log('Upload is running');\n break;\n default:\n }\n }, error => {\n // Handle unsuccessful uploads\n console.error(error);\n reject(error);\n }, () => {\n // Handle successful uploads on complete\n // For instance, get the download URL: https://firebasestorage.googleapis.com/...\n uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {\n // DEV\n // console.log('File available at', downloadURL)\n resolve(downloadURL);\n });\n });\n });\n }\n createShowcase(downloadURL) {\n return _source_js_connectionDB__WEBPACK_IMPORTED_MODULE_1__[\"default\"].collection('showcases').add({\n from: cryptr.decrypt(\"177d7e743d4ef19dc6ae00ec61b2848d1e1424b88201806ad975799e38f66faff36072282df28b177081126c30281eb0d9d6736ecbfd25c98b2b8a0f3df1a79101f20468b5a4abd53e17ac74912dec73b9ab3084087efd42b00384ee00fbb625b3b73a50698b942ed7a9b4ec8d\"),\n authorName: this.$refs.authorName.value,\n authorUrl: this.$refs.authorUrl.value,\n isValidated: false,\n pictureUrl: downloadURL,\n siteName: this.$refs.siteName.value,\n siteUrl: this.$refs.siteUrl.value,\n dateCreation: new firebase_app__WEBPACK_IMPORTED_MODULE_2___default.a.firestore.Timestamp.now() // eslint-disable-line new-cap\n });\n }\n resetValues() {\n this.$refs.authorName.value = '';\n this.$refs.authorUrl.value = '';\n this.$refs.dropArea.value = '';\n this.$refs.pictureFile.value = '';\n this.$refs.pictureName.innerHTML = 'No file submitted';\n this.$refs.siteName.value = '';\n this.$refs.siteUrl.value = '';\n this.file = [];\n }\n\n // eslint-disable-next-line class-methods-use-this\n preventDefaults(e) {\n e.preventDefault();\n e.stopPropagation();\n }\n highlight() {\n this.$refs.dropArea.classList.add('highlight');\n }\n unhighlight() {\n this.$refs.dropArea.classList.remove('highlight');\n }\n handleDrop(e) {\n const dt = e.dataTransfer;\n this.file = dt.files[0]; // eslint-disable-line prefer-destructuring\n this.checkInputs();\n this.$refs.pictureName.innerHTML = this.file.name;\n }\n onDropAreaClick() {\n this.$refs.pictureFile.click();\n }\n checkInputs() {\n if (this.$refs.authorName.value && this.$refs.siteName.value && this.$refs.siteUrl.value && this.file.length !== 0) {\n this.$el.classList.remove('is-invalid');\n return true;\n }\n this.$el.classList.add('is-invalid');\n return false;\n }\n formValidation() {\n // eslint-disable-next-line max-len\n const urlPattern = /^(?:(?:https?|ftp):\\/\\/)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:\\/\\S*)?$/;\n\n // Picture\n if (this.file.length === 0 || this.file.size > 2100000 || this.file.type !== 'image/jpeg' && this.file.type !== 'image/png' && this.file.type !== 'image/gif') {\n console.error('Invalid image, please respect indications');\n return false;\n } else if (\n // Site Name\n typeof this.$refs.siteName.value !== 'string' && this.$refs.siteName.value.length < 2 && this.$refs.siteName.value.length > 64) {\n console.error('Invalid site name, it should be between 2 and 64 characters');\n return false;\n } else if (\n // Site Url\n urlPattern.test(this.$refs.siteUrl.value) === false) {\n console.error('Invalid site url');\n return false;\n } else if (\n // Author Name\n typeof this.$refs.authorName.value !== 'string' && this.$refs.authorName.value.length < 2 && this.$refs.authorName.value.length > 64) {\n console.error('Invalid author name, it should be between 2 and 64 characters');\n return false;\n } else if (\n // Author Url\n this.$refs.authorUrl.value && urlPattern.test(this.$refs.authorUrl.value) === false) {\n console.error('Invalid author url');\n return false;\n }\n return true;\n }\n}\n\n//# sourceURL=webpack:///./themes/barba/layout/components/showcase/Form.js?"); /***/ }),