diff --git a/chrome-extension/.gitignore b/chrome-extension/.gitignore new file mode 100644 index 0000000..2ac2913 --- /dev/null +++ b/chrome-extension/.gitignore @@ -0,0 +1,2 @@ +# Firebase config with real keys - exclude from version control +firebase-config.js diff --git a/chrome-extension/README.md b/chrome-extension/README.md new file mode 100644 index 0000000..6fafdf5 --- /dev/null +++ b/chrome-extension/README.md @@ -0,0 +1,41 @@ +# GitHub Chat - Chrome Extension + +A Chrome extension that adds a real-time chat widget to every GitHub repository page. + +## Features +- Toggle chat with a button in the bottom-right corner +- Real-time messaging via Firebase Firestore +- Chat on any `github.com/*` page +- Delete your own messages +- Persistent display name (localStorage) +- Responsive design (full screen on mobile) + +## Installation (Developer Mode) +1. Open `chrome://extensions` in Chrome +2. Enable "Developer mode" (top right) +3. Click "Load unpacked" +4. Select this `chrome-extension/` folder +5. Visit any GitHub repo page - the chat button appears in the bottom right + +## How It Works +- **Content script** (`content.js`): Injects a toggle button and iframe into GitHub pages +- **Chat widget** (`chat-widget.html` + `chat-widget.js`): The chat UI running inside the iframe +- **Firebase Firestore**: Stores and syncs messages in real-time + +## Technical Details +- Manifest V3 compliant +- No special permissions required +- Only activates on `https://github.com/*` +- Uses the existing `inquid-chat` Firebase project + +## Files +| File | Purpose | +|------|---------| +| `manifest.json` | Extension manifest (V3) | +| `content.js` | Content script - injects UI into GitHub | +| `chat-widget.html` | Chat UI (loaded in iframe) | +| `chat-widget.js` | Chat logic and Firebase integration | +| `chat-widget.css` | Styles for toggle button and chat widget | +| `icon*.png` | Extension icons | + +Closes #1 diff --git a/chrome-extension/chat-widget.css b/chrome-extension/chat-widget.css new file mode 100644 index 0000000..eb7a027 --- /dev/null +++ b/chrome-extension/chat-widget.css @@ -0,0 +1,201 @@ +/* Toggle Button */ +#github-chat-toggle { + position: fixed; + bottom: 20px; + right: 20px; + z-index: 9999; + width: 56px; + height: 56px; + border-radius: 50%; + background: #2da44e; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); + transition: all 0.2s ease; +} +#github-chat-toggle:hover { + background: #2c974b; + transform: scale(1.05); +} +#github-chat-toggle.active { + background: #cf222e; +} + +/* Chat Container */ +#github-chat-container { + display: none; + position: fixed; + bottom: 90px; + right: 20px; + z-index: 9998; + width: 380px; + height: 520px; + border-radius: 12px; + box-shadow: 0 8px 30px rgba(0, 0, 0, 0.25); + overflow: hidden; + background: #fff; +} + +/* Responsive */ +@media (max-width: 480px) { + #github-chat-container { + width: 100vw; + height: 100vh; + bottom: 0; + right: 0; + border-radius: 0; + } + #github-chat-toggle { + bottom: 16px; + right: 16px; + } +} + +/* Chat Widget Internal Styles */ +.github-chat * { + box-sizing: border-box; + margin: 0; + padding: 0; +} +.github-chat { + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif; + display: flex; + flex-direction: column; + height: 100%; + background: #f6f8fa; +} +.github-chat .chat-header { + background: #24292f; + color: white; + padding: 12px 16px; + font-size: 16px; + font-weight: 600; + display: flex; + align-items: center; + gap: 8px; +} +.github-chat .chat-header .repo-name { + font-size: 13px; + opacity: 0.85; + font-weight: 400; +} +.github-chat .messages { + flex: 1; + overflow-y: auto; + padding: 16px; + display: flex; + flex-direction: column; + gap: 8px; +} +.github-chat .message { + max-width: 80%; + padding: 10px 14px; + border-radius: 12px; + font-size: 14px; + line-height: 1.4; + word-wrap: break-word; + position: relative; +} +.github-chat .message.sent { + align-self: flex-end; + background: #ddf4ff; + border: 1px solid #54aeff; +} +.github-chat .message.received { + align-self: flex-start; + background: #fff; + border: 1px solid #d0d7de; +} +.github-chat .message .sender { + font-size: 11px; + font-weight: 600; + color: #656d76; + margin-bottom: 4px; +} +.github-chat .message .delete-btn { + position: absolute; + top: 4px; + right: 8px; + background: none; + border: none; + color: #cf222e; + cursor: pointer; + font-size: 12px; + display: none; + padding: 2px 4px; + border-radius: 3px; +} +.github-chat .message:hover .delete-btn { + display: block; +} +.github-chat .message .delete-btn:hover { + background: #ffebe9; +} +.github-chat .input-area { + padding: 12px; + background: #fff; + border-top: 1px solid #d0d7de; + display: flex; + gap: 8px; +} +.github-chat .input-area input { + flex: 1; + padding: 8px 12px; + border: 1px solid #d0d7de; + border-radius: 6px; + font-size: 14px; + outline: none; +} +.github-chat .input-area input:focus { + border-color: #0969da; + box-shadow: 0 0 0 3px rgba(9, 105, 218, 0.15); +} +.github-chat .input-area button { + padding: 8px 16px; + background: #2da44e; + color: white; + border: none; + border-radius: 6px; + font-size: 14px; + font-weight: 500; + cursor: pointer; +} +.github-chat .input-area button:hover { + background: #2c974b; +} +.github-chat .name-prompt { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + height: 100%; + gap: 12px; + padding: 32px; + text-align: center; +} +.github-chat .name-prompt h2 { + color: #24292f; +} +.github-chat .name-prompt p { + color: #656d76; + font-size: 14px; +} +.github-chat .name-prompt input { + padding: 8px 12px; + border: 1px solid #d0d7de; + border-radius: 6px; + font-size: 14px; + width: 100%; + max-width: 250px; +} +.github-chat .name-prompt button { + padding: 8px 24px; + background: #2da44e; + color: white; + border: none; + border-radius: 6px; + font-size: 14px; + cursor: pointer; +} diff --git a/chrome-extension/chat-widget.html b/chrome-extension/chat-widget.html new file mode 100644 index 0000000..113a0fd --- /dev/null +++ b/chrome-extension/chat-widget.html @@ -0,0 +1,28 @@ + + + + + + GitHub Chat + + + +
+
+ + GitHub Chat +
+
+
+ + +
+
+ + + + + + + + diff --git a/chrome-extension/chat-widget.js b/chrome-extension/chat-widget.js new file mode 100644 index 0000000..21ef2b3 --- /dev/null +++ b/chrome-extension/chat-widget.js @@ -0,0 +1,149 @@ +// Chat Widget Logic - runs inside iframe on GitHub pages +(function () { + // Firebase config loaded from firebase-config.js + var firebaseConfig = window.FIREBASE_CONFIG; + + firebase.initializeApp(firebaseConfig); + var db = firebase.firestore(); + + var myName = localStorage.getItem("github-chat-username") || ""; + var myUid = localStorage.getItem("github-chat-uid") || ""; + if (!myUid) { + myUid = "uid-" + Math.random().toString(36).substr(2, 9) + "-" + Date.now().toString(36); + localStorage.setItem("github-chat-uid", myUid); + } + var messagesEl = document.getElementById("messages"); + var inputEl = document.getElementById("messageInput"); + var sendBtn = document.getElementById("sendBtn"); + + // Show name prompt if no username set + if (!myName) { + showNamePrompt(); + } else { + initChat(); + } + + function showNamePrompt() { + messagesEl.innerHTML = + '
' + + '

Welcome to GitHub Chat

' + + '

Enter a display name to start chatting

' + + '' + + '' + + "
"; + + document.getElementById("nameBtn").addEventListener("click", function () { + var name = document.getElementById("nameInput").value.trim(); + if (name) { + myName = name; + localStorage.setItem("github-chat-username", name); + initChat(); + } + }); + + document.getElementById("nameInput").addEventListener("keypress", function (e) { + if (e.key === "Enter") { + document.getElementById("nameBtn").click(); + } + }); + } + + function initChat() { + messagesEl.innerHTML = ""; + loadMessages(); + setupListeners(); + } + + function loadMessages() { + db.collection("messages") + .orderBy("timestamp", "asc") + .onSnapshot(function (snapshot) { + snapshot.docChanges().forEach(function (change) { + if (change.type === "added") { + addMessageToUI(change.doc.id, change.doc.data()); + } + if (change.type === "removed") { + var el = document.getElementById("message-" + change.doc.id); + if (el) { + el.innerHTML = "This message has been deleted"; + } + } + }); + scrollToBottom(); + }); + } + + function addMessageToUI(id, data) { + if (document.getElementById("message-" + id)) return; + + var isSent = data.uid === myUid; + var msgEl = document.createElement("div"); + msgEl.id = "message-" + id; + msgEl.className = "message " + (isSent ? "sent" : "received"); + + var senderHtml = data.sender ? '
' + escapeHtml(data.sender) + "
" : ""; + var deleteBtnHtml = isSent + ? '' + : ""; + + msgEl.innerHTML = senderHtml + escapeHtml(data.message) + deleteBtnHtml; + messagesEl.appendChild(msgEl); + + // Delete button handler + if (isSent) { + msgEl.querySelector(".delete-btn").addEventListener("click", function () { + deleteMessage(id); + }); + } + } + + function setupListeners() { + sendBtn.addEventListener("click", sendMessage); + inputEl.addEventListener("keypress", function (e) { + if (e.key === "Enter") { + sendMessage(); + } + }); + } + + function sendMessage() { + var message = inputEl.value.trim(); + if (!message) return; + + db.collection("messages") + .add({ + message: message, + sender: myName, + uid: myUid, + timestamp: firebase.firestore.FieldValue.serverTimestamp() + }) + .then(function () { + inputEl.value = ""; + }) + .catch(function (error) { + console.error("Error sending message: ", error); + }); + } + + function deleteMessage(id) { + db.collection("messages") + .doc(id) + .delete() + .then(function () { + console.log("Message deleted"); + }) + .catch(function (error) { + console.error("Error deleting message: ", error); + }); + } + + function scrollToBottom() { + messagesEl.scrollTop = messagesEl.scrollHeight; + } + + function escapeHtml(text) { + var div = document.createElement("div"); + div.appendChild(document.createTextNode(text)); + return div.innerHTML; + } +})(); diff --git a/chrome-extension/content.js b/chrome-extension/content.js new file mode 100644 index 0000000..06464da --- /dev/null +++ b/chrome-extension/content.js @@ -0,0 +1,42 @@ +// Content script: Injects the GitHub Chat widget toggle button and iframe +(function () { + // Prevent duplicate injection + if (document.getElementById("github-chat-extension-root")) return; + + // Create toggle button + const toggleBtn = document.createElement("div"); + toggleBtn.id = "github-chat-toggle"; + toggleBtn.innerHTML = ''; + toggleBtn.title = "Toggle GitHub Chat"; + + // Create chat container (hidden by default) + const chatContainer = document.createElement("div"); + chatContainer.id = "github-chat-container"; + + // Create iframe for the chat widget + const iframe = document.createElement("iframe"); + iframe.id = "github-chat-iframe"; + iframe.src = chrome.runtime.getURL("chat-widget.html"); + iframe.style.width = "100%"; + iframe.style.height = "100%"; + iframe.style.border = "none"; + iframe.title = "GitHub Chat"; + + chatContainer.appendChild(iframe); + + // Create root element + const root = document.createElement("div"); + root.id = "github-chat-extension-root"; + root.appendChild(toggleBtn); + root.appendChild(chatContainer); + + document.body.appendChild(root); + + // Toggle chat visibility + let chatVisible = false; + toggleBtn.addEventListener("click", () => { + chatVisible = !chatVisible; + chatContainer.style.display = chatVisible ? "flex" : "none"; + toggleBtn.classList.toggle("active", chatVisible); + }); +})(); diff --git a/chrome-extension/firebase-app.js b/chrome-extension/firebase-app.js new file mode 100644 index 0000000..f6d0c51 --- /dev/null +++ b/chrome-extension/firebase-app.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).firebase=t()}(this,function(){"use strict";var r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,t)};var i=function(){return(i=Object.assign||function(e){for(var t,n=1,r=arguments.length;na[0]&&t[1]=e.length?void 0:e)&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function p(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),a=[];try{for(;(void 0===t||0"})):"Error",e=this.serviceName+": "+e+" ("+o+").";return new l(o,e,i)},v);function v(e,t,n){this.service=e,this.serviceName=t,this.errors=n}var y=/\{\$([^}]+)}/g;function m(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function b(e,t){t=new g(e,t);return t.subscribe.bind(t)}var g=(I.prototype.next=function(t){this.forEachObserver(function(e){e.next(t)})},I.prototype.error=function(t){this.forEachObserver(function(e){e.error(t)}),this.close(t)},I.prototype.complete=function(){this.forEachObserver(function(e){e.complete()}),this.close()},I.prototype.subscribe=function(e,t,n){var r,i=this;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");void 0===(r=function(e,t){if("object"!=typeof e||null===e)return!1;for(var n=0,r=t;n=(null!=o?o:e.logLevel)&&a({level:R[t].toLowerCase(),message:i,args:n,type:e.name})}}(n[e])}var H=((H={})["no-app"]="No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()",H["bad-app-name"]="Illegal App name: '{$appName}",H["duplicate-app"]="Firebase App named '{$appName}' already exists",H["app-deleted"]="Firebase App named '{$appName}' already deleted",H["invalid-app-argument"]="firebase.{$appName}() takes either no argument or a Firebase App instance.",H["invalid-log-argument"]="First argument to `onLog` must be null or a function.",H),B=new d("app","Firebase",H),V="@firebase/app",M="[DEFAULT]",U=((H={})[V]="fire-core",H["@firebase/analytics"]="fire-analytics",H["@firebase/app-check"]="fire-app-check",H["@firebase/auth"]="fire-auth",H["@firebase/database"]="fire-rtdb",H["@firebase/functions"]="fire-fn",H["@firebase/installations"]="fire-iid",H["@firebase/messaging"]="fire-fcm",H["@firebase/performance"]="fire-perf",H["@firebase/remote-config"]="fire-rc",H["@firebase/storage"]="fire-gcs",H["@firebase/firestore"]="fire-fst",H["fire-js"]="fire-js",H["firebase-wrapper"]="fire-js-all",H),W=new z("@firebase/app"),G=(Object.defineProperty($.prototype,"automaticDataCollectionEnabled",{get:function(){return this.checkDestroyed_(),this.automaticDataCollectionEnabled_},set:function(e){this.checkDestroyed_(),this.automaticDataCollectionEnabled_=e},enumerable:!1,configurable:!0}),Object.defineProperty($.prototype,"name",{get:function(){return this.checkDestroyed_(),this.name_},enumerable:!1,configurable:!0}),Object.defineProperty($.prototype,"options",{get:function(){return this.checkDestroyed_(),this.options_},enumerable:!1,configurable:!0}),$.prototype.delete=function(){var t=this;return new Promise(function(e){t.checkDestroyed_(),e()}).then(function(){return t.firebase_.INTERNAL.removeApp(t.name_),Promise.all(t.container.getProviders().map(function(e){return e.delete()}))}).then(function(){t.isDeleted_=!0})},$.prototype._getService=function(e,t){return void 0===t&&(t=M),this.checkDestroyed_(),this.container.getProvider(e).getImmediate({identifier:t})},$.prototype._removeServiceInstance=function(e,t){void 0===t&&(t=M),this.container.getProvider(e).clearInstance(t)},$.prototype._addComponent=function(t){try{this.container.addComponent(t)}catch(e){W.debug("Component "+t.name+" failed to register with FirebaseApp "+this.name,e)}},$.prototype._addOrOverwriteComponent=function(e){this.container.addOrOverwriteComponent(e)},$.prototype.toJSON=function(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}},$.prototype.checkDestroyed_=function(){if(this.isDeleted_)throw B.create("app-deleted",{appName:this.name_})},$);function $(e,t,n){var r=this;this.firebase_=n,this.isDeleted_=!1,this.name_=t.name,this.automaticDataCollectionEnabled_=t.automaticDataCollectionEnabled||!1,this.options_=f(void 0,e),this.container=new L(t.name),this._addComponent(new E("app",function(){return r},"PUBLIC")),this.firebase_.INTERNAL.components.forEach(function(e){return r._addComponent(e)})}G.prototype.name&&G.prototype.options||G.prototype.delete||console.log("dc");var Y="8.5.0";function J(a){var s={},c=new Map,l={__esModule:!0,initializeApp:function(e,t){void 0===t&&(t={});"object"==typeof t&&null!==t||(t={name:t});var n=t;void 0===n.name&&(n.name=M);t=n.name;if("string"!=typeof t||!t)throw B.create("bad-app-name",{appName:String(t)});if(m(s,t))throw B.create("duplicate-app",{appName:t});n=new a(e,n,l);return s[t]=n},app:u,registerVersion:function(e,t,n){var r=null!==(i=U[e])&&void 0!==i?i:e;n&&(r+="-"+n);var i=r.match(/\s|\//),e=t.match(/\s|\//);if(i||e){n=['Unable to register library "'+r+'" with version "'+t+'":'];return i&&n.push('library name "'+r+'" contains illegal characters (whitespace or "/")'),i&&e&&n.push("and"),e&&n.push('version name "'+t+'" contains illegal characters (whitespace or "/")'),void W.warn(n.join(" "))}o(new E(r+"-version",function(){return{library:r,version:t}},"VERSION"))},setLogLevel:T,onLog:function(e,t){if(null!==e&&"function"!=typeof e)throw B.create("invalid-log-argument");x(e,t)},apps:null,SDK_VERSION:Y,INTERNAL:{registerComponent:o,removeApp:function(e){delete s[e]},components:c,useAsService:function(e,t){if("serverAuth"===t)return null;return t}}};function u(e){if(!m(s,e=e||M))throw B.create("no-app",{appName:e});return s[e]}function o(n){var e,r=n.name;if(c.has(r))return W.debug("There were multiple attempts to register component "+r+"."),"PUBLIC"===n.type?l[r]:null;c.set(r,n),"PUBLIC"===n.type&&(e=function(e){if("function"!=typeof(e=void 0===e?u():e)[r])throw B.create("invalid-app-argument",{appName:r});return e[r]()},void 0!==n.serviceProps&&f(e,n.serviceProps),l[r]=e,a.prototype[r]=function(){for(var e=[],t=0;t Project Settings > General > Your apps > Web app +window.FIREBASE_CONFIG = { + apiKey: "YOUR_FIREBASE_API_KEY", + authDomain: "YOUR_PROJECT.firebaseapp.com", + databaseURL: "https://YOUR_PROJECT-default-rtdb.firebaseio.com", + projectId: "YOUR_PROJECT_ID", + storageBucket: "YOUR_PROJECT.appspot.com", + messagingSenderId: "YOUR_SENDER_ID", + appId: "YOUR_APP_ID" +}; diff --git a/chrome-extension/firebase-database.js b/chrome-extension/firebase-database.js new file mode 100644 index 0000000..6ec05f6 --- /dev/null +++ b/chrome-extension/firebase-database.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase)}(this,function(Ru){"use strict";try{!function(){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var t=e(Ru),r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,t)};function n(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var l=function(){return(l=Object.assign||function(e){for(var t,n=1,r=arguments.length;na[0]&&t[1]=e.length?void 0:e)&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function y(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),a=[];try{for(;(void 0===t||0>6|192:(55296==(64512&i)&&r+1>18|240,t[n++]=i>>12&63|128):t[n++]=i>>12|224,t[n++]=i>>6&63|128),t[n++]=63&i|128)}return t}function s(e){try{return h.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}var u={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},g=function(e,t){if(!e)throw m(t)},m=function(e){return new Error("Firebase Database ("+u.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},h={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray:function(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();for(var n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[],i=0;i>2,o=(3&o)<<4|s>>4,s=(15&s)<<2|l>>6,l=63&l;u||(l=64,a||(s=64)),r.push(n[h],n[o],n[s],n[l])}return r.join("")},encodeString:function(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(o(e),t)},decodeString:function(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){for(var t=[],n=0,r=0;n>10)),t[r++]=String.fromCharCode(56320+(1023&i))):(o=e[n++],a=e[n++],t[r++]=String.fromCharCode((15&s)<<12|(63&o)<<6|63&a))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray:function(e,t){this.init_();for(var n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[],i=0;i>4;r.push(o),64!==s&&(a=a<<4&240|s>>2,r.push(a),64!==u&&(u=s<<6&192|u,r.push(u)))}return r},init_:function(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(var e=0;e=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};function c(e){return function e(t,n){if(!(n instanceof Object))return n;switch(n.constructor){case Date:var r=n;return new Date(r.getTime());case Object:void 0===t&&(t={});break;case Array:t=[];break;default:return n}for(var i in n)n.hasOwnProperty(i)&&d(i)&&(t[i]=e(t[i],n[i]));return t}(void 0,e)}function d(e){return"__proto__"!==e}var f=(v.prototype.wrapCallback=function(n){var r=this;return function(e,t){e?r.reject(e):r.resolve(t),"function"==typeof n&&(r.promise.catch(function(){}),1===n.length?n(e):n(e,t))}},v);function v(){var n=this;this.reject=function(){},this.resolve=function(){},this.promise=new Promise(function(e,t){n.resolve=e,n.reject=t})}function w(){return"undefined"!=typeof window&&(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test("undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:"")}function C(){return!0===u.NODE_ADMIN}var b,T="FirebaseError",E=(n(I,b=Error),I);function I(e,t,n){t=b.call(this,t)||this;return t.code=e,t.customData=n,t.name=T,Object.setPrototypeOf(t,I.prototype),Error.captureStackTrace&&Error.captureStackTrace(t,S.prototype.create),t}var S=(k.prototype.create=function(e){for(var t=[],n=1;n"})):"Error",e=this.serviceName+": "+e+" ("+o+").";return new E(o,e,i)},k);function k(e,t,n){this.service=e,this.serviceName=t,this.errors=n}var P=/\{\$([^}]+)}/g;function N(e){return JSON.parse(e)}function x(e){return JSON.stringify(e)}function R(e){var t={},n={},r={},i="";try{var o=e.split("."),t=N(s(o[0])||""),n=N(s(o[1])||""),i=o[2],r=n.d||{};delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function O(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function A(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function L(e,t,n){var r,i={};for(r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=t.call(n,e[r],r,e));return i}function M(e){for(var n=[],t=0,r=Object.entries(e);t>>31)}for(var o,a=this.chain_[0],s=this.chain_[1],u=this.chain_[2],l=this.chain_[3],h=this.chain_[4],r=0;r<80;r++)var c=r<40?r<20?(o=l^s&(u^l),1518500249):(o=s^u^l,1859775393):r<60?(o=s&u|l&(s|u),2400959708):(o=s^u^l,3395469782),i=(a<<5|a>>>27)+o+h+c+n[r]&4294967295,h=l,l=u,u=4294967295&(s<<30|s>>>2),s=a,a=i;this.chain_[0]=this.chain_[0]+a&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+u&4294967295,this.chain_[3]=this.chain_[3]+l&4294967295,this.chain_[4]=this.chain_[4]+h&4294967295},q.prototype.update=function(e,t){if(null!=e){for(var n=(t=void 0===t?e.length:t)-this.blockSize,r=0,i=this.buf_,o=this.inbuf_;r>i&255,++r;return e},q);function q(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(var e=1;e>6|192:(o<65536?t[n++]=o>>12|224:(t[n++]=o>>18|240,t[n++]=o>>12&63|128),t[n++]=o>>6&63|128),t[n++]=63&o|128)}return t}(e);return(e=new F).update(t),e=e.digest(),h.encodeByteArray(e)}function pe(e,t){g(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(be.logLevel=$.VERBOSE,Ie=be.log.bind(be),t&&Ce.set("logging_enabled",!0)):"function"==typeof e?Ie=e:(Ie=null,Ce.remove("logging_enabled"))}function de(){for(var e=[],t=0;t=Math.pow(2,-1022)?(n=(i=Math.min(Math.floor(Math.log(e)/Math.LN2),1023))+1023,Math.round(e*Math.pow(2,52-i)-Math.pow(2,52))):(n=0,Math.round(e/Math.pow(2,-1074))));for(var o=[],a=52;a;--a)o.push(r%2?1:0),r=Math.floor(r/2);for(a=11;a;--a)o.push(n%2?1:0),n=Math.floor(n/2);o.push(t?1:0),o.reverse();var s=o.join(""),u="";for(a=0;a<64;a+=8){var l=parseInt(s.substr(a,8),2).toString(16);u+=l=1===l.length?"0"+l:l}return u.toLowerCase()}function Fe(e,t){return"object"==typeof(t=setTimeout(e,t))&&t.unref&&t.unref(),t}var qe=new RegExp("^-?(0*)\\d{1,10}$"),We=-2147483648,je=2147483647,Ue=function(e){if(qe.test(e)){e=Number(e);if(We<=e&&e<=je)return e}return null},Be=function(e){try{e()}catch(t){setTimeout(function(){var e=t.stack||"";throw xe("Exception was thrown by user callback.",e),t},Math.floor(0))}},Ve=(ze.prototype.getToken=function(e){return this.appCheck?this.appCheck.getToken(e):Promise.resolve(null)},ze.prototype.addTokenChangeListener=function(t){var e;null!==(e=this.appCheckProvider)&&void 0!==e&&e.get().then(function(e){return e.addTokenListener(t)})},ze.prototype.notifyForInvalidToken=function(){xe('Provided AppCheck credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly.')},ze);function ze(e,t){var n=this;this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null!=t&&t.get().then(function(e){return n.appCheck=e})}var He=(Qe.prototype.getToken=function(e){return this.auth_?this.auth_.getToken(e).catch(function(e){return e&&"auth/token-not-initialized"===e.code?(ke("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)}):Promise.resolve(null)},Qe.prototype.addTokenChangeListener=function(t){this.auth_?this.auth_.addAuthTokenListener(t):(setTimeout(function(){return t(null)},0),this.authProvider_.get().then(function(e){return e.addAuthTokenListener(t)}))},Qe.prototype.removeTokenChangeListener=function(t){this.authProvider_.get().then(function(e){return e.removeAuthTokenListener(t)})},Qe.prototype.notifyForInvalidToken=function(){var e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',xe(e)},Qe);function Qe(e,t,n){var r=this;this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.get().then(function(e){return r.auth_=e})}var Ye=(Ke.prototype.getToken=function(e){return Promise.resolve({accessToken:this.accessToken})},Ke.prototype.addTokenChangeListener=function(e){e(this.accessToken)},Ke.prototype.removeTokenChangeListener=function(e){},Ke.prototype.notifyForInvalidToken=function(){},Ke.OWNER="owner",Ke);function Ke(e){this.accessToken=e}var Ge=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,$e="websocket",Je="long_polling",Xe=(Ze.prototype.isCacheableHost=function(){return"s-"===this.internalHost.substr(0,2)},Ze.prototype.isCustomHost=function(){return"firebaseio.com"!==this._domain&&"firebaseio-demo.com"!==this._domain},Object.defineProperty(Ze.prototype,"host",{get:function(){return this._host},set:function(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&we.set("host:"+this._host,this.internalHost))},enumerable:!1,configurable:!0}),Ze.prototype.toString=function(){var e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e},Ze.prototype.toURLString=function(){var e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?"?ns="+this.namespace:"";return e+this.host+"/"+t},Ze);function Ze(e,t,n,r,i,o,a){void 0===i&&(i=!1),void 0===o&&(o=""),void 0===a&&(a=!1),this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=o,this.includeNamespaceInQueryParams=a,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=we.get("host:"+e)||this._host}function et(e,t,n){var r;if(g("string"==typeof t,"typeof type must == string"),g("object"==typeof n,"typeof params must == object"),t===$e)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==Je)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}((t=e).host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams)&&(n.ns=e.namespace);var i=[];return Le(n,function(e,t){i.push(e+"="+t)}),r+i.join("&")}var tt=(nt.prototype.incrementCounter=function(e,t){void 0===t&&(t=1),D(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t},nt.prototype.get=function(){return c(this.counters_)},nt);function nt(){this.counters_={}}var rt={},it={};function ot(e){e=e.toString();return rt[e]||(rt[e]=new tt),rt[e]}var at=(st.prototype.closeAfter=function(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponsedocument.domain="'+document.domain+'";<\/script>':t)+"";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){ke("frame writing exception"),e.stack&&ke(e.stack),ke(e)}}var ft=null;"undefined"!=typeof MozWebSocket?ft=MozWebSocket:"undefined"!=typeof WebSocket&&(ft=WebSocket);var _t=(yt.connectionURL_=function(e,t,n,r){var i={v:"5"};return"undefined"!=typeof location&&location.hostname&&Ge.test(location.hostname)&&(i.r="f"),t&&(i.s=t),n&&(i.ls=n),r&&(i.ac=r),et(e,$e,i)},yt.prototype.open=function(t,e){var n,r=this;this.onDisconnect=e,this.onMessage=t,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,we.set("previous_websocket_failure",!0);try{C()||(n={headers:{"X-Firebase-GMPID":this.applicationId||"","X-Firebase-AppCheck":this.appCheckToken||""}},this.mySock=new ft(this.connURL,[],n))}catch(e){this.log_("Error instantiating WebSocket.");t=e.message||e.data;return t&&this.log_(t),void this.onClosed_()}this.mySock.onopen=function(){r.log_("Websocket connected."),r.everConnected_=!0},this.mySock.onclose=function(){r.log_("Websocket connection was disconnected."),r.mySock=null,r.onClosed_()},this.mySock.onmessage=function(e){r.handleIncomingFrame(e)},this.mySock.onerror=function(e){r.log_("WebSocket error. Closing connection.");e=e.message||e.data;e&&r.log_(e),r.onClosed_()}},yt.prototype.start=function(){},yt.forceDisallow=function(){yt.forceDisallow_=!0},yt.isAvailable=function(){var e,t=!1;return"undefined"!=typeof navigator&&navigator.userAgent&&((e=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/))&&1=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function At(e){return e.pieces_.length-e.pieceNum_}function Lt(e){var t=e.pieceNum_;return t=e.pieces_.length)return null;for(var t=[],n=e.pieceNum_;n=e.pieces_.length}function Ut(e,t){var n=Ot(e),r=Ot(t);if(null===n)return t;if(n===r)return Ut(Lt(e),Lt(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function Bt(e,t){for(var n=Ft(e,0),r=Ft(t,0),i=0;iAt(t))return!1;for(;nNt)throw new Error(e.errorPrefix_+"has a key path longer than "+Nt+" bytes ("+e.byteLength_+").");if(e.parts_.length>Pt)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+Pt+") or object contains a cycle "+Yt(e))}function Yt(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}var Kt,Gt=(n($t,Kt=Tt),$t.getInstance=function(){return new $t},$t.prototype.getInitialEvent=function(e){return g("visible"===e,"Unknown event type: "+e),[this.visible_]},$t);function $t(){var t,e,n=Kt.call(this,["visible"])||this;return"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(e="visibilitychange",t="hidden"):void 0!==document.mozHidden?(e="mozvisibilitychange",t="mozHidden"):void 0!==document.msHidden?(e="msvisibilitychange",t="msHidden"):void 0!==document.webkitHidden&&(e="webkitvisibilitychange",t="webkitHidden")),n.visible_=!0,e&&document.addEventListener(e,function(){var e=!document[t];e!==n.visible_&&(n.visible_=e,n.trigger("visible",e))},!1),n}var Jt,Xt=1e3,Zt=3e5,en=(n(tn,Jt=Ct),tn.prototype.sendRequest=function(e,t,n){var r=++this.requestNumber_,t={r:r,a:e,b:t};this.log_(x(t)),g(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(t),n&&(this.requestCBHash_[r]=n)},tn.prototype.get=function(e){var n=this,r=new f,i={p:e._path.toString(),q:e._queryObject},t={action:"g",request:i,onComplete:function(e){var t=e.d;"ok"===e.s?(n.onDataUpdate_(i.p,t,!1,null),r.resolve(t)):r.reject(t)}};this.outstandingGets_.push(t),this.outstandingGetCount_++;var o=this.outstandingGets_.length-1;return this.connected_||setTimeout(function(){var e=n.outstandingGets_[o];void 0!==e&&t===e&&(delete n.outstandingGets_[o],n.outstandingGetCount_--,0===n.outstandingGetCount_&&(n.outstandingGets_=[]),n.log_("get "+o+" timed out on connection"),r.reject(new Error("Client is offline.")))},3e3),this.connected_&&this.sendGet_(o),r.promise},tn.prototype.listen=function(e,t,n,r){var i=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+i),this.listens.has(o)||this.listens.set(o,new Map),g(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),g(!this.listens.get(o).has(i),"listen() called twice for same path/queryId.");n={onComplete:r,hashFn:t,query:e,tag:n};this.listens.get(o).set(i,n),this.connected_&&this.sendListen_(n)},tn.prototype.sendGet_=function(t){var n=this,r=this.outstandingGets_[t];this.sendRequest("g",r.request,function(e){delete n.outstandingGets_[t],n.outstandingGetCount_--,0===n.outstandingGetCount_&&(n.outstandingGets_=[]),r.onComplete&&r.onComplete(e)})},tn.prototype.sendListen_=function(r){var i=this,o=r.query,a=o._path.toString(),s=o._queryIdentifier;this.log_("Listen on "+a+" for "+s);var e={p:a};r.tag&&(e.q=o._queryObject,e.t=r.tag),e.h=r.hashFn(),this.sendRequest("q",e,function(e){var t=e.d,n=e.s;tn.warnOnListenWarnings_(t,o),(i.listens.get(a)&&i.listens.get(a).get(s))===r&&(i.log_("listen response",e),"ok"!==n&&i.removeListen_(a,s),r.onComplete&&r.onComplete(n,t))})},tn.warnOnListenWarnings_=function(e,t){e&&"object"==typeof e&&D(e,"w")&&(e=O(e,"w"),Array.isArray(e)&&~e.indexOf("no_index")&&(e='".indexOn": "'+t._queryParams.getIndex().toString()+'"',t=t._path.toString(),xe("Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding "+e+" at "+t+" to your security rules for better performance.")))},tn.prototype.refreshAuthToken=function(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},function(){}),this.reduceReconnectDelayIfAdminCredential_(e)},tn.prototype.reduceReconnectDelayIfAdminCredential_=function(e){(e&&40===e.length||function(e){e=R(e).claims;return"object"==typeof e&&!0===e.admin}(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)},tn.prototype.refreshAppCheckToken=function(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},function(){})},tn.prototype.tryAuth=function(){var n,e,t,r=this;this.connected_&&this.authToken_&&(e=function(e){e=R(e).claims;return!!e&&"object"==typeof e&&e.hasOwnProperty("iat")}(n=this.authToken_)?"auth":"gauth",t={cred:n},null===this.authOverride_?t.noauth=!0:"object"==typeof this.authOverride_&&(t.authvar=this.authOverride_),this.sendRequest(e,t,function(e){var t=e.s,e=e.d||"error";r.authToken_===n&&("ok"===t?r.invalidAuthTokenCount_=0:r.onAuthRevoked_(t,e))}))},tn.prototype.tryAppCheck=function(){var n=this;this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},function(e){var t=e.s,e=e.d||"error";"ok"===t?n.invalidAppCheckTokenCount_=0:n.onAppCheckRevoked_(t,e)})},tn.prototype.unlisten=function(e,t){var n=e._path.toString(),r=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+r),g(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)},tn.prototype.sendUnlisten_=function(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);e={p:e};r&&(e.q=n,e.t=r),this.sendRequest("n",e)},tn.prototype.onDisconnectPut=function(e,t,n){this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})},tn.prototype.onDisconnectMerge=function(e,t,n){this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})},tn.prototype.onDisconnectCancel=function(e,t){this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})},tn.prototype.sendOnDisconnect_=function(e,t,n,r){n={p:t,d:n};this.log_("onDisconnect "+e,n),this.sendRequest(e,n,function(e){r&&setTimeout(function(){r(e.s,e.d)},Math.floor(0))})},tn.prototype.put=function(e,t,n,r){this.putInternal("p",e,t,n,r)},tn.prototype.merge=function(e,t,n,r){this.putInternal("m",e,t,n,r)},tn.prototype.putInternal=function(e,t,n,r,i){n={p:t,d:n};void 0!==i&&(n.h=i),this.outstandingPuts_.push({action:e,request:n,onComplete:r}),this.outstandingPutCount_++;r=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(r):this.log_("Buffering put: "+t)},tn.prototype.sendPut_=function(t){var n=this,r=this.outstandingPuts_[t].action,e=this.outstandingPuts_[t].request,i=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(r,e,function(e){n.log_(r+" response",e),delete n.outstandingPuts_[t],n.outstandingPutCount_--,0===n.outstandingPutCount_&&(n.outstandingPuts_=[]),i&&i(e.s,e.d)})},tn.prototype.reportStats=function(e){var t=this;this.connected_&&(e={c:e},this.log_("reportStats",e),this.sendRequest("s",e,function(e){"ok"!==e.s&&(e=e.d,t.log_("reportStats","Error sending stats: "+e))}))},tn.prototype.onDataMessage_=function(e){if("r"in e){this.log_("from server: "+x(e));var t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}},tn.prototype.onDataPush_=function(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):de("Unrecognized action received from server: "+x(e)+"\nAre you using the latest client?")},tn.prototype.onReady_=function(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)},tn.prototype.scheduleConnect_=function(e){var t=this;g(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(function(){t.establishConnectionTimer_=null,t.establishConnection_()},Math.floor(e))},tn.prototype.onVisible_=function(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=Xt,this.realtime_||this.scheduleConnect_(0)),this.visible_=e},tn.prototype.onOnline_=function(e){e?(this.log_("Browser went online."),this.reconnectDelay_=Xt,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())},tn.prototype.onRealtimeDisconnect_=function(){var e;this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()&&(this.visible_?this.lastConnectionEstablishedTime_&&(3e4<(new Date).getTime()-this.lastConnectionEstablishedTime_&&(this.reconnectDelay_=Xt),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime()),e=(new Date).getTime()-this.lastConnectionAttemptTime_,e=Math.max(0,this.reconnectDelay_-e),e=Math.random()*e,this.log_("Trying to reconnect in "+e+"ms"),this.scheduleConnect_(e),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)),this.onConnectStatus_(!1)},tn.prototype.establishConnection_=function(){return i(this,void 0,void 0,function(){var t,n,r,i,o,a,s,u,l,h,c=this;return p(this,function(e){switch(e.label){case 0:if(!this.shouldReconnect_())return[3,4];this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null,t=this.onDataMessage_.bind(this),n=this.onReady_.bind(this),r=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+tn.nextConnectionId_++,h=this.lastSessionId,o=!1,a=null,s=function(){a?a.close():(o=!0,r())},l=function(e){g(a,"sendRequest call when we're not connected not allowed."),a.sendRequest(e)},this.realtime_={close:s,sendRequest:l},u=this.forceTokenRefresh_,this.forceTokenRefresh_=!1,e.label=1;case 1:return e.trys.push([1,3,,4]),[4,Promise.all([this.authTokenProvider_.getToken(u),this.appCheckTokenProvider_.getToken(u)])];case 2:return l=y.apply(void 0,[e.sent(),2]),u=l[0],l=l[1],o?ke("getToken() completed but was canceled"):(ke("getToken() completed. Creating connection."),this.authToken_=u&&u.accessToken,this.appCheckToken_=l&&l.token,a=new mt(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,t,n,r,function(e){xe(e+" ("+c.repoInfo_.toString()+")"),c.interrupt("server_kill")},h)),[3,4];case 3:return h=e.sent(),this.log_("Failed to get token: "+h),o||(this.repoInfo_.nodeAdmin&&xe(h),s()),[3,4];case 4:return[2]}})})},tn.prototype.interrupt=function(e){ke("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())},tn.prototype.resume=function(e){ke("Resuming connection for reason: "+e),delete this.interruptReasons_[e],A(this.interruptReasons_)&&(this.reconnectDelay_=Xt,this.realtime_||this.scheduleConnect_(0))},tn.prototype.handleTimestamp_=function(e){e-=(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:e})},tn.prototype.cancelSentTransactions_=function(){for(var e=0;eo.lastWriteId,"Stacking an older write on top of newer ones"),void 0===u&&(u=!0),o.allWrites.push({path:a,snap:s,writeId:r,visible:u}),u&&(o.visibleWrites=ai(o.visibleWrites,a,s)),o.lastWriteId=r,i?vo(e,new Ur(Ar(),t,n)):[]}function lo(e,t,n,r){var i,o,a;i=e.pendingWriteTree_,o=t,a=n,g((r=r)>i.lastWriteId,"Stacking an older merge on top of newer ones"),i.allWrites.push({path:o,children:a,writeId:r,visible:!0}),i.visibleWrites=si(i.visibleWrites,o,a),i.lastWriteId=r;n=ni.fromObject(n);return vo(e,new Vr(Ar(),t,n))}function ho(e,t,n){void 0===n&&(n=!1);var r=function(e,t){for(var n=0;nXo/3&&V(e)>Xo)throw new Error(r+"contains a string greater than "+Xo+" utf8 bytes "+Yt(i)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){var o=!1,a=!1;if(Le(e,function(e,t){if(".value"===e)o=!0;else if(".priority"!==e&&".sv"!==e&&(a=!0,!Ho(e)))throw new Error(r+" contains an invalid key ("+e+") "+Yt(i)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');var n;n=e,0<(e=i).parts_.length&&(e.byteLength_+=1),e.parts_.push(n),e.byteLength_+=V(n),Qt(e),ta(r,t,i),t=(e=i).parts_.pop(),e.byteLength_-=V(t),0=pa?(s=!0,t="maxretry",p.concat(ho(u.serverSyncTree_,o.currentWriteId,!0))):(n=Na(u,o.path,d),o.currentInputSnapshot=n,void 0!==(i=l[e].update(n.val()))?(ta("transaction failed: Data returned ",i,o.path),r=Hn(i),"object"==typeof i&&null!=i&&D(i,".priority")||(r=r.updatePriority(n.getPriority())),a=o.currentWriteId,i=va(u),i=Lo(r,n,i),o.currentOutputSnapshotRaw=r,o.currentOutputSnapshotResolved=i,o.currentWriteId=Ca(u),d.splice(d.indexOf(a),1),(p=p.concat(uo(u.serverSyncTree_,o.path,i,o.currentWriteId,o.applyLocally))).concat(ho(u.serverSyncTree_,a,!0))):(s=!0,t="nodata",p.concat(ho(u.serverSyncTree_,o.currentWriteId,!0))))),la(u.eventQueue_,h,p),p=[],s&&(l[e].status=2,s=l[e].unwatcher,setTimeout(s,Math.floor(0)),l[e].onComplete&&("nodata"===t?c.push(function(){return l[e].onComplete(null,!1,l[e].currentInputSnapshot)}):c.push(function(){return l[e].onComplete(new Error(t),!1,null)})))}(e);Aa(u,u.transactionQueueTree_);for(e=0;e.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||Ne("Cannot parse Firebase url. Please use https://.firebaseio.com"),n.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&xe("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");e="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new Xe(n.host,n.secure,r,t,e,"",r!==n.subdomain),path:new xt(n.pathString)}},qa=function(e){var t,n,r,i="",o="",a="",s="",u="",l=!0,h="https",c=443;return"string"==typeof e&&(0<=(r=e.indexOf("//"))&&(h=e.substring(0,r-1),e=e.substring(r+2)),-1===(t=e.indexOf("/"))&&(t=e.length),-1===(n=e.indexOf("?"))&&(n=e.length),i=e.substring(0,Math.min(t,n)),ts[0]&&e[1]>2,o=(3&o)<<4|a>>4,a=(15&a)<<2|c>>6,c=63&c;u||(c=64,s||(a=64)),r.push(n[h],n[o],n[a],n[c])}return r.join("")},encodeString:function(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(function(t){for(var e=[],n=0,r=0;r>6|192:(55296==(64512&i)&&r+1>18|240,e[n++]=i>>12&63|128):e[n++]=i>>12|224,e[n++]=i>>6&63|128),e[n++]=63&i|128)}return e}(t),e)},decodeString:function(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):function(t){for(var e=[],n=0,r=0;n>10)),e[r++]=String.fromCharCode(56320+(1023&i))):(o=t[n++],s=t[n++],e[r++]=String.fromCharCode((15&a)<<12|(63&o)<<6|63&s))}return e.join("")}(this.decodeStringToByteArray(t,e))},decodeStringToByteArray:function(t,e){this.init_();for(var n=e?this.charToByteMapWebSafe_:this.charToByteMap_,r=[],i=0;i>4;r.push(o),64!==a&&(s=s<<4&240|a>>2,r.push(s),64!==u&&(u=a<<6&192|u,r.push(u)))}return r},init_:function(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(var t=0;t=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}};function h(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}var i,u="FirebaseError",c=(n(l,i=Error),l);function l(t,e,n){e=i.call(this,e)||this;return e.code=t,e.customData=n,e.name=u,Object.setPrototypeOf(e,l.prototype),Error.captureStackTrace&&Error.captureStackTrace(e,f.prototype.create),e}var f=(d.prototype.create=function(t){for(var e=[],n=1;n"})):"Error",t=this.serviceName+": "+t+" ("+o+").";return new c(o,t,i)},d);function d(t,e,n){this.service=t,this.serviceName=e,this.errors=n}var p,m=/\{\$([^}]+)}/g;function v(t){return t&&t._delegate?t._delegate:t}(_e=p=p||{})[_e.DEBUG=0]="DEBUG",_e[_e.VERBOSE=1]="VERBOSE",_e[_e.INFO=2]="INFO",_e[_e.WARN=3]="WARN",_e[_e.ERROR=4]="ERROR",_e[_e.SILENT=5]="SILENT";function b(t,e){for(var n=[],r=2;r=t.length?void 0:t)&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}var D,N="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},C={},k=N||self;function R(){}function x(t){var e=typeof t;return"array"==(e="object"!=e?e:t?Array.isArray(t)?"array":e:"null")||"object"==e&&"number"==typeof t.length}function O(t){var e=typeof t;return"object"==e&&null!=t||"function"==e}var L="closure_uid_"+(1e9*Math.random()>>>0),P=0;function M(t,e,n){return t.call.apply(t.bind,arguments)}function F(e,n,t){if(!e)throw Error();if(2parseFloat(ft)){it=String(dt);break t}}it=ft}var pt={};function yt(a){return t=a,e=function(){for(var t=0,e=Y(String(it)).split("."),n=Y(String(a)).split("."),r=Math.max(e.length,n.length),i=0;0==t&&i>>0);function qt(e){return"function"==typeof e?e:(e[Ut]||(e[Ut]=function(t){return e.handleEvent(t)}),e[Ut])}function Bt(){j.call(this),this.c=new Dt(this),(this.J=this).C=null}function jt(t,e){var n,r=t.C;if(r)for(n=[];r;r=r.C)n.push(r);if(t=t.J,r=e.type||e,"string"==typeof e?e=new wt(e,t):e instanceof wt?e.target=e.target||t:(s=e,nt(e=new wt(r,t),s)),s=!0,n)for(var i=n.length-1;0<=i;i--)var o=e.a=n[i],s=Kt(o,r,!0,e)&&s;if(s=Kt(o=e.a=t,r,!0,e)&&s,s=Kt(o,r,!1,e)&&s,n)for(i=0;ia.length?Me:(a=a.substr(o,i),r.D=o+i,a)));if(a==Me){4==e&&(t.h=4,Ee(14),s=!1),pe(t.c,t.f,null,"[Incomplete Response]");break}if(a==Pe){t.h=4,Ee(15),pe(t.c,t.f,n,"[Invalid Chunk]"),s=!1;break}pe(t.c,t.f,a,null),Qe(t,a)}4==e&&0==n.length&&(t.h=1,Ee(16),s=!1),t.b=t.b&&s,s?0>4&15).toString(16)+(15&t).toString(16)}Je.prototype.toString=function(){var t=[],e=this.f;e&&t.push(an(e,cn,!0),":");var n=this.c;return!n&&"file"!=e||(t.push("//"),(e=this.j)&&t.push(an(e,cn,!0),"@"),t.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.h)&&t.push(":",String(n))),(n=this.g)&&(this.c&&"/"!=n.charAt(0)&&t.push("/"),t.push(an(n,"/"==n.charAt(0)?ln:hn,!0))),(n=this.b.toString())&&t.push("?",n),(n=this.i)&&t.push("#",an(n,dn)),t.join("")};var cn=/[#\/\?@]/g,hn=/[#\?:]/g,ln=/[#\?]/g,fn=/[#\?@]/g,dn=/#/g;function pn(t,e){this.b=this.a=null,this.c=t||null,this.f=!!e}function yn(n){n.a||(n.a=new He,n.b=0,n.c&&function(t,e){if(t){t=t.split("&");for(var n=0;n2*t.c&&We(t)))}function mn(t,e){return yn(t),e=bn(t,e),Ye(t.a.b,e)}function vn(t,e,n){gn(t,e),0=t.f}function _n(t){return t.b?1:t.a?t.a.size:0}function Sn(t,e){return t.b?t.b==e:t.a&&t.a.has(e)}function An(t,e){t.a?t.a.add(e):t.b=e}function Dn(t,e){t.b&&t.b==e?t.b=null:t.a&&t.a.has(e)&&t.a.delete(e)}function Nn(t){var e,n;if(null!=t.b)return t.c.concat(t.b.s);if(null==t.a||0===t.a.size)return z(t.c);var r=t.c;try{for(var i=A(t.a.values()),o=i.next();!o.done;o=i.next())var s=o.value,r=r.concat(s.s)}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(e)throw e.error}}return r}function Cn(){}function kn(){this.a=new Cn}function Rn(t,e,n,r,i){try{e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null,i(r)}catch(t){}}En.prototype.cancel=function(){var e,t;if(this.c=Nn(this),this.b)this.b.cancel(),this.b=null;else if(this.a&&0!==this.a.size){try{for(var n=A(this.a.values()),r=n.next();!r.done;r=n.next())r.value.cancel()}catch(t){e={error:t}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}this.a.clear()}},Cn.prototype.stringify=function(t){return k.JSON.stringify(t,void 0)},Cn.prototype.parse=function(t){return k.JSON.parse(t,void 0)};var xn=k.JSON.parse;function On(t){Bt.call(this),this.headers=new He,this.H=t||null,this.b=!1,this.s=this.a=null,this.B="",this.h=0,this.f="",this.g=this.A=this.l=this.u=!1,this.o=0,this.m=null,this.I=Ln,this.D=this.F=!1}B(On,Bt);var Ln="",Pn=/^https?$/i,Mn=["POST","PUT"];function Fn(t){return"content-type"==t.toLowerCase()}function Vn(t,e){t.b=!1,t.a&&(t.g=!0,t.a.abort(),t.g=!1),t.f=e,t.h=5,Un(t),Bn(t)}function Un(t){t.u||(t.u=!0,jt(t,"complete"),jt(t,"error"))}function qn(t){if(t.b&&void 0!==C&&(!t.s[1]||4!=Kn(t)||2!=t.W()))if(t.l&&4==Kn(t))ne(t.za,0,t);else if(jt(t,"readystatechange"),4==Kn(t)){t.b=!1;try{var e,n,r,i,o=t.W();t:switch(o){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var s=!0;break t;default:s=!1}(e=s)||((n=0===o)&&(!(i=String(t.B).match(Xe)[1]||null)&&k.self&&k.self.location&&(i=(r=k.self.location.protocol).substr(0,r.length-1)),n=!Pn.test(i?i.toLowerCase():"")),e=n);if(e)jt(t,"complete"),jt(t,"success");else{t.h=6;try{var a=2=r.b.f-(r.h?1:0)||(r.h?(r.g=i.s.concat(r.g),0):1==r.v||2==r.v||r.u>=(r.La?0:r.Ma)||(r.h=Ie(V(r.Ba,r,i),ar(r,r.u)),r.u++,0))))&&(2!=s||!nr(t)))switch(o&&0e.length?1:0},ci),ti=(n(ui,Zr=Se),ui.prototype.construct=function(t,e,n){return new ui(t,e,n)},ui.prototype.canonicalString=function(){return this.toArray().join("/")},ui.prototype.toString=function(){return this.canonicalString()},ui.fromString=function(){for(var t=[],e=0;et.length&&Vr(),void 0===n?n=t.length-e:n>t.length-e&&Vr(),this.segments=t,this.offset=e,this.len=n}ii.EMPTY_BYTE_STRING=new ii("");var hi=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function li(t){if(Ur(!!t),"string"!=typeof t)return{seconds:fi(t.seconds),nanos:fi(t.nanos)};var e=0,n=hi.exec(t);Ur(!!n),n[1]&&(n=((n=n[1])+"000000000").substr(0,9),e=Number(n));t=new Date(t);return{seconds:Math.floor(t.getTime()/1e3),nanos:e}}function fi(t){return"number"==typeof t?t:"string"==typeof t?Number(t):0}function di(t){return"string"==typeof t?ii.fromBase64String(t):ii.fromUint8Array(t)}function pi(t){return"server_timestamp"===(null===(t=((null===(t=null==t?void 0:t.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===t?void 0:t.stringValue)}function yi(t){t=li(t.mapValue.fields.__local_write_time__.timestampValue);return new Qr(t.seconds,t.nanos)}function gi(t){return null==t}function mi(t){return 0===t&&1/t==-1/0}function vi(t){return"number"==typeof t&&Number.isInteger(t)&&!mi(t)&&t<=Number.MAX_SAFE_INTEGER&&t>=Number.MIN_SAFE_INTEGER}var bi=(wi.fromPath=function(t){return new wi(ti.fromString(t))},wi.fromName=function(t){return new wi(ti.fromString(t).popFirst(5))},wi.prototype.hasCollectionId=function(t){return 2<=this.path.length&&this.path.get(this.path.length-2)===t},wi.prototype.isEqual=function(t){return null!==t&&0===ti.comparator(this.path,t.path)},wi.prototype.toString=function(){return this.path.toString()},wi.comparator=function(t,e){return ti.comparator(t.path,e.path)},wi.isDocumentKey=function(t){return t.length%2==0},wi.fromSegments=function(t){return new wi(new ti(t.slice()))},wi);function wi(t){this.path=t}function Ei(t){return"nullValue"in t?0:"booleanValue"in t?1:"integerValue"in t||"doubleValue"in t?2:"timestampValue"in t?3:"stringValue"in t?5:"bytesValue"in t?6:"referenceValue"in t?7:"geoPointValue"in t?8:"arrayValue"in t?9:"mapValue"in t?pi(t)?4:10:Vr()}function Ti(r,i){var t,e,n=Ei(r);if(n!==Ei(i))return!1;switch(n){case 0:return!0;case 1:return r.booleanValue===i.booleanValue;case 4:return yi(r).isEqual(yi(i));case 3:return function(t){if("string"==typeof r.timestampValue&&"string"==typeof t.timestampValue&&r.timestampValue.length===t.timestampValue.length)return r.timestampValue===t.timestampValue;var e=li(r.timestampValue),t=li(t.timestampValue);return e.seconds===t.seconds&&e.nanos===t.nanos}(i);case 5:return r.stringValue===i.stringValue;case 6:return e=i,di(r.bytesValue).isEqual(di(e.bytesValue));case 7:return r.referenceValue===i.referenceValue;case 8:return t=i,fi((e=r).geoPointValue.latitude)===fi(t.geoPointValue.latitude)&&fi(e.geoPointValue.longitude)===fi(t.geoPointValue.longitude);case 2:return function(t,e){if("integerValue"in t&&"integerValue"in e)return fi(t.integerValue)===fi(e.integerValue);if("doubleValue"in t&&"doubleValue"in e){t=fi(t.doubleValue),e=fi(e.doubleValue);return t===e?mi(t)===mi(e):isNaN(t)&&isNaN(e)}return!1}(r,i);case 9:return Kr(r.arrayValue.values||[],i.arrayValue.values||[],Ti);case 10:return function(){var t,e=r.mapValue.fields||{},n=i.mapValue.fields||{};if(Yr(e)!==Yr(n))return!1;for(t in e)if(e.hasOwnProperty(t)&&(void 0===n[t]||!Ti(e[t],n[t])))return!1;return!0}();default:return Vr()}}function Ii(t,e){return void 0!==(t.values||[]).find(function(t){return Ti(t,e)})}function _i(t,e){var n,r,i,o=Ei(t),s=Ei(e);if(o!==s)return jr(o,s);switch(o){case 0:return 0;case 1:return jr(t.booleanValue,e.booleanValue);case 2:return r=e,i=fi(t.integerValue||t.doubleValue),r=fi(r.integerValue||r.doubleValue),i":return 0=":return 0<=t;default:return Vr()}},Gi.prototype.g=function(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)},Gi);function Gi(t,e,n){var r=this;return(r=ji.call(this)||this).field=t,r.op=e,r.value=n,r}var Qi,zi,Hi,Wi=(n(Zi,Hi=Ki),Zi.prototype.matches=function(t){t=bi.comparator(t.key,this.key);return this.m(t)},Zi),Yi=(n($i,zi=Ki),$i.prototype.matches=function(e){return this.keys.some(function(t){return t.isEqual(e.key)})},$i),Xi=(n(Ji,Qi=Ki),Ji.prototype.matches=function(e){return!this.keys.some(function(t){return t.isEqual(e.key)})},Ji);function Ji(t,e){var n=this;return(n=Qi.call(this,t,"not-in",e)||this).keys=to(0,e),n}function $i(t,e){var n=this;return(n=zi.call(this,t,"in",e)||this).keys=to(0,e),n}function Zi(t,e,n){var r=this;return(r=Hi.call(this,t,e,n)||this).key=bi.fromName(n.referenceValue),r}function to(t,e){return((null===(e=e.arrayValue)||void 0===e?void 0:e.values)||[]).map(function(t){return bi.fromName(t.referenceValue)})}var eo,no,ro,io,oo=(n(po,io=Ki),po.prototype.matches=function(t){t=t.data.field(this.field);return Ci(t)&&Ii(t.arrayValue,this.value)},po),so=(n(fo,ro=Ki),fo.prototype.matches=function(t){t=t.data.field(this.field);return null!==t&&Ii(this.value.arrayValue,t)},fo),ao=(n(lo,no=Ki),lo.prototype.matches=function(t){if(Ii(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;t=t.data.field(this.field);return null!==t&&!Ii(this.value.arrayValue,t)},lo),uo=(n(ho,eo=Ki),ho.prototype.matches=function(t){var e=this,t=t.data.field(this.field);return!(!Ci(t)||!t.arrayValue.values)&&t.arrayValue.values.some(function(t){return Ii(e.value.arrayValue,t)})},ho),co=function(t,e){this.position=t,this.before=e};function ho(t,e){return eo.call(this,t,"array-contains-any",e)||this}function lo(t,e){return no.call(this,t,"not-in",e)||this}function fo(t,e){return ro.call(this,t,"in",e)||this}function po(t,e){return io.call(this,t,"array-contains",e)||this}function yo(t){return(t.before?"b":"a")+":"+t.position.map(Ai).join(",")}var go=function(t,e){void 0===e&&(e="asc"),this.field=t,this.dir=e};function mo(t,e,n){for(var r=0,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"},sa=function(t,e){this.databaseId=t,this.I=e};function aa(t,e){return t.I?new Date(1e3*e.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")+"."+("000000000"+e.nanoseconds).slice(-9)+"Z":{seconds:""+e.seconds,nanos:e.nanoseconds}}function ua(t,e){return t.I?e.toBase64():e.toUint8Array()}function ca(t){return Ur(!!t),zr.fromTimestamp((t=li(t),new Qr(t.seconds,t.nanos)))}function ha(t,e){return new ti(["projects",t.projectId,"databases",t.database]).child("documents").child(e).canonicalString()}function la(t){t=ti.fromString(t);return Ur(Ra(t)),t}function fa(t,e){return ha(t.databaseId,e.path)}function da(t,e){e=la(e);if(e.get(1)!==t.databaseId.projectId)throw new kr(Cr.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+e.get(1)+" vs "+t.databaseId.projectId);if(e.get(3)!==t.databaseId.database)throw new kr(Cr.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+e.get(3)+" vs "+t.databaseId.database);return new bi(ma(e))}function pa(t,e){return ha(t.databaseId,e)}function ya(t){t=la(t);return 4===t.length?ti.emptyPath():ma(t)}function ga(t){return new ti(["projects",t.databaseId.projectId,"databases",t.databaseId.database]).canonicalString()}function ma(t){return Ur(4";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";case"OPERATOR_UNSPECIFIED":default:return Vr()}}(),t.fieldFilter.value)}function ka(t){switch(t.unaryFilter.op){case"IS_NAN":var e=Na(t.unaryFilter.field);return Ki.create(e,"==",{doubleValue:NaN});case"IS_NULL":e=Na(t.unaryFilter.field);return Ki.create(e,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":var n=Na(t.unaryFilter.field);return Ki.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":n=Na(t.unaryFilter.field);return Ki.create(n,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":default:return Vr()}}function Ra(t){return 4<=t.length&&"projects"===t.get(0)&&"databases"===t.get(2)}function xa(t){for(var e="",n=0;n",t),this.store.put(t));return gu(t)},yu.prototype.add=function(t){return Lr("SimpleDb","ADD",this.store.name,t,t),gu(this.store.add(t))},yu.prototype.get=function(e){var n=this;return gu(this.store.get(e)).next(function(t){return void 0===t&&(t=null),Lr("SimpleDb","GET",n.store.name,e,t),t})},yu.prototype.delete=function(t){return Lr("SimpleDb","DELETE",this.store.name,t),gu(this.store.delete(t))},yu.prototype.count=function(){return Lr("SimpleDb","COUNT",this.store.name),gu(this.store.count())},yu.prototype.Nt=function(t,e){var e=this.cursor(this.options(t,e)),n=[];return this.xt(e,function(t,e){n.push(e)}).next(function(){return n})},yu.prototype.Ft=function(t,e){Lr("SimpleDb","DELETE ALL",this.store.name);e=this.options(t,e);e.kt=!1;e=this.cursor(e);return this.xt(e,function(t,e,n){return n.delete()})},yu.prototype.Ot=function(t,e){e?n=t:(n={},e=t);var n=this.cursor(n);return this.xt(n,e)},yu.prototype.$t=function(r){var t=this.cursor({});return new nu(function(n,e){t.onerror=function(t){t=vu(t.target.error);e(t)},t.onsuccess=function(t){var e=t.target.result;e?r(e.primaryKey,e.value).next(function(t){t?e.continue():n()}):n()}})},yu.prototype.xt=function(t,i){var o=[];return new nu(function(r,e){t.onerror=function(t){e(t.target.error)},t.onsuccess=function(t){var e,n=t.target.result;n?(e=new ou(n),(t=i(n.primaryKey,n.value,e))instanceof nu&&(t=t.catch(function(t){return e.done(),nu.reject(t)}),o.push(t)),e.isDone?r():null===e.Dt?n.continue():n.continue(e.Dt)):r()}}).next(function(){return nu.waitFor(o)})},yu.prototype.options=function(t,e){var n;return void 0!==t&&("string"==typeof t?n=t:e=t),{index:n,range:e}},yu.prototype.cursor=function(t){var e="next";if(t.reverse&&(e="prev"),t.index){var n=this.store.index(t.index);return t.kt?n.openKeyCursor(t.range,e):n.openCursor(t.range,e)}return this.store.openCursor(t.range,e)},yu);function yu(t){this.store=t}function gu(t){return new nu(function(e,n){t.onsuccess=function(t){t=t.target.result;e(t)},t.onerror=function(t){t=vu(t.target.error);n(t)}})}var mu=!1;function vu(t){var e=iu._t(h());if(12.2<=e&&e<13){e="An internal error was encountered in the Indexed Database server";if(0<=t.message.indexOf(e)){var n=new kr("internal","IOS_INDEXEDDB_BUG1: IndexedDb has thrown '"+e+"'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.");return mu||(mu=!0,setTimeout(function(){throw n},0)),n}}return t}var bu,wu=(n(Eu,bu=Se),Eu);function Eu(t,e){var n=this;return(n=bu.call(this)||this).Mt=t,n.currentSequenceNumber=e,n}function Tu(t,e){return iu.It(t.Mt,e)}var Iu=(Cu.prototype.applyToRemoteDocument=function(t,e){for(var n,r,i,o,s,a,u=e.mutationResults,c=0;c=i),o=Mu(r.R,e)),n.done()}).next(function(){return o})},rc.prototype.getHighestUnacknowledgedBatchId=function(t){var e=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]),r=-1;return oc(t).Ot({index:Va.userMutationsIndex,range:e,reverse:!0},function(t,e,n){r=e.batchId,n.done()}).next(function(){return r})},rc.prototype.getAllMutationBatches=function(t){var e=this,n=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return oc(t).Nt(Va.userMutationsIndex,n).next(function(t){return t.map(function(t){return Mu(e.R,t)})})},rc.prototype.getAllMutationBatchesAffectingDocumentKey=function(o,s){var a=this,t=Ua.prefixForPath(this.userId,s.path),t=IDBKeyRange.lowerBound(t),u=[];return sc(o).Ot({range:t},function(t,e,n){var r=t[0],i=t[1],t=t[2],i=La(i);if(r===a.userId&&s.path.isEqual(i))return oc(o).get(t).next(function(t){if(!t)throw Vr();Ur(t.userId===a.userId),u.push(Mu(a.R,t))});n.done()}).next(function(){return u})},rc.prototype.getAllMutationBatchesAffectingDocumentKeys=function(e,t){var s=this,a=new Ps(jr),n=[];return t.forEach(function(o){var t=Ua.prefixForPath(s.userId,o.path),t=IDBKeyRange.lowerBound(t),t=sc(e).Ot({range:t},function(t,e,n){var r=t[0],i=t[1],t=t[2],i=La(i);r===s.userId&&o.path.isEqual(i)?a=a.add(t):n.done()});n.push(t)}),nu.waitFor(n).next(function(){return s.Wt(e,a)})},rc.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var o=this,s=e.path,a=s.length+1,e=Ua.prefixForPath(this.userId,s),e=IDBKeyRange.lowerBound(e),u=new Ps(jr);return sc(t).Ot({range:e},function(t,e,n){var r=t[0],i=t[1],t=t[2],i=La(i);r===o.userId&&s.isPrefixOf(i)?i.length===a&&(u=u.add(t)):n.done()}).next(function(){return o.Wt(t,u)})},rc.prototype.Wt=function(e,t){var n=this,r=[],i=[];return t.forEach(function(t){i.push(oc(e).get(t).next(function(t){if(null===t)throw Vr();Ur(t.userId===n.userId),r.push(Mu(n.R,t))}))}),nu.waitFor(i).next(function(){return r})},rc.prototype.removeMutationBatch=function(e,n){var r=this;return tc(e.Mt,this.userId,n).next(function(t){return e.addOnCommittedListener(function(){r.Gt(n.batchId)}),nu.forEach(t,function(t){return r.referenceDelegate.markPotentiallyOrphaned(e,t)})})},rc.prototype.Gt=function(t){delete this.Qt[t]},rc.prototype.performConsistencyCheck=function(e){var i=this;return this.checkEmpty(e).next(function(t){if(!t)return nu.resolve();var t=IDBKeyRange.lowerBound(Ua.prefixForUser(i.userId)),r=[];return sc(e).Ot({range:t},function(t,e,n){t[0]===i.userId?(t=La(t[1]),r.push(t)):n.done()}).next(function(){Ur(0===r.length)})})},rc.prototype.containsKey=function(t,e){return ic(t,this.userId,e)},rc.prototype.zt=function(t){var e=this;return ac(t).get(this.userId).next(function(t){return t||new Fa(e.userId,-1,"")})},rc);function rc(t,e,n,r){this.userId=t,this.R=e,this.Ut=n,this.referenceDelegate=r,this.Qt={}}function ic(t,o,e){var e=Ua.prefixForPath(o,e.path),s=e[1],e=IDBKeyRange.lowerBound(e),a=!1;return sc(t).Ot({range:e,kt:!0},function(t,e,n){var r=t[0],i=t[1];t[2],r===o&&i===s&&(a=!0),n.done()}).next(function(){return a})}function oc(t){return Tu(t,Va.store)}function sc(t){return Tu(t,Ua.store)}function ac(t){return Tu(t,Fa.store)}var uc=(lc.prototype.next=function(){return this.Ht+=2,this.Ht},lc.Jt=function(){return new lc(0)},lc.Yt=function(){return new lc(-1)},lc),cc=(hc.prototype.allocateTargetId=function(n){var r=this;return this.Xt(n).next(function(t){var e=new uc(t.highestTargetId);return t.highestTargetId=e.next(),r.Zt(n,t).next(function(){return t.highestTargetId})})},hc.prototype.getLastRemoteSnapshotVersion=function(t){return this.Xt(t).next(function(t){return zr.fromTimestamp(new Qr(t.lastRemoteSnapshotVersion.seconds,t.lastRemoteSnapshotVersion.nanoseconds))})},hc.prototype.getHighestSequenceNumber=function(t){return this.Xt(t).next(function(t){return t.highestListenSequenceNumber})},hc.prototype.setTargetsMetadata=function(e,n,r){var i=this;return this.Xt(e).next(function(t){return t.highestListenSequenceNumber=n,r&&(t.lastRemoteSnapshotVersion=r.toTimestamp()),n>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=n),i.Zt(e,t)})},hc.prototype.addTargetData=function(e,n){var r=this;return this.te(e,n).next(function(){return r.Xt(e).next(function(t){return t.targetCount+=1,r.ee(n,t),r.Zt(e,t)})})},hc.prototype.updateTargetData=function(t,e){return this.te(t,e)},hc.prototype.removeTargetData=function(e,t){var n=this;return this.removeMatchingKeysForTargetId(e,t.targetId).next(function(){return fc(e).delete(t.targetId)}).next(function(){return n.Xt(e)}).next(function(t){return Ur(0e.highestTargetId&&(e.highestTargetId=t.targetId,n=!0),t.sequenceNumber>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=t.sequenceNumber,n=!0),n},hc.prototype.getTargetCount=function(t){return this.Xt(t).next(function(t){return t.targetCount})},hc.prototype.getTargetData=function(t,r){var e=Ui(r),e=IDBKeyRange.bound([e,Number.NEGATIVE_INFINITY],[e,Number.POSITIVE_INFINITY]),i=null;return fc(t).Ot({range:e,index:Qa.queryTargetsIndexName},function(t,e,n){e=Fu(e);qi(r,e.target)&&(i=e,n.done())}).next(function(){return i})},hc.prototype.addMatchingKeys=function(n,t,r){var i=this,o=[],s=pc(n);return t.forEach(function(t){var e=xa(t.path);o.push(s.put(new za(r,e))),o.push(i.referenceDelegate.addReference(n,r,t))}),nu.waitFor(o)},hc.prototype.removeMatchingKeys=function(n,t,r){var i=this,o=pc(n);return nu.forEach(t,function(t){var e=xa(t.path);return nu.waitFor([o.delete([r,e]),i.referenceDelegate.removeReference(n,r,t)])})},hc.prototype.removeMatchingKeysForTargetId=function(t,e){t=pc(t),e=IDBKeyRange.bound([e],[e+1],!1,!0);return t.delete(e)},hc.prototype.getMatchingKeysForTargetId=function(t,e){var e=IDBKeyRange.bound([e],[e+1],!1,!0),t=pc(t),r=Ks();return t.Ot({range:e,kt:!0},function(t,e,n){t=La(t[1]),t=new bi(t);r=r.add(t)}).next(function(){return r})},hc.prototype.containsKey=function(t,e){var e=xa(e.path),e=IDBKeyRange.bound([e],[Gr(e)],!1,!0),i=0;return pc(t).Ot({index:za.documentTargetsIndex,kt:!0,range:e},function(t,e,n){var r=t[0];t[1],0!==r&&(i++,n.done())}).next(function(){return 0h.params.maximumSequenceNumbersToCollect?(Lr("LruGarbageCollector","Capping sequence numbers to collect down to the maximum of "+h.params.maximumSequenceNumbersToCollect+" from "+t),h.params.maximumSequenceNumbersToCollect):t,s=Date.now(),h.nthSequenceNumber(e,i)}).next(function(t){return r=t,a=Date.now(),h.removeTargets(e,r,n)}).next(function(t){return o=t,u=Date.now(),h.removeOrphanedDocuments(e,r)}).next(function(t){return c=Date.now(),Or()<=p.DEBUG&&Lr("LruGarbageCollector","LRU Garbage Collection\n\tCounted targets in "+(s-l)+"ms\n\tDetermined least recently used "+i+" in "+(a-s)+"ms\n\tRemoved "+o+" targets in "+(u-a)+"ms\n\tRemoved "+t+" documents in "+(c-u)+"ms\nTotal Duration: "+(c-l)+"ms"),nu.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:o,documentsRemoved:t})})},Tc),wc=(Ec.prototype.he=function(t){var n=this.de(t);return this.db.getTargetCache().getTargetCount(t).next(function(e){return n.next(function(t){return e+t})})},Ec.prototype.de=function(t){var e=0;return this.le(t,function(t){e++}).next(function(){return e})},Ec.prototype.forEachTarget=function(t,e){return this.db.getTargetCache().forEachTarget(t,e)},Ec.prototype.le=function(t,n){return this.we(t,function(t,e){return n(e)})},Ec.prototype.addReference=function(t,e,n){return Sc(t,n)},Ec.prototype.removeReference=function(t,e,n){return Sc(t,n)},Ec.prototype.removeTargets=function(t,e,n){return this.db.getTargetCache().removeTargets(t,e,n)},Ec.prototype.markPotentiallyOrphaned=Sc,Ec.prototype._e=function(t,e){return r=e,i=!1,ac(n=t).$t(function(t){return ic(n,t,r).next(function(t){return t&&(i=!0),nu.resolve(!t)})}).next(function(){return i});var n,r,i},Ec.prototype.removeOrphanedDocuments=function(n,r){var i=this,o=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[],a=0;return this.we(n,function(e,t){t<=r&&(t=i._e(n,e).next(function(t){if(!t)return a++,o.getEntry(n,e).next(function(){return o.removeEntry(e),pc(n).delete([0,xa(e.path)])})}),s.push(t))}).next(function(){return nu.waitFor(s)}).next(function(){return o.apply(n)}).next(function(){return a})},Ec.prototype.removeTarget=function(t,e){e=e.withSequenceNumber(t.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(t,e)},Ec.prototype.updateLimboDocument=Sc,Ec.prototype.we=function(t,r){var i,t=pc(t),o=Ar.o;return t.Ot({index:za.documentTargetsIndex},function(t,e){var n=t[0],t=(t[1],e.path),e=e.sequenceNumber;0===n?(o!==Ar.o&&r(new bi(La(i)),o),o=e,i=t):o=Ar.o}).next(function(){o!==Ar.o&&r(new bi(La(i)),o)})},Ec.prototype.getCacheSize=function(t){return this.db.getRemoteDocumentCache().getSize(t)},Ec);function Ec(t,e){this.db=t,this.garbageCollector=new bc(this,e)}function Tc(t,e){this.ae=t,this.params=e}function Ic(t,e){this.garbageCollector=t,this.asyncQueue=e,this.oe=!1,this.ce=null}function _c(t){this.ne=t,this.buffer=new Ps(gc),this.se=0}function Sc(t,e){return pc(t).put((t=t.currentSequenceNumber,new za(0,xa(e.path),t)))}var Ac,Dc=(Oc.prototype.get=function(t){var e=this.mapKeyFn(t),e=this.inner[e];if(void 0!==e)for(var n=0,r=e;n "+n),1))},jc.prototype.We=function(){var t=this;null!==this.document&&"function"==typeof this.document.addEventListener&&(this.ke=function(){t.Se.enqueueAndForget(function(){return t.inForeground="visible"===t.document.visibilityState,t.je()})},this.document.addEventListener("visibilitychange",this.ke),this.inForeground="visible"===this.document.visibilityState)},jc.prototype.an=function(){this.ke&&(this.document.removeEventListener("visibilitychange",this.ke),this.ke=null)},jc.prototype.Ge=function(){var t,e=this;"function"==typeof(null===(t=this.window)||void 0===t?void 0:t.addEventListener)&&(this.Fe=function(){e.un(),e.Se.enqueueAndForget(function(){return e.shutdown()})},this.window.addEventListener("unload",this.Fe))},jc.prototype.hn=function(){this.Fe&&(this.window.removeEventListener("unload",this.Fe),this.Fe=null)},jc.prototype.cn=function(t){try{var e=null!==(null===(e=this.Ke)||void 0===e?void 0:e.getItem(this.on(t)));return Lr("IndexedDbPersistence","Client '"+t+"' "+(e?"is":"is not")+" zombied in LocalStorage"),e}catch(t){return Pr("IndexedDbPersistence","Failed to get zombied client id.",t),!1}},jc.prototype.un=function(){if(this.Ke)try{this.Ke.setItem(this.on(this.clientId),String(Date.now()))}catch(t){Pr("Failed to set zombie client id.",t)}},jc.prototype.ln=function(){if(this.Ke)try{this.Ke.removeItem(this.on(this.clientId))}catch(t){}},jc.prototype.on=function(t){return"firestore_zombie_"+this.persistenceKey+"_"+t},jc);function jc(t,e,n,r,i,o,s,a,u,c){if(this.allowTabSynchronization=t,this.persistenceKey=e,this.clientId=n,this.Se=i,this.window=o,this.document=s,this.De=u,this.Ce=c,this.Ne=null,this.xe=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Fe=null,this.inForeground=!1,this.ke=null,this.Oe=null,this.$e=Number.NEGATIVE_INFINITY,this.Me=function(t){return Promise.resolve()},!jc.yt())throw new kr(Cr.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new wc(this,r),this.Le=e+"main",this.R=new Au(a),this.Be=new iu(this.Le,11,new Fc(this.R)),this.qe=new cc(this.referenceDelegate,this.R),this.Ut=new zu,this.Ue=(e=this.R,a=this.Ut,new Nc(e,a)),this.Qe=new qu,this.window&&this.window.localStorage?this.Ke=this.window.localStorage:(this.Ke=null,!1===c&&Pr("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}function Kc(t){return Tu(t,Pa.store)}function Gc(t){return Tu(t,Ya.store)}function Qc(t,e){var n=t.projectId;return t.isDefaultDatabase||(n+="."+t.database),"firestore/"+e+"/"+n+"/"}function zc(t,e){this.progress=t,this.wn=e}var Hc=(th.prototype.mn=function(e,n){var r=this;return this._n.getAllMutationBatchesAffectingDocumentKey(e,n).next(function(t){return r.yn(e,n,t)})},th.prototype.yn=function(t,e,r){return this.Ue.getEntry(t,e).next(function(t){for(var e=0,n=r;ee?this._n[e]:null)},Oh.prototype.getHighestUnacknowledgedBatchId=function(){return nu.resolve(0===this._n.length?-1:this.ss-1)},Oh.prototype.getAllMutationBatches=function(t){return nu.resolve(this._n.slice())},Oh.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=new mh(e,0),e=new mh(e,Number.POSITIVE_INFINITY),i=[];return this.rs.forEachInRange([r,e],function(t){t=n.os(t.ns);i.push(t)}),nu.resolve(i)},Oh.prototype.getAllMutationBatchesAffectingDocumentKeys=function(t,e){var n=this,r=new Ps(jr);return e.forEach(function(t){var e=new mh(t,0),t=new mh(t,Number.POSITIVE_INFINITY);n.rs.forEachInRange([e,t],function(t){r=r.add(t.ns)})}),nu.resolve(this.us(r))},Oh.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=e.path,r=n.length+1,e=n;bi.isDocumentKey(e)||(e=e.child(""));var e=new mh(new bi(e),0),i=new Ps(jr);return this.rs.forEachWhile(function(t){var e=t.key.path;return!!n.isPrefixOf(e)&&(e.length===r&&(i=i.add(t.ns)),!0)},e),nu.resolve(this.us(i))},Oh.prototype.us=function(t){var e=this,n=[];return t.forEach(function(t){t=e.os(t);null!==t&&n.push(t)}),n},Oh.prototype.removeMutationBatch=function(n,r){var i=this;Ur(0===this.hs(r.batchId,"removed")),this._n.shift();var o=this.rs;return nu.forEach(r.mutations,function(t){var e=new mh(t.key,r.batchId);return o=o.delete(e),i.referenceDelegate.markPotentiallyOrphaned(n,t.key)}).next(function(){i.rs=o})},Oh.prototype.Gt=function(t){},Oh.prototype.containsKey=function(t,e){var n=new mh(e,0),n=this.rs.firstAfterOrEqual(n);return nu.resolve(e.isEqual(n&&n.key))},Oh.prototype.performConsistencyCheck=function(t){return this._n.length,nu.resolve()},Oh.prototype.hs=function(t,e){return this.cs(t)},Oh.prototype.cs=function(t){return 0===this._n.length?0:t-this._n[0].batchId},Oh.prototype.os=function(t){t=this.cs(t);return t<0||t>=this._n.length?null:this._n[t]},Oh),bh=(xh.prototype.addEntry=function(t,e,n){var r=e.key,i=this.docs.get(r),o=i?i.size:0,i=this.ls(e);return this.docs=this.docs.insert(r,{document:e.clone(),size:i,readTime:n}),this.size+=i-o,this.Ut.addToCollectionParentIndex(t,r.path.popLast())},xh.prototype.removeEntry=function(t){var e=this.docs.get(t);e&&(this.docs=this.docs.remove(t),this.size-=e.size)},xh.prototype.getEntry=function(t,e){var n=this.docs.get(e);return nu.resolve(n?n.document.clone():Pi.newInvalidDocument(e))},xh.prototype.getEntries=function(t,e){var n=this,r=Fs;return e.forEach(function(t){var e=n.docs.get(t);r=r.insert(t,e?e.document.clone():Pi.newInvalidDocument(t))}),nu.resolve(r)},xh.prototype.getDocumentsMatchingQuery=function(t,e,n){for(var r=Fs,i=new bi(e.path.child("")),o=this.docs.getIteratorFrom(i);o.hasNext();){var s=o.getNext(),a=s.key,u=s.value,s=u.document,u=u.readTime;if(!e.path.isPrefixOf(a.path))break;u.compareTo(n)<=0||Oo(e,s)&&(r=r.insert(s.key,s.clone()))}return nu.resolve(r)},xh.prototype.fs=function(t,e){return nu.forEach(this.docs,function(t){return e(t)})},xh.prototype.newChangeBuffer=function(t){return new wh(this)},xh.prototype.getSize=function(t){return nu.resolve(this.size)},xh),wh=(n(Rh,ph=I),Rh.prototype.applyChanges=function(n){var r=this,i=[];return this.changes.forEach(function(t,e){e.document.isValidDocument()?i.push(r.Ie.addEntry(n,e.document,r.getReadTime(t))):r.Ie.removeEntry(t)}),nu.waitFor(i)},Rh.prototype.getFromCache=function(t,e){return this.Ie.getEntry(t,e)},Rh.prototype.getAllFromCache=function(t,e){return this.Ie.getEntries(t,e)},Rh),Eh=(kh.prototype.forEachTarget=function(t,n){return this.ds.forEach(function(t,e){return n(e)}),nu.resolve()},kh.prototype.getLastRemoteSnapshotVersion=function(t){return nu.resolve(this.lastRemoteSnapshotVersion)},kh.prototype.getHighestSequenceNumber=function(t){return nu.resolve(this.ws)},kh.prototype.allocateTargetId=function(t){return this.highestTargetId=this.ys.next(),nu.resolve(this.highestTargetId)},kh.prototype.setTargetsMetadata=function(t,e,n){return n&&(this.lastRemoteSnapshotVersion=n),e>this.ws&&(this.ws=e),nu.resolve()},kh.prototype.te=function(t){this.ds.set(t.target,t);var e=t.targetId;e>this.highestTargetId&&(this.ys=new uc(e),this.highestTargetId=e),t.sequenceNumber>this.ws&&(this.ws=t.sequenceNumber)},kh.prototype.addTargetData=function(t,e){return this.te(e),this.targetCount+=1,nu.resolve()},kh.prototype.updateTargetData=function(t,e){return this.te(e),nu.resolve()},kh.prototype.removeTargetData=function(t,e){return this.ds.delete(e.target),this._s.Zn(e.targetId),--this.targetCount,nu.resolve()},kh.prototype.removeTargets=function(n,r,i){var o=this,s=0,a=[];return this.ds.forEach(function(t,e){e.sequenceNumber<=r&&null===i.get(e.targetId)&&(o.ds.delete(t),a.push(o.removeMatchingKeysForTargetId(n,e.targetId)),s++)}),nu.waitFor(a).next(function(){return s})},kh.prototype.getTargetCount=function(t){return nu.resolve(this.targetCount)},kh.prototype.getTargetData=function(t,e){e=this.ds.get(e)||null;return nu.resolve(e)},kh.prototype.addMatchingKeys=function(t,e,n){return this._s.Jn(e,n),nu.resolve()},kh.prototype.removeMatchingKeys=function(e,t,n){this._s.Xn(t,n);var r=this.persistence.referenceDelegate,i=[];return r&&t.forEach(function(t){i.push(r.markPotentiallyOrphaned(e,t))}),nu.waitFor(i)},kh.prototype.removeMatchingKeysForTargetId=function(t,e){return this._s.Zn(e),nu.resolve()},kh.prototype.getMatchingKeysForTargetId=function(t,e){e=this._s.es(e);return nu.resolve(e)},kh.prototype.containsKey=function(t,e){return nu.resolve(this._s.containsKey(e))},kh),Th=(Ch.prototype.start=function(){return Promise.resolve()},Ch.prototype.shutdown=function(){return this.xe=!1,Promise.resolve()},Object.defineProperty(Ch.prototype,"started",{get:function(){return this.xe},enumerable:!1,configurable:!0}),Ch.prototype.setDatabaseDeletedListener=function(){},Ch.prototype.setNetworkEnabled=function(){},Ch.prototype.getIndexManager=function(){return this.Ut},Ch.prototype.getMutationQueue=function(t){var e=this.gs[t.toKey()];return e||(e=new vh(this.Ut,this.referenceDelegate),this.gs[t.toKey()]=e),e},Ch.prototype.getTargetCache=function(){return this.qe},Ch.prototype.getRemoteDocumentCache=function(){return this.Ue},Ch.prototype.getBundleCache=function(){return this.Qe},Ch.prototype.runTransaction=function(t,e,n){var r=this;Lr("MemoryPersistence","Starting transaction:",t);var i=new Ih(this.Ne.next());return this.referenceDelegate.Es(),n(i).next(function(t){return r.referenceDelegate.Ts(i).next(function(){return t})}).toPromise().then(function(t){return i.raiseOnCommittedEvent(),t})},Ch.prototype.Is=function(e,n){return nu.or(Object.values(this.gs).map(function(t){return function(){return t.containsKey(e,n)}}))},Ch),Ih=(n(Nh,dh=Se),Nh),_h=(Dh.bs=function(t){return new Dh(t)},Object.defineProperty(Dh.prototype,"vs",{get:function(){if(this.Rs)return this.Rs;throw Vr()},enumerable:!1,configurable:!0}),Dh.prototype.addReference=function(t,e,n){return this.As.addReference(n,e),this.vs.delete(n.toString()),nu.resolve()},Dh.prototype.removeReference=function(t,e,n){return this.As.removeReference(n,e),this.vs.add(n.toString()),nu.resolve()},Dh.prototype.markPotentiallyOrphaned=function(t,e){return this.vs.add(e.toString()),nu.resolve()},Dh.prototype.removeTarget=function(t,e){var n=this;this.As.Zn(e.targetId).forEach(function(t){return n.vs.add(t.toString())});var r=this.persistence.getTargetCache();return r.getMatchingKeysForTargetId(t,e.targetId).next(function(t){t.forEach(function(t){return n.vs.add(t.toString())})}).next(function(){return r.removeTargetData(t,e)})},Dh.prototype.Es=function(){this.Rs=new Set},Dh.prototype.Ts=function(n){var r=this,i=this.persistence.getRemoteDocumentCache().newChangeBuffer();return nu.forEach(this.vs,function(t){var e=bi.fromPath(t);return r.Ps(n,e).next(function(t){t||i.removeEntry(e)})}).next(function(){return r.Rs=null,i.apply(n)})},Dh.prototype.updateLimboDocument=function(t,e){var n=this;return this.Ps(t,e).next(function(t){t?n.vs.delete(e.toString()):n.vs.add(e.toString())})},Dh.prototype.ps=function(t){return 0},Dh.prototype.Ps=function(t,e){var n=this;return nu.or([function(){return nu.resolve(n.As.containsKey(e))},function(){return n.persistence.getTargetCache().containsKey(t,e)},function(){return n.persistence.Is(t,e)}])},Dh),Sh=(Ah.prototype.isAuthenticated=function(){return null!=this.uid},Ah.prototype.toKey=function(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"},Ah.prototype.isEqual=function(t){return t.uid===this.uid},Ah);function Ah(t){this.uid=t}function Dh(t){this.persistence=t,this.As=new gh,this.Rs=null}function Nh(t){var e=this;return(e=dh.call(this)||this).currentSequenceNumber=t,e}function Ch(t,e){var n=this;this.gs={},this.Ne=new Ar(0),this.xe=!1,this.xe=!0,this.referenceDelegate=t(this),this.qe=new Eh(this),this.Ut=new Gu,this.Ue=(t=this.Ut,new bh(t,function(t){return n.referenceDelegate.ps(t)})),this.R=new Au(e),this.Qe=new yh(this.R)}function kh(t){this.persistence=t,this.ds=new Dc(Ui,qi),this.lastRemoteSnapshotVersion=zr.min(),this.highestTargetId=0,this.ws=0,this._s=new gh,this.targetCount=0,this.ys=uc.Jt()}function Rh(t){var e=this;return(e=ph.call(this)||this).Ie=t,e}function xh(t,e){this.Ut=t,this.ls=e,this.docs=new Ns(bi.comparator),this.size=0}function Oh(t,e){this.Ut=t,this.referenceDelegate=e,this._n=[],this.ss=1,this.rs=new Ps(mh.Gn)}function Lh(t,e){this.key=t,this.ns=e}function Ph(){this.Wn=new Ps(mh.Gn),this.zn=new Ps(mh.Hn)}function Mh(t){this.R=t,this.Kn=new Map,this.jn=new Map}function Fh(t,e){return"firestore_clients_"+t+"_"+e}function Vh(t,e,n){n="firestore_mutations_"+t+"_"+n;return e.isAuthenticated()&&(n+="_"+e.uid),n}function Uh(t,e){return"firestore_targets_"+t+"_"+e}Sh.UNAUTHENTICATED=new Sh(null),Sh.GOOGLE_CREDENTIALS=new Sh("google-credentials-uid"),Sh.FIRST_PARTY=new Sh("first-party-uid");var qh,Bh=(hl.Vs=function(t,e,n){var r,i=JSON.parse(n),o="object"==typeof i&&-1!==["pending","acknowledged","rejected"].indexOf(i.state)&&(void 0===i.error||"object"==typeof i.error);return o&&i.error&&(o="string"==typeof i.error.message&&"string"==typeof i.error.code)&&(r=new kr(i.error.code,i.error.message)),o?new hl(t,e,i.state,r):(Pr("SharedClientState","Failed to parse mutation state for ID '"+e+"': "+n),null)},hl.prototype.Ss=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)},hl),jh=(cl.Vs=function(t,e){var n,r=JSON.parse(e),i="object"==typeof r&&-1!==["not-current","current","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return i&&r.error&&(i="string"==typeof r.error.message&&"string"==typeof r.error.code)&&(n=new kr(r.error.code,r.error.message)),i?new cl(t,r.state,n):(Pr("SharedClientState","Failed to parse target state for ID '"+t+"': "+e),null)},cl.prototype.Ss=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)},cl),Kh=(ul.Vs=function(t,e){for(var n=JSON.parse(e),r="object"==typeof n&&n.activeTargetIds instanceof Array,i=Gs,o=0;r&&othis.Bi&&(this.qi=this.Bi)},Nl.prototype.Gi=function(){null!==this.Ui&&(this.Ui.skipDelay(),this.Ui=null)},Nl.prototype.cancel=function(){null!==this.Ui&&(this.Ui.cancel(),this.Ui=null)},Nl.prototype.Wi=function(){return(Math.random()-.5)*this.qi},Nl),I=(Dl.prototype.tr=function(){return 1===this.state||2===this.state||4===this.state},Dl.prototype.er=function(){return 2===this.state},Dl.prototype.start=function(){3!==this.state?this.auth():this.nr()},Dl.prototype.stop=function(){return y(this,void 0,void 0,function(){return g(this,function(t){switch(t.label){case 0:return this.tr()?[4,this.close(0)]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})})},Dl.prototype.sr=function(){this.state=0,this.Zi.reset()},Dl.prototype.ir=function(){var t=this;this.er()&&null===this.Xi&&(this.Xi=this.Se.enqueueAfterDelay(this.zi,6e4,function(){return t.rr()}))},Dl.prototype.cr=function(t){this.ur(),this.stream.send(t)},Dl.prototype.rr=function(){return y(this,void 0,void 0,function(){return g(this,function(t){return this.er()?[2,this.close(0)]:[2]})})},Dl.prototype.ur=function(){this.Xi&&(this.Xi.cancel(),this.Xi=null)},Dl.prototype.close=function(e,n){return y(this,void 0,void 0,function(){return g(this,function(t){switch(t.label){case 0:return this.ur(),this.Zi.cancel(),this.Yi++,3!==e?this.Zi.reset():n&&n.code===Cr.RESOURCE_EXHAUSTED?(Pr(n.toString()),Pr("Using maximum backoff delay to prevent overloading the backend."),this.Zi.Ki()):n&&n.code===Cr.UNAUTHENTICATED&&this.Ji.invalidateToken(),null!==this.stream&&(this.ar(),this.stream.close(),this.stream=null),this.state=e,[4,this.listener.Ri(n)];case 1:return t.sent(),[2]}})})},Dl.prototype.ar=function(){},Dl.prototype.auth=function(){var n=this;this.state=1;var t=this.hr(this.Yi),e=this.Yi;this.Ji.getToken().then(function(t){n.Yi===e&&n.lr(t)},function(e){t(function(){var t=new kr(Cr.UNKNOWN,"Fetching auth token failed: "+e.message);return n.dr(t)})})},Dl.prototype.lr=function(t){var e=this,n=this.hr(this.Yi);this.stream=this.wr(t),this.stream.Ii(function(){n(function(){return e.state=2,e.listener.Ii()})}),this.stream.Ri(function(t){n(function(){return e.dr(t)})}),this.stream.onMessage(function(t){n(function(){return e.onMessage(t)})})},Dl.prototype.nr=function(){var t=this;this.state=4,this.Zi.ji(function(){return y(t,void 0,void 0,function(){return g(this,function(t){return this.state=0,this.start(),[2]})})})},Dl.prototype.dr=function(t){return Lr("PersistentStream","close with error: "+t),this.stream=null,this.close(3,t)},Dl.prototype.hr=function(e){var n=this;return function(t){n.Se.enqueueAndForget(function(){return n.Yi===e?t():(Lr("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())})}},Dl),bl=(n(Al,ml=I),Al.prototype.wr=function(t){return this.Hi.$i("Listen",t)},Al.prototype.onMessage=function(t){this.Zi.reset();var e=function(t,e){if("targetChange"in e){e.targetChange;var n="NO_CHANGE"===(o=e.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===o?1:"REMOVE"===o?2:"CURRENT"===o?3:"RESET"===o?4:Vr(),r=e.targetChange.targetIds||[],i=(s=e.targetChange.resumeToken,t.I?(Ur(void 0===s||"string"==typeof s),ii.fromBase64String(s||"")):(Ur(void 0===s||s instanceof Uint8Array),ii.fromUint8Array(s||new Uint8Array))),o=(a=e.targetChange.cause)&&(u=void 0===(c=a).code?Cr.UNKNOWN:Ds(c.code),new kr(u,c.message||"")),s=new Ys(n,r,i,o||null)}else if("documentChange"in e){e.documentChange,(n=e.documentChange).document,n.document.name,n.document.updateTime;var r=da(t,n.document.name),i=ca(n.document.updateTime),a=new Oi({mapValue:{fields:n.document.fields}}),u=(o=Pi.newFoundDocument(r,i,a),n.targetIds||[]),c=n.removedTargetIds||[];s=new Hs(u,c,o.key,o)}else if("documentDelete"in e)e.documentDelete,(n=e.documentDelete).document,r=da(t,n.document),i=n.readTime?ca(n.readTime):zr.min(),a=Pi.newNoDocument(r,i),o=n.removedTargetIds||[],s=new Hs([],o,a.key,a);else if("documentRemove"in e)e.documentRemove,(n=e.documentRemove).document,r=da(t,n.document),i=n.removedTargetIds||[],s=new Hs([],i,r,null);else{if(!("filter"in e))return Vr();e.filter;e=e.filter;e.targetId,n=e.count||0,r=new vs(n),i=e.targetId,s=new Ws(i,r)}return s}(this.R,t),t=function(t){if(!("targetChange"in t))return zr.min();t=t.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?ca(t.readTime):zr.min()}(t);return this.listener._r(e,t)},Al.prototype.mr=function(t){var e,n,r,i={};i.database=ga(this.R),i.addTarget=(e=this.R,(r=Bi(r=(n=t).target)?{documents:Ta(e,r)}:{query:Ia(e,r)}).targetId=n.targetId,0this.query.limit;){var n=To(this.query)?h.last():h.first(),h=h.delete(n.key),c=c.delete(n.key);a.track({type:1,doc:n})}return{fo:h,mo:a,Nn:l,mutatedKeys:c}},Sf.prototype.yo=function(t,e){return t.hasLocalMutations&&e.hasCommittedMutations&&!e.hasLocalMutations},Sf.prototype.applyChanges=function(t,e,n){var o=this,r=this.fo;this.fo=t.fo,this.mutatedKeys=t.mutatedKeys;var i=t.mo.jr();i.sort(function(t,e){return r=t.type,i=e.type,n(r)-n(i)||o.lo(t.doc,e.doc);function n(t){switch(t){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return Vr()}}var r,i}),this.po(n);var s=e?this.Eo():[],n=0===this.ho.size&&this.current?1:0,e=n!==this.ao;return this.ao=n,0!==i.length||e?{snapshot:new tf(this.query,t.fo,r,i,t.mutatedKeys,0==n,e,!1),To:s}:{To:s}},Sf.prototype.zr=function(t){return this.current&&"Offline"===t?(this.current=!1,this.applyChanges({fo:this.fo,mo:new Zl,mutatedKeys:this.mutatedKeys,Nn:!1},!1)):{To:[]}},Sf.prototype.Io=function(t){return!this.uo.has(t)&&!!this.fo.has(t)&&!this.fo.get(t).hasLocalMutations},Sf.prototype.po=function(t){var e=this;t&&(t.addedDocuments.forEach(function(t){return e.uo=e.uo.add(t)}),t.modifiedDocuments.forEach(function(t){}),t.removedDocuments.forEach(function(t){return e.uo=e.uo.delete(t)}),this.current=t.current)},Sf.prototype.Eo=function(){var e=this;if(!this.current)return[];var n=this.ho;this.ho=Ks(),this.fo.forEach(function(t){e.Io(t.key)&&(e.ho=e.ho.add(t.key))});var r=[];return n.forEach(function(t){e.ho.has(t)||r.push(new bf(t))}),this.ho.forEach(function(t){n.has(t)||r.push(new vf(t))}),r},Sf.prototype.Ao=function(t){this.uo=t.Bn,this.ho=Ks();t=this._o(t.documents);return this.applyChanges(t,!0)},Sf.prototype.Ro=function(){return tf.fromInitialDocuments(this.query,this.fo,this.mutatedKeys,0===this.ao)},Sf),Ef=function(t,e,n){this.query=t,this.targetId=e,this.view=n},Tf=function(t){this.key=t,this.bo=!1},If=(Object.defineProperty(_f.prototype,"isPrimaryClient",{get:function(){return!0===this.Oo},enumerable:!1,configurable:!0}),_f);function _f(t,e,n,r,i,o){this.localStore=t,this.remoteStore=e,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=o,this.vo={},this.Po=new Dc(Ro,ko),this.Vo=new Map,this.So=new Set,this.Do=new Ns(bi.comparator),this.Co=new Map,this.No=new gh,this.xo={},this.Fo=new Map,this.ko=uc.Yt(),this.onlineState="Unknown",this.Oo=void 0}function Sf(t,e){this.query=t,this.uo=e,this.ao=null,this.current=!1,this.ho=Ks(),this.mutatedKeys=Ks(),this.lo=Lo(t),this.fo=new $l(this.lo)}function Af(i,o,s,a){return y(this,void 0,void 0,function(){var e,n,r;return g(this,function(t){switch(t.label){case 0:return i.$o=function(t,e,n){return function(r,i,o,s){return y(this,void 0,void 0,function(){var e,n;return g(this,function(t){switch(t.label){case 0:return(e=i.view._o(o)).Nn?[4,ch(r.localStore,i.query,!1).then(function(t){t=t.documents;return i.view._o(t,e)})]:[3,2];case 1:e=t.sent(),t.label=2;case 2:return n=s&&s.targetChanges.get(i.targetId),n=i.view.applyChanges(e,r.isPrimaryClient,n),[2,(Mf(r,i.targetId,n.To),n.snapshot)]}})})}(i,t,e,n)},[4,ch(i.localStore,o,!0)];case 1:return n=t.sent(),r=new wf(o,n.Bn),e=r._o(n.documents),n=zs.createSynthesizedTargetChangeForCurrentChange(s,a&&"Offline"!==i.onlineState),n=r.applyChanges(e,i.isPrimaryClient,n),Mf(i,s,n.To),r=new Ef(o,s,r),[2,(i.Po.set(o,r),i.Vo.has(s)?i.Vo.get(s).push(o):i.Vo.set(s,[o]),n.snapshot)]}})})}function Df(f,d,p){return y(this,void 0,void 0,function(){var s,l;return g(this,function(t){switch(t.label){case 0:l=Qf(f),t.label=1;case 1:return t.trys.push([1,5,,6]),[4,(i=l.localStore,a=d,c=i,h=Qr.now(),o=a.reduce(function(t,e){return t.add(e.key)},Ks()),c.persistence.runTransaction("Locally write mutations","readwrite",function(s){return c.Mn.pn(s,o).next(function(t){u=t;for(var e=[],n=0,r=a;n, or >=) must be on the same field. But you have inequality filters on '"+n.toString()+"' and '"+e.field.toString()+"'");n=_o(t);null!==n&&Jy(0,e.field,n)}t=function(t,e){for(var n=0,r=t.filters;ns.length)throw new kr(Cr.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 a=[],u=0;u, or >=) on field '"+e.toString()+"' and so you must also use '"+e.toString()+"' as your first argument to orderBy(), but your first orderBy() is on field '"+n.toString()+"' instead.")}$y.prototype.convertValue=function(t,e){switch(void 0===e&&(e="none"),Ei(t)){case 0:return null;case 1:return t.booleanValue;case 2:return fi(t.integerValue||t.doubleValue);case 3:return this.convertTimestamp(t.timestampValue);case 4:return this.convertServerTimestamp(t,e);case 5:return t.stringValue;case 6:return this.convertBytes(di(t.bytesValue));case 7:return this.convertReference(t.referenceValue);case 8:return this.convertGeoPoint(t.geoPointValue);case 9:return this.convertArray(t.arrayValue,e);case 10:return this.convertObject(t.mapValue,e);default:throw Vr()}},$y.prototype.convertObject=function(t,n){var r=this,i={};return Xr(t.fields||{},function(t,e){i[t]=r.convertValue(e,n)}),i},$y.prototype.convertGeoPoint=function(t){return new _p(fi(t.latitude),fi(t.longitude))},$y.prototype.convertArray=function(t,e){var n=this;return(t.values||[]).map(function(t){return n.convertValue(t,e)})},$y.prototype.convertServerTimestamp=function(t,e){switch(e){case"previous":var n=function t(e){e=e.mapValue.fields.__previous_value__;return pi(e)?t(e):e}(t);return null==n?null:this.convertValue(n,e);case"estimate":return this.convertTimestamp(yi(t));default:return null}},$y.prototype.convertTimestamp=function(t){t=li(t);return new Qr(t.seconds,t.nanos)},$y.prototype.convertDocumentKey=function(t,e){var n=ti.fromString(t);Ur(Ra(n));t=new Dd(n.get(1),n.get(3)),n=new bi(n.popFirst(5));return t.isEqual(e)||Pr("Document "+n+" contains a document reference within a different database ("+t.projectId+"/"+t.database+") which is not supported. It will be treated as a reference in the current database ("+e.projectId+"/"+e.database+") instead."),n},I=$y;function $y(){}function Zy(t,e,n){return t?n&&(n.merge||n.mergeFields)?t.toFirestore(e,n):t.toFirestore(e):e}var tg,eg=(n(ig,tg=I),ig.prototype.convertBytes=function(t){return new Tp(t)},ig.prototype.convertReference=function(t){t=this.convertDocumentKey(t,this.firestore._databaseId);return new Jd(this.firestore,null,t)},ig),ng=(rg.prototype.set=function(t,e,n){this._verifyNotCommitted();t=og(t,this._firestore),e=Zy(t.converter,e,n),n=Up(this._dataReader,"WriteBatch.set",t._key,e,null!==t.converter,n);return this._mutations.push(n.toMutation(t._key,rs.none())),this},rg.prototype.update=function(t,e,n){for(var r=[],i=3;i