From 80b07c85b1e54b2ea834620fb738f90bb2a996c9 Mon Sep 17 00:00:00 2001 From: Kushagra Gour Date: Wed, 10 Jan 2018 04:02:21 +0530 Subject: [PATCH] build with db --- app/index.html | 109 +--- app/partials/changelog.html | 290 ++++++++++ app/partials/help-modal.html | 37 ++ app/partials/keyboard-shortcuts.html | 106 ++++ app/partials/login-modal.html | 16 + app/partials/onboard-modal.html | 53 ++ app/script.js | 833 ++++++++++++++++++++------- app/service-worker.js | 2 +- app/style.css | 8 + app/vendor.js | 46 +- 10 files changed, 1187 insertions(+), 313 deletions(-) create mode 100644 app/partials/changelog.html create mode 100644 app/partials/help-modal.html create mode 100644 app/partials/keyboard-shortcuts.html create mode 100644 app/partials/login-modal.html create mode 100644 app/partials/onboard-modal.html diff --git a/app/index.html b/app/index.html index 2321238..a19a4aa 100644 --- a/app/index.html +++ b/app/index.html @@ -64,6 +64,13 @@ Open + + + Logout + +
@@ -295,106 +302,19 @@
+
diff --git a/app/partials/changelog.html b/app/partials/changelog.html new file mode 100644 index 0000000..cac2c37 --- /dev/null +++ b/app/partials/changelog.html @@ -0,0 +1,290 @@ + + + + + + +

Whats new?

+ +
+ 2.9.6 + +
+ +
+ 2.9.5 +
    +
  • Read blog post about this release.
  • +
  • Keyboard shortcuts panel: Add a list of all keyboard shotcuts. Access with Ctrl/⌘ + Shift + ? or click keyboard button in footer.
  • +
  • Add external library: Better UX for searching third party libraries.
  • +
  • Improvement: Code panes now go fullscreen when double-clicked on their headers - which is much more intuitive behavior based on feedback from lot of developers.
  • +
  • Improvement: Add allowfullscreen attribute on iframes. Thanks ClassicOldSong.
  • +
  • Bugfix - Stop screenlog.js from showing up in the exported HTML.
  • +
  • Popular external libraries list updated. Thanks jlapitan.
  • +
+
+ +
+ 2.9.4 +
    +
  • Improvement: Atomic CSS (Atomizer) has been updated to latest version. Now you can do things like psuedo elements. Learn More.
  • +
  • Bugfix - Logging circular objects is now possible. It won't show in the Web Maker console, but will show fine in browser's console.
  • +
  • Bugfix - Console's z-index issue has been fixed.
  • +
+
+ +
+ 2.9.3 +
    +
  • Choose the save location while exporting your saved creations. Now easily sync them to your Dropbox or any cloud storage.
  • +
  • All modals inside the app now have a close button.
  • +
  • Checkbox that showed on clicking a boolean value is now removed. Thanks Gaurav Nanda.
  • +
  • Bugfix - Screenshots on retina device are now correct. Thanks Ashish Bardhan.
  • +
  • Bugfix - Double console log in detached mode fixed.
  • +
  • Bugfix - Console.clear now works in detached mode too.
  • +
  • Bugfix - DOCTYPE added in preview.
  • +
  • Bugfix - Typo correction in README. Thanks Adil Mahmood.
  • +
  • gstatic.com is available to load external JavaScripts from.
  • +
  • Popular libraries list updated. Thanks diomed.
  • +
  • Added contribution guidelines in the Github repository.
  • +
+
+ +
+ 2.9.2 +
    +
  • Minor bug fixes.
  • +
+
+ + +
+ 2.9.1 + +
+ +
+ 2.9.0 +
    +
  • Read blog post about this release.
  • +
  • Detached Preview - Yes, you read that correct! You can now detach your preview and send it to your secondary monitor. +
  • +
  • Find & Replace - Long awaited, now its there. Ctrl/Cmd+f to find and add Alt to replace.
  • +
  • Atomic CSS (Atomizer) configurations - Add custom config for Atomic CSS. Read more.
  • +
  • Light mode - This new setting makes Web Maker drop some heavy effects like blur etc to gain more performance. Thanks Andrew.
  • +
  • Preserve logs setting - Choose whether or not to preserve logs across preview refreshes. Thanks Basit.
  • +
  • Line wrap setting - As the name says.
  • +
  • Semantic UI added to popular libraries.
  • +
  • Bootstrap, Vue, UI-Kit and more updated to latest versions in popular libraries.
  • +
  • UX improvements in settings UI
  • + +
  • Bugfix - Trigger preview refresh anytime with Ctrl/⌘ + Shift + 5. Even with auto-preview on.
  • +
+
+ +
+ 2.8.1 +
    +
  • Vue.js & UIKit version updated to latest version in 'Add Library' list.
  • +
  • UTF-8 charset added to preview HTML to support universal characters.
  • +
+
+ +
+ 2.8.0 +
    +
  • Read blog post about this release.
  • +
  • Auto Save - Your creations now auto-save after your + first manual save. This is configurable from settings. +
  • +
  • Base2Tone-Meadow Editor Theme - First user contributed theme. + Thanks to Diomed.
  • +
  • Use System Fonts - You can now use any of your existing + system fonts in the editor!
  • +
  • Matching Tag Highlight - Cursor over any HTML tag would + highlight the matching pair tag.
  • +
  • Auto-completion suggestion can now be switched off from settings.
  • +
  • Improvement - Stop white flicker in editor when the app + opens.
  • +
  • Bugfix - Add Babel Polyfill to enable use of next-gen + built-ins like Promise or WeakMap. +
  • +
  • Vue.js version updated to 2.4.0 in popular library list.
  • +
  • Downloads permission is optional. Asked only when you take screenshot.
  • +
+
+ +
+ 2.7.2 +
    +
  • External Libraries - Add Foundation.js and update UIKit 3 to latest beta.
  • +
  • rawgit.com & wzrd.in domains are now allowed for loading external libraries from.
  • +
  • Minor booting speed improvements
  • +
+
+ +
+ 2.7.1 +
    +
  • Framer.js support - You can now load the latest framer.js library from framer builds page and start coding framer prototypes.
  • +
  • Bugfix: Edit on CodePen is back in action.
  • +
  • Bugfix: Autocompletion menu doesn't show on cut and paste now.
  • +
  • Bugfix: Updated & fixed urls of some common external libraries to latest versions. UIKit3 & Bootstrap 4α are now in the list.
  • +
  • Preprocessor selector are now more accessible.
  • +
+
+ +
+ 2.7.0 +
    +
  • Fork any creation!: Now you can fork any existing creation of yours to start a new work based on it. One big use case of this feature is "Templates"! Read more about it.
  • +
  • Fonts 😍 : Super-awesome 4 fonts (mostly with ligature support) now available to choose from. Fira Code is the default font now.
  • +
  • Updated most used external libraries to latest versions.
  • +
  • Bugfix: Add missing Bootstrap JS file to most used external libraries list.
  • +
  • Several other minor bugfixes and improvements to make Web Maker awesome!
  • + +
  • Great news to share with you - Web Maker has been featured on the Chrome Webstore homepage! Thanks for all the love :)
  • +
+
+ +
+ 2.6.1 +
    +
  • Bugfix: Emojis vanishing while exporting to Codepen has been fixed.
  • +
  • Bugfix: console.clear() now doesn't error and clears the inbuilt console.
  • +
  • Bugfix: External libraries added to the creation are exported as well to Codepen.
  • +
+
+ +
+ 2.6.0 +
    +
  • The "Console": The most awaited feature is here! There is now an inbuilt console to see your logs, errors and for quickly evaluating JavaScript code inside your preview. Enjoy! I also a blog post about it.
  • +
  • Number slider which popped on clicking any number in the code has been removed due to poor user experience.
  • +
  • Minor usability improvements.
  • +
+
+ +
+ 2.5.0 +
    +
  • Atomic CSS: Use can now use Atomic CSS(ACSS) in your work! Read more about it here.
  • +
  • Search your saved creations: Easily search through all your saved creations by title.
  • +
  • Configurable Auto-preview - You can turn off the auto preview in settings if you don't want the preview to update as you type.
  • +
  • Configurable refresh on resize - You can configure whether you want the preview to refresh when you resize the preview panel.
  • +
  • Bugfix - Fix indentation issue with custom indentation size.
  • +
+
+ +
+ 2.4.2 +
    +
  • Improved infinite loop protection: Infinite loop protection is now faster and more reliable. And works without the need of Escodegen. Thanks to Ariya Hidayat!
  • +
  • Bugfix - Default parameters not working in JavaScript is fixed.
  • +
+
+ +
+ 2.4.0 +
    +
  • Import/Export: Your creations are most important. Now export all your creations into a single file as a backup that can be imported anytime & anywhere.
  • +
  • Editor themes: You have been heard. Now you can choose from a huge list of wonderful editor themes!
  • +
  • Identation settings: Not a spaces fan? Switch to tabs and set your indentation size.
  • +
  • Vim key bindings: Rejoice Vim lovers!
  • +
  • Code blast: Why don't you try coding with this switched on from the settings? Go on...
  • +
  • Important: Due to security policy changes from Chrome 57 onwards, Web Maker now allows loading external JavaScript libraries only from certain whitelisted domains (localhost, https://ajax.googleapis.com, https://code.jquery.com, https://cdnjs.cloudflare.com, + https://unpkg.com, https://maxcdn.com, https://cdn77.com, https://maxcdn.bootstrapcdn.com, https://cdn.jsdelivr.net/)
  • +
  • Save button now highlights when you have unsaved changes.
  • +
  • Jade is now called Pug. Just a name change.
  • +
+
+ +
+ 2.3.2 +
    +
  • Update Babel to support latest and coolest ES6 features.
  • +
  • Improve onboarding experience at first install.
  • +
+
+
+ 2.3.1 +
    +
  • Bugfix - Splitting of code and preview panes is remembered by the editor.
  • +
  • Title of the creation is used for the file name when saving as HTML.
  • +
+
+
+ 2.3.0 +
    +
  • Add Library Autocompletion - Just start typing the name of library and you'll be shown matching libraries from cdnjs.
  • +
  • Preview Screenshot Capture - Want to grab a nice screenshot of your creation. You have it! Click and capture.
  • +
  • Auto Indent Code - Select your code and hit Shift-Tab to auto-indent it!
  • +
  • Keyboard Navigation in Saved List - Now select your creation using arrow keys and hit ENTER to open it.
  • +
  • Highlight active line in code panes.
  • +
  • Bugfix - Fix in generated title of new creation.
  • +
  • Bugfix - HTML autocompletion is manual triggered now with Ctrl+Space.
  • +
+
+ +
+ 2.2.0 +
    +
  • Code Autocompletion - See code suggestions while you type!
  • +
  • Full Screen Preview - Checkout your creation in a full-screen layout.
  • +
  • SASS - SASS support added for CSS.
  • +
  • Faster CSS update - Preview updates instantly without refresh when just CSS is changed.
  • +
  • Bugfix - Indentation fixed while going on new line.
  • +
  • Bugfix - Works even in Chrome Canary now. Though libraries can be added only through CDNs.
  • +
+
+ +
+ 2.1.0 +
    +
  • TypeScript - Now you can code in TypeScript too!
  • +
  • Stylus Preprocessor - Stylus supported adding for CSS.
  • +
  • Code Folding - Collapse large code blocks for easy editing.
  • +
  • Bugfix - Support JSX in JavaScript.
  • +
  • Better onboarding for first time users.
  • +
+
+
+ 2.0.0 +
    +
  • Save and Load - Long pending and super-useful, now you can save your creations and resume them anytime later.
  • +
  • Insert JS & CSS - Load popular JavaScript & CSS libraries in your work without writing any code.
  • +
  • Collapsed Panes - Collapse/uncollapse code panes with a single click. Your pane configuration is even saved with every creation!
  • +
  • Quick color & number change - Click on any color or number and experiment with quick values using a slider.
  • +
  • Linting - See your code errors right where you are coding.
  • +
  • No more browser hang due to infinite loops!
  • + +
+
+
+ 1.7.0 +
    +
  • Preprocessors! - Enjoy a whole list of preprocessors for HTML(Jade & markdown), CSS(SCSS & LESS) and JavaScript(CoffeeScript & Babel).
  • +
  • More awesome font for code.
  • +
+
+
+ 1.6.0 +
    +
  • You can now configure Web-Maker to not replace new tab page from the settings. It is always accessible from the icon in the top-right.
  • +
  • Download current code as HTML file with Ctrl/⌘ + S keyboard shortcut.
  • +
  • New notifications panel added so you are always aware of the new changes in Web-Maker.
  • +
+
diff --git a/app/partials/help-modal.html b/app/partials/help-modal.html new file mode 100644 index 0000000..8df9fea --- /dev/null +++ b/app/partials/help-modal.html @@ -0,0 +1,37 @@ + + + + + + +

Web Maker v2.9.6

+ +
+

Made with 💖 & 🙌 by Kushagra Gour

+

Tweet out your feature requests, comments & suggestions to @webmakerApp.

+

Like this extension? Please rate it here.

+

+ Show some love + Chat + Report a bug + Support the developer +

+ +

+

Awesome libraries used

+ +

+ +

+

License

+ "Web Maker" is open-source under the MIT License. +

+
\ No newline at end of file diff --git a/app/partials/keyboard-shortcuts.html b/app/partials/keyboard-shortcuts.html new file mode 100644 index 0000000..b94cc08 --- /dev/null +++ b/app/partials/keyboard-shortcuts.html @@ -0,0 +1,106 @@ + + + + + + +

Keyboard Shortcuts

+ +
+
+

Global

+

+ + Ctrl/⌘ + Shift + ? + + See keyboard shortcuts +

+

+ + Ctrl/⌘ + Shift + 5 + + Refresh preview +

+

+ + Ctrl/⌘ + S + + Save current creations +

+

+ + Ctrl/⌘ + O + + Open list of saved creations +

+

+ + Ctrl + L + + Clear console (works when console input is focused) +

+

+ + Esc + + Close saved creations panel & modals +

+
+
+

Editor

+

+ + Ctrl/⌘ + F + + Find +

+

+ + Ctrl/⌘ + G + + Select next match +

+

+ + Ctrl/⌘ + Shift + G + + Select previous match +

+

+ + Ctrl/⌘ + Opt/Alt + F + + Find & replace +

+

+ + Shift + Tab + + Realign code +

+

+ + Ctrl/⌘ + ] + + Indent code right +

+

+ + Ctrl/⌘ + [ + + Indent code left +

+

+ + Tab + + Emmet code completion Read more +

+

+ + Ctrl/⌘ + / + + Single line comment +

+
+
\ No newline at end of file diff --git a/app/partials/login-modal.html b/app/partials/login-modal.html new file mode 100644 index 0000000..d642cfa --- /dev/null +++ b/app/partials/login-modal.html @@ -0,0 +1,16 @@ + + + + + + +

Login

+ +
+

+ +

+

+ +

+
\ No newline at end of file diff --git a/app/partials/onboard-modal.html b/app/partials/onboard-modal.html new file mode 100644 index 0000000..c1e9594 --- /dev/null +++ b/app/partials/onboard-modal.html @@ -0,0 +1,53 @@ +
+ + + +

Welcome to Web Maker

+
+ +
+
+
+ + + +
+

+ Open Web Maker anytime by clicking the + + + button in top-right side of your browser. +

+
+
+
+ + + +
+

+ Configure and customize settings by clicking the gear icon ( + + + ) in bottom right of the app. +

+
+
+
+ + + +
+

+ Follow @webmakerApp to know about the new upcoming + features! +

+
+
+ + +

+ +

\ No newline at end of file diff --git a/app/script.js b/app/script.js index b445315..63bef35 100644 --- a/app/script.js +++ b/app/script.js @@ -15,50 +15,54 @@ */ /* eslint-env browser */ -'use strict'; if ('serviceWorker' in navigator) { - // Delay registration until after the page has loaded, to ensure that our - // precaching requests don't degrade the first visit experience. - // See https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/registration - window.addEventListener('load', function() { - // Your service-worker.js *must* be located at the top-level directory relative to your site. - // It won't be able to control pages unless it's located at the same level or higher than them. - // *Don't* register service worker file in, e.g., a scripts/ sub-directory! - // See https://github.com/slightlyoff/ServiceWorker/issues/468 - navigator.serviceWorker.register('service-worker.js').then(function(reg) { - // updatefound is fired if service-worker.js changes. - reg.onupdatefound = function() { - // The updatefound event implies that reg.installing is set; see - // https://w3c.github.io/ServiceWorker/#service-worker-registration-updatefound-event - var installingWorker = reg.installing; + // Delay registration until after the page has loaded, to ensure that our + // precaching requests don't degrade the first visit experience. + // See https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/registration + window.addEventListener('load', function() { + // Your service-worker.js *must* be located at the top-level directory relative to your site. + // It won't be able to control pages unless it's located at the same level or higher than them. + // *Don't* register service worker file in, e.g., a scripts/ sub-directory! + // See https://github.com/slightlyoff/ServiceWorker/issues/468 + navigator.serviceWorker + .register('service-worker.js') + .then(function(reg) { + // updatefound is fired if service-worker.js changes. + reg.onupdatefound = function() { + // The updatefound event implies that reg.installing is set; see + // https://w3c.github.io/ServiceWorker/#service-worker-registration-updatefound-event + var installingWorker = reg.installing; - installingWorker.onstatechange = function() { - switch (installingWorker.state) { - case 'installed': - if (navigator.serviceWorker.controller) { - // At this point, the old content will have been purged and the fresh content will - // have been added to the cache. - // It's the perfect time to display a "New content is available; please refresh." - // message in the page's interface. - console.log('New or updated content is available.'); - } else { - // At this point, everything has been precached. - // It's the perfect time to display a "Content is cached for offline use." message. - console.log('Content is now available offline!'); - } - break; + installingWorker.onstatechange = function() { + switch (installingWorker.state) { + case 'installed': + if (navigator.serviceWorker.controller) { + // At this point, the old content will have been purged and the fresh content will + // have been added to the cache. + // It's the perfect time to display a "New content is available; please refresh." + // message in the page's interface. + console.log('New or updated content is available.'); + } else { + // At this point, everything has been precached. + // It's the perfect time to display a "Content is cached for offline use." message. + console.log('Content is now available offline!'); + } + break; - case 'redundant': - console.error('The installing service worker became redundant.'); - break; - } - }; - }; - }).catch(function(e) { - console.error('Error during service worker registration:', e); - }); - }); + case 'redundant': + console.error( + 'The installing service worker became redundant.' + ); + break; + } + }; + }; + }) + .catch(function(e) { + console.error('Error during service worker registration:', e); + }); + }); } (function() { @@ -246,20 +250,25 @@ if ('serviceWorker' in navigator) { window.chrome = window.chrome || {}; window.chrome.i18n = { getMessage: () => {} }; + + window.IS_EXTENSION = !!window.chrome.extension; })(); (() => { const FAUX_DELAY = 1; + + var db; + var dbPromise; + var local = { get: (obj, cb) => { + const retVal = {}; if (typeof obj === 'string') { - const retVal = {}; retVal[obj] = JSON.parse(window.localStorage.getItem(obj)); setTimeout(() => cb(retVal), FAUX_DELAY); } else { - const retVal = {}; Object.keys(obj).forEach(key => { - let val = window.localStorage.getItem(key); + const val = window.localStorage.getItem(key); retVal[key] = val === undefined || val === null ? obj[key] : JSON.parse(val); }); @@ -270,17 +279,189 @@ if ('serviceWorker' in navigator) { Object.keys(obj).forEach(key => { window.localStorage.setItem(key, JSON.stringify(obj[key])); }); + /* eslint-disable consistent-return */ setTimeout(() => { - if (cb) cb(); + if (cb) { + return cb(); + } }, FAUX_DELAY); + /* eslint-enable consistent-return */ } }; + const dbLocalAlias = chrome && chrome.storage ? chrome.storage.local : local; + const dbSyncAlias = chrome && chrome.storage ? chrome.storage.sync : local; + + async function getDb() { + if (dbPromise) { + return dbPromise; + } + utils.log('Initializing firestore'); + dbPromise = new Promise((resolve, reject) => { + if (db) { + return resolve(db); + } + return firebase + .firestore() + .enablePersistence() + .then(function() { + // Initialize Cloud Firestore through firebase + db = firebase.firestore(); + utils.log('firebase db ready', db); + resolve(db); + }) + .catch(function(err) { + reject(err.code); + if (err.code === 'failed-precondition') { + // Multiple tabs open, persistence can only be enabled + // in one tab at a a time. + // ... + } else if (err.code === 'unimplemented') { + // The current browser does not support all of the + // features required to enable persistence + // ... + } + }); + }); + return dbPromise; + } + + async function getUserLastSeenVersion() { + const d = deferred(); + // Will be chrome.storage.sync in extension environment, + // otherwise will fallback to localstorage + dbSyncAlias.get( + { + lastSeenVersion: '' + }, + result => { + d.resolve(result.lastSeenVersion); + } + ); + return d.promise; + // Might consider getting actual value from remote db. + // Not critical right now. + } + + async function setUserLastSeenVersion(version) { + if (window.IS_EXTENSION) { + chrome.storage.sync.set( + { + lastSeenVersion: version + }, + function() {} + ); + return; + } + // Settings the lastSeenVersion in localStorage also because next time we need + // to fetch it irrespective of the user being logged in or out + local.set({ lastSeenVersion: version }); + if (window.user) { + const remoteDb = await getDb(); + remoteDb + .doc(`users/${window.user.uid}`) + .update({ lastSeenVersion: version }); + } + } + + async function getUser(userId) { + const remoteDb = await getDb(); + return remoteDb.doc(`users/${userId}`).get().then(doc => { + if (!doc.exists) + return remoteDb.doc(`users/${userId}`).set({}, { merge: true }); + const user = doc.data(); + Object.assign(window.user, user); + return user; + }); + } + + function getSettings(defaultSettings) { + const d = deferred(); + // Will be chrome.storage.sync in extension environment, + // otherwise will fallback to localstorage + dbSyncAlias.get(defaultSettings, result => { + d.resolve(result); + }); + return d.promise; + } + window.db = { - local: chrome && chrome.storage ? chrome.storage.local : local, - sync: chrome && chrome.storage ? chrome.storage.sync : local + getDb, + getUser, + getUserLastSeenVersion, + setUserLastSeenVersion, + getSettings, + local: dbLocalAlias, + sync: dbSyncAlias }; })(); +window.logout = function logout() { + firebase.auth().signOut(); +}; +function login(providerName) { + var provider; + if (providerName === 'fb') { + provider = new firebase.auth.FacebookAuthProvider(); + } else if (providerName === 'twitter') { + provider = new firebase.auth.TwitterAuthProvider(); + } else if (providerName === 'google') { + provider = new firebase.auth.GoogleAuthProvider(); + provider.addScope('https://www.googleapis.com/auth/userinfo.profile'); + } else { + provider = new firebase.auth.GithubAuthProvider(); + } + + return firebase + .auth() + .signInWithPopup(provider) + .then(function(result) { + return; + // Save this user in the store + firebase + .database() + .ref('users/' + result.user.uid) + .update({ + displayName: result.user.displayName, + email: result.user.email, + photoURL: result.user.providerData[0].photoURL, + signedUpOn: Date.now() + }) + .then(function() { + // Port items in localstorage to user account + if (window.localStorage.prototyp) { + var items = JSON.parse(window.localStorage.prototyp); + var newItemKey; + items.forEach(function(localItem) { + itemService.fetchItem(localItem.id).then(function(item) { + newItemKey = firebase.database().ref('pens').push().key; + item.createdBy = result.user.uid; + delete item.uid; + firebase.database().ref('pens/' + newItemKey).set(item); + firebase + .database() + .ref('users/' + result.user.uid) + .child('items') + .child(newItemKey) + .set(true); + }); + }); + delete localStorage.prototyp; + } + }); + }) + .catch(function(error) { + // Handle Errors here. + var errorCode = error.code; + var errorMessage = error.message; + // The email of the user's account used. + var email = error.email; + // The firebase.auth.AuthCredential type that was used. + var credential = error.credential; + utils.log(error); + }); +} +window.login = login; + /* global ga */ // eslint-disable-next-line max-params window.trackEvent = function(category, action, label, value) { @@ -665,6 +846,201 @@ window.cssLibs = [ window.TextareaAutoComplete = TextareaAutoComplete; })(); +(() => { + window.itemService = { + async getItem(id) { + var remoteDb = await window.db.getDb(); + return remoteDb.doc(`items/${id}`).get().then(doc => { + return doc.data(); + }); + }, + async getUserItemIds() { + if (window.user) { + return new Promise(resolve => { + resolve(window.user.items || {}); + }); + } + var remoteDb = await window.db.getDb(); + return remoteDb.doc(`users/${window.user.uid}`).get().then(doc => { + if (!doc.exists) { + return {}; + } + return doc.data().items; + }); + }, + + async getAllItems() { + var d = deferred(); + let itemIds = await this.getUserItemIds(); + itemIds = Object.getOwnPropertyNames(itemIds || {}); + utils.log('itemids', itemIds); + + if (!itemIds.length) { + d.resolve([]); + } + + const items = []; + for (let i = 0; i < itemIds.length; i++) { + const id = itemIds[i]; + utils.log('Starting to fetch item ', id); + this.getItem(id).then(item => { + items.push(item); + // Check if we have all items now. + if (itemIds.length === items.length) { + d.resolve(items); + } + }); + } + return d.promise; + }, + + async setUser() { + const remoteDb = await window.db.getDb(); + return remoteDb.doc(`users/${window.user.uid}`).set({ + items: {} + }); + }, + + async setItem(id, item) { + if (!window.user) { + return new Promise(resolve => resolve()); + } + var remoteDb = await window.db.getDb(); + utils.log(`Starting to save item ${id}`); + item.createdBy = window.user.uid; + return remoteDb + .collection('items') + .doc(id) + .set(item, { + merge: true + }) + .then(arg => { + utils.log('Document written', arg); + }) + .catch(error => utils.log(error)); + }, + + /** + * Saves the passed items in the database. + * @param {Array} items to be saved in DB + */ + saveItems(items) { + var d = deferred(); + if (window.IS_EXTENSION) { + // save new items + window.db.local.set(items, d.resolve); + // Push in new item IDs + window.db.local.get( + { + items: {} + }, + function(result) { + /* eslint-disable guard-for-in */ + for (var id in items) { + result.items[id] = true; + } + window.db.local.set({ + items: result.items + }); + /* eslint-enable guard-for-in */ + } + ); + } else { + window.db.getDb().then(remoteDb => { + const batch = remoteDb.batch(); + /* eslint-disable guard-for-in */ + for (var id in items) { + items[id].createdBy = window.user.uid; + batch.set(remoteDb.doc(`items/${id}`), items[id]); + batch.update(remoteDb.doc(`users/${window.user.uid}`), { + [`items.${id}`]: true + }); + // Set these items on out cached user object too + window.user.items[id] = true; + } + batch.commit().then(d.resolve); + /* eslint-enable guard-for-in */ + }); + } + return d.promise; + }, + + async removeItem(id) { + if (window.IS_EXTENSION) { + var d = deferred(); + db.local.remove(id, d.resolve); + return d.promise; + } + const remoteDb = await window.db.getDb(); + utils.log(`Starting to save item ${id}`); + return remoteDb + .collection('items') + .doc(id) + .delete() + .then(arg => { + utils.log('Document removed', arg); + }) + .catch(error => utils.log(error)); + }, + + async setItemForUser(itemId) { + if (window.IS_EXTENSION || !window.user) { + return window.db.local.get( + { + items: {} + }, + function(result) { + result.items[itemId] = true; + window.db.local.set({ + items: result.items + }); + } + ); + } + const remoteDb = await window.db.getDb(); + return remoteDb + .collection('users') + .doc(window.user.uid) + .update({ + [`items.${itemId}`]: true + }) + .then(arg => { + utils.log(`Item ${itemId} set for user`, arg); + window.user.items = window.user.items || {}; + window.user.items[itemId] = true; + }) + .catch(error => utils.log(error)); + }, + + async unsetItemForUser(itemId) { + if (window.IS_EXTENSION) { + return window.db.local.get( + { + items: {} + }, + function(result) { + delete result.items[itemId]; + db.local.set({ + items: result.items + }); + } + ); + } + const remoteDb = await window.db.getDb(); + return remoteDb + .collection('users') + .doc(window.user.uid) + .update({ + [`items.${itemId}`]: firebase.firestore.FieldValue.delete() + }) + .then(arg => { + utils.log(`Item ${itemId} unset for user`, arg); + }) + .catch(error => utils.log(error)); + } + }; +})(); + /* global trackEvent */ /* global layoutBtn1, layoutBtn2, layoutBtn3, helpModal, notificationsModal, addLibraryModal, onboardModal, layoutBtn1, layoutBtn2, layoutBtn3, layoutBtn4, onboardModal, onboardModal, @@ -674,18 +1050,41 @@ onboardModal, settingsModal, notificationsBtn, onboardShowInTabOptionBtn, editor onboardDontShowInTabOptionBtn, TextareaAutoComplete, savedItemCountEl, indentationSizeValueEl, runBtn, searchInput, consoleEl, consoleLogEl, logCountEl, fontStyleTag, fontStyleTemplate, customEditorFontInput, cssSettingsModal, cssSettingsBtn, acssSettingsTextarea, -globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal +globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal, headerAvatarImg, +loginModal */ /* eslint-disable no-extra-semi */ -(function(alertsService) { +(function(alertsService, itemService) { /* eslint-enable no-extra-semi */ var scope = scope || {}; - var version = '2.9.4'; + var version = '2.9.6'; if (window.DEBUG) { window.scope = scope; } + const defaultSettings = { + preserveLastCode: true, + replaceNewTab: false, + htmlMode: 'html', + jsMode: 'js', + cssMode: 'css', + isCodeBlastOn: false, + indentWith: 'spaces', + indentSize: 2, + editorTheme: 'monokai', + keymap: 'sublime', + fontSize: 16, + refreshOnResize: false, + autoPreview: true, + editorFont: 'FiraCode', + editorCustomFont: '', + autoSave: true, + autoComplete: true, + preserveConsoleLogs: true, + lightVersion: false, + lineWrap: true + }; var HtmlModes = { HTML: 'html', MARKDOWN: 'markdown', @@ -968,8 +1367,9 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal function saveSetting(setting, value) { const d = deferred(); - var obj = {}; - obj[setting] = value; + const obj = { + [setting]: value + }; db.local.set(obj, d.resolve); return d.promise; } @@ -990,17 +1390,7 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal }); // Push into the items hash if its a new item being saved if (isNewItem) { - db.local.get( - { - items: {} - }, - function(result) { - result.items[currentItem.id] = true; - db.local.set({ - items: result.items - }); - } - ); + itemService.setItemForUser(currentItem.id); } } @@ -1075,7 +1465,8 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal currentItem.mainSizes = getMainPaneSizes(); utils.log('saving key', key || currentItem.id, currentItem); - return saveSetting(key || currentItem.id, currentItem).then(() => { + saveSetting(key || currentItem.id, currentItem); + return itemService.setItem(key || currentItem.id, currentItem).then(() => { alertsService.add('Item saved.'); unsavedEditCount = 0; saveBtn.classList.remove('is-marked'); @@ -1139,16 +1530,27 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal * @param {boolean} shouldSaveGlobally Whether to store the fetched items in global arr for later use. * @return {promise} Promise. */ - function fetchItems(shouldSaveGlobally) { + async function fetchItems(shouldSaveGlobally) { var d = deferred(); + savedItems = savedItems || {}; + var items = []; + if (!window.IS_EXTENSION && window.user) { + items = await itemService.getAllItems(); + + if (shouldSaveGlobally) { + items.forEach(item => { + savedItems[item.id] = item; + }); + } + d.resolve(items); + return d.promise; + } db.local.get('items', function(result) { - var itemIds = Object.getOwnPropertyNames(result.items || {}), - items = []; + var itemIds = Object.getOwnPropertyNames(result.items || {}); if (!itemIds.length) { d.resolve([]); } - savedItems = savedItems || {}; trackEvent('fn', 'fetchItems', itemIds.length); for (let i = 0; i < itemIds.length; i++) { /* eslint-disable no-loop-func */ @@ -1176,6 +1578,8 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal } function setCurrentItem(item) { currentItem = item; + utils.log('Current Item set', item); + // Reset auto-saving flag isAutoSavingEnabled = false; // Reset unsaved count, in UI also. @@ -1240,26 +1644,17 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal itemTile.remove(); // Remove from items list - db.local.get( - { - items: {} - }, - function(result) { - delete result.items[itemId]; - db.local.set({ - items: result.items - }); - } - ); + itemService.unsetItemForUser(itemId); // Remove individual item too. - db.local.remove(itemId, function() { + itemService.removeItem(itemId).then(() => { alertsService.add('Item removed.'); // This item is open in the editor. Lets open a new one. if (currentItem.id === itemId) { createNewItem(); } }); + // Remove from cached list delete savedItems[itemId]; @@ -1316,6 +1711,7 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal settingsModal.classList.remove('is-modal-visible'); cssSettingsModal.classList.remove('is-modal-visible'); keyboardShortcutsModal.classList.remove('is-modal-visible'); + loginModal.classList.remove('is-modal-visible'); toggleSavedItemsPane(false); document.dispatchEvent(new Event('overlaysClosed')); } @@ -1743,7 +2139,8 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal } function createPreviewFile(html, css, js) { - const shouldInlineJs = !window.webkitRequestFileSystem; + const shouldInlineJs = + !window.webkitRequestFileSystem || !window.IS_EXTENSION; var contents = getCompleteHtml(html, css, shouldInlineJs ? js : null); var blob = new Blob([contents], { type: 'text/plain;charset=UTF-8' }); var blobjs = new Blob([js], { type: 'text/plain;charset=UTF-8' }); @@ -2084,6 +2481,9 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal var existingItemIds = []; var toMergeItems = {}; items.forEach(item => { + // We can access `savedItems` here because this gets set when user + // opens the saved creations panel. And import option is available + // inside the saved items panel. if (savedItems[item.id]) { // Item already exists existingItemIds.push(item.id); @@ -2107,31 +2507,12 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal } } if (mergedItemCount) { - // save new items - db.local.set(toMergeItems, function() { + itemService.saveItems(toMergeItems).then(() => { alertsService.add( mergedItemCount + ' creations imported successfully.' ); + trackEvent('fn', 'itemsImported', mergedItemCount); }); - // Push in new item IDs - db.local.get( - { - items: {} - }, - function(result) { - /* eslint-disable guard-for-in */ - for (var id in toMergeItems) { - result.items[id] = true; - } - db.local.set({ - items: result.items - }); - trackEvent('fn', 'itemsImported', mergedItemCount); - - /* eslint-enable guard-for-in */ - } - ); - alertsService.add(mergedItemCount + ' creations imported successfully.'); } // FIXME: Move from here toggleSavedItemsPane(false); @@ -2150,7 +2531,8 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal items = JSON.parse(progressEvent.target.result); utils.log(items); mergeImportedItems(items); - } catch (ex) { + } catch (exception) { + utils.log(exception); alert( 'Oops! Selected file is corrupted. Please select a file that was generated by clicking the "Export" button.' ); @@ -2371,9 +2753,26 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal utils.log(settingName, el.type === 'checkbox' ? el.checked : el.value); prefs[settingName] = el.type === 'checkbox' ? el.checked : el.value; obj[settingName] = prefs[settingName]; + + // In case of !extension, we save in localstorage so that it gets fetched + // faster on future loads. db.sync.set(obj, function() { alertsService.add('Setting saved'); }); + if (!window.IS_EXTENSION) { + window.db.getDb().then(remoteDb => { + remoteDb + .collection('users') + .doc(window.user.uid) + .update({ + [`settings.${settingName}`]: prefs[settingName] + }) + .then(arg => { + utils.log(`Setting "${settingName}" for user`, arg); + }) + .catch(error => utils.log(error)); + }); + } trackEvent('ui', 'updatePref-' + settingName, prefs[settingName]); } @@ -2559,9 +2958,21 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal /* eslint-enable no-param-reassign */ }; - function compileNodes() { + /** + * Compiles directives on the given node + * @param {Node} root The element on which compilation is required + */ + function compileNodes(root) { + if (!(root instanceof Node)) { + /* eslint-disable no-param-reassign */ + root = document; + /* eslint-enable no-param-reassign */ + } + // Create a querySelectorAll function bound to the passed `root` Node + const query = selector => [...root.querySelectorAll(selector)]; + function attachListenerForEvent(eventName) { - const nodes = $all(`[d-${eventName}]`); + const nodes = query(`[d-${eventName}]`); nodes.forEach(function(el) { el.addEventListener(eventName, function(e) { scope[el.getAttribute(`d-${eventName}`)].call(window, e); @@ -2574,7 +2985,7 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal attachListenerForEvent('keyup'); // Compile d-open-modal directive - const modalTriggers = $all(`[d-open-modal]`); + const modalTriggers = query(`[d-open-modal]`); modalTriggers.forEach(function(el) { utils.onButtonClick(el, function() { scope.toggleModal(window[el.getAttribute('d-open-modal')]); @@ -2586,7 +2997,7 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal }); // Compile d-html directive - const dHtmlNodes = $all(`[d-html]`); + const dHtmlNodes = query(`[d-html]`); dHtmlNodes.forEach(function(el) { fetch(el.getAttribute('d-html')).then(response => { // Stop further compilation because of future recursion by removing attribute. @@ -2594,6 +3005,8 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal response.text().then(html => { requestIdleCallback(() => { el.innerHTML = html; + // Now compile this newly inserted HTML also. + compileNodes(el); }); }); }); @@ -2649,7 +3062,60 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal e.preventDefault(); }; + scope.updateProfileUi = () => { + if (window.user) { + document.body.classList.add('is-logged-in'); + headerAvatarImg.src = window.user.photoURL; + } else { + document.body.classList.remove('is-logged-in'); + headerAvatarImg.src = ''; + } + }; + + scope.login = e => { + firebase.auth().signInAnonymously().then().catch(function(error) { + // Handle Errors here. + utils.log(error); + }); + + if (e) { + e.preventDefault(); + } + }; + scope.login = window.login; + scope.logout = window.logout; + function init() { + var config = { + apiKey: 'AIzaSyBl8Dz7ZOE7aP75mipYl2zKdLSRzBU2fFc', + authDomain: 'web-maker-app.firebaseapp.com', + databaseURL: 'https://web-maker-app.firebaseio.com', + projectId: 'web-maker-app', + storageBucket: 'web-maker-app.appspot.com', + messagingSenderId: '560473480645' + }; + firebase.initializeApp(config); + + firebase.auth().onAuthStateChanged(function(user) { + scope.closeAllOverlays(); + if (user) { + utils.log('You are -> ', user); + alertsService.add('You are now logged in!'); + scope.user = window.user = user; + window.db.getUser(user.uid).then(customUser => { + if (customUser) { + Object.assign(prefs, user.settings); + updateSettingsInUi(); + scope.updateSetting(); + } + }); + } else { + delete window.user; + // User is signed out. + } + scope.updateProfileUi(); + }); + var lastCode; CodeMirror.modeURL = `lib/codemirror/mode/%N/%N.js`; @@ -2676,12 +3142,7 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal ) { hasSeenNotifications = true; notificationsBtn.classList.remove('has-new'); - db.sync.set( - { - lastSeenVersion: version - }, - function() {} - ); + window.db.setUserLastSeenVersion(version); } trackEvent('ui', 'notificationButtonClick', version); return false; @@ -2816,7 +3277,11 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal event.preventDefault(); openSavedItemsPane(); trackEvent('ui', 'openCreationKeyboardShortcut'); - } else if ((event.ctrlKey || event.metaKey) && event.keyCode === 191) { + } else if ( + (event.ctrlKey || event.metaKey) && + event.shiftKey && + event.keyCode === 191 + ) { // Ctrl/⌘ + Shift + ? event.preventDefault(); scope.toggleModal(keyboardShortcutsModal); @@ -2980,118 +3445,54 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal ); // Get synced `preserveLastCode` setting to get back last code (or not). - db.sync.get( - { - preserveLastCode: true, - replaceNewTab: false, - htmlMode: 'html', - jsMode: 'js', - cssMode: 'css', - isCodeBlastOn: false, - indentWith: 'spaces', - indentSize: 2, - editorTheme: 'monokai', - keymap: 'sublime', - fontSize: 16, - refreshOnResize: false, - autoPreview: true, - editorFont: 'FiraCode', - editorCustomFont: '', - autoSave: true, - autoComplete: true, - preserveConsoleLogs: true, - lightVersion: false, - lineWrap: true - }, - function syncGetCallback(result) { - if (result.preserveLastCode && lastCode) { - unsavedEditCount = 0; - if (lastCode.id) { - db.local.get(lastCode.id, function(itemResult) { + db.getSettings(defaultSettings).then(result => { + if (result.preserveLastCode && lastCode) { + unsavedEditCount = 0; + if (lastCode.id) { + // Ignore for remote db + db.local.get(lastCode.id, function(itemResult) { + if (itemResult[lastCode.id]) { utils.log('Load item ', lastCode.id); currentItem = itemResult[lastCode.id]; refreshEditor(); - }); - } else { - utils.log('Load last unsaved item', lastCode); - currentItem = lastCode; - refreshEditor(); - } + } + }); } else { - createNewItem(); + utils.log('Load last unsaved item', lastCode); + currentItem = lastCode; + refreshEditor(); } - prefs.preserveLastCode = result.preserveLastCode; - prefs.replaceNewTab = result.replaceNewTab; - prefs.htmlMode = result.htmlMode; - prefs.cssMode = result.cssMode; - prefs.jsMode = result.jsMode; - prefs.isCodeBlastOn = result.isCodeBlastOn; - prefs.indentSize = result.indentSize; - prefs.indentWith = result.indentWith; - prefs.editorTheme = result.editorTheme; - prefs.keymap = result.keymap; - prefs.fontSize = result.fontSize; - prefs.refreshOnResize = result.refreshOnResize; - prefs.autoPreview = result.autoPreview; - prefs.editorFont = result.editorFont; - prefs.editorCustomFont = result.editorCustomFont; - prefs.autoSave = result.autoSave; - prefs.autoComplete = result.autoComplete; - prefs.preserveConsoleLogs = result.preserveConsoleLogs; - prefs.lightVersion = result.lightVersion; - prefs.lineWrap = result.lineWrap; - - updateSettingsInUi(); - scope.updateSetting(); + } else { + createNewItem(); } - ); + Object.assign(prefs, result); + + updateSettingsInUi(); + scope.updateSetting(); + }); // Check for new version notifications - db.sync.get( - { - lastSeenVersion: '' - }, - function syncGetCallback(result) { - // Check if new user - if (!result.lastSeenVersion) { - onboardModal.classList.add('is-modal-visible'); - if (document.cookie.indexOf('onboarded') === -1) { - trackEvent('ui', 'onboardModalSeen', version); - document.cookie = 'onboarded=1'; - } - db.sync.set( - { - lastSeenVersion: version - }, - function() {} - ); - // set some initial preferences on closing the onboard modal - utils.once(document, 'overlaysClosed', function() { - db.sync.set( - { - replaceNewTab: onboardShowInTabOptionBtn.classList.contains( - 'selected' - ) - }, - function() { - trackEvent( - 'fn', - 'setReplaceNewTabFromOnboard', - onboardShowInTabOptionBtn.classList.contains('selected') - ); - } - ); - }); - } - if ( - !result.lastSeenVersion || - utils.semverCompare(result.lastSeenVersion, version) === -1 - ) { - notificationsBtn.classList.add('has-new'); - hasSeenNotifications = false; + db.getUserLastSeenVersion().then(lastSeenVersion => { + // Check if new user + if (!lastSeenVersion) { + onboardModal.classList.add('is-modal-visible'); + if (document.cookie.indexOf('onboarded') === -1) { + trackEvent('ui', 'onboardModalSeen', version); + document.cookie = 'onboarded=1'; } + window.db.setUserLastSeenVersion(version); + // set some initial preferences on closing the onboard modal + // Old onboarding. + // utils.once(document, 'overlaysClosed', function() {}); } - ); + if ( + !lastSeenVersion || + utils.semverCompare(lastSeenVersion, version) === -1 + ) { + notificationsBtn.classList.add('has-new'); + hasSeenNotifications = false; + } + }); scope.acssSettingsCm = CodeMirror.fromTextArea(acssSettingsTextarea, { mode: 'application/ld+json' @@ -3163,7 +3564,7 @@ globalConsoleContainerEl, externalLibrarySearchInput, keyboardShortcutsModal scope.closeAllOverlays = closeAllOverlays; init(); -})(window.alertsService); +})(window.alertsService, window.itemService); // Dropdown.js diff --git a/app/service-worker.js b/app/service-worker.js index 945030d..4aa1738 100644 --- a/app/service-worker.js +++ b/app/service-worker.js @@ -37,7 +37,7 @@ /* eslint-disable indent, no-unused-vars, no-multiple-empty-lines, max-nested-callbacks, space-before-function-paren, quotes, comma-spacing */ 'use strict'; -var precacheConfig = [["FiraCode.ttf","fa1f8c8961adca519738d9518139579c"],["changelog.html","7f40f4b9a97ca60826e7ad09e401d570"],["icon-48.png","ca68956f464ed4fd2e09c66d5edaed5f"],["index.html","fd3a70bbb629491e4fb58eb797083821"],["lib/atomizer.browser.js","451f56bc105c5ad333445998b3c085a2"],["lib/babel-polyfill.min.js","60977959048c0f5ef5aa66d6eac61eb3"],["lib/babel.min.js","77a1a84bbc2661db874c738f9b3ba375"],["lib/code-blast.js","48f8f054be45d3ad5054a7c7f87be0ff"],["lib/codemirror/mode/coffeescript/coffeescript.js","dea87b9f4c669789c4760605d947f1a9"],["lib/codemirror/mode/css/css.js","6c9ca32a78c120340e588ed3df734138"],["lib/codemirror/mode/css/gss.html","9afa6e2f3a7daa6127a3f26e2e68005c"],["lib/codemirror/mode/css/gss_test.js","e40c6fd9abdc6edc2b29e521bda726e1"],["lib/codemirror/mode/css/less.html","a35ff50857d48bb2f4df8ac737f35d64"],["lib/codemirror/mode/css/scss.html","8c96251f27727a9b23b45c41511e23a0"],["lib/codemirror/mode/haml/haml.js","9abc1679e0f54dcdd62d2326ed6133f5"],["lib/codemirror/mode/htmlembedded/htmlembedded.js","67f745ab3879bf7bc3029ac75ea3e181"],["lib/codemirror/mode/htmlmixed/htmlmixed.js","2d6915b576f267e93f0e1cf72f31af37"],["lib/codemirror/mode/javascript/javascript.js","3b2f1591e3175a24846cb182943f2a40"],["lib/codemirror/mode/javascript/json-ld.html","a2a5069194b78b6b5523cace263cab06"],["lib/codemirror/mode/javascript/typescript.html","76c2ffb883a133aa0fc5cc75ec0c56f5"],["lib/codemirror/mode/jsx/jsx.js","7bee6944931c2cc6ccd99b50fca637db"],["lib/codemirror/mode/markdown/markdown.js","30dd4984e2e929429d70cf5174b35c5d"],["lib/codemirror/mode/meta.js","6e456ea5fd8920c85d5281bd1efecb4c"],["lib/codemirror/mode/pug/pug.js","e988fd72c82f3b11836f6a06f7452436"],["lib/codemirror/mode/sass/sass.js","bd31ac70e9a457abc2789c2b83a21984"],["lib/codemirror/mode/stylus/stylus.js","81e2d281ecbb1dcf5c86857097ae60a7"],["lib/codemirror/mode/xml/xml.js","80f64aaafa6af7844d14f32f3219bb26"],["lib/codemirror/theme/3024-day.css","73c8f41583b4b71dbe1e5eac5c96f1a9"],["lib/codemirror/theme/3024-night.css","745180be9a932f24c6c0dd4ebdf5a0ed"],["lib/codemirror/theme/abcdef.css","8004cb71fd65e58bdfa64fdd55241315"],["lib/codemirror/theme/ambiance-mobile.css","256f2dd130b80c6afaa40fddf700d12a"],["lib/codemirror/theme/ambiance.css","6a200e1f3976929816cf3ac4675c810a"],["lib/codemirror/theme/base16-dark.css","84b6347918411d58d7f9b65a7ee87f65"],["lib/codemirror/theme/base16-light.css","037c7f3d16fe6d5ae2baa532e334172b"],["lib/codemirror/theme/base2tone-meadow-dark.css","f9dd12e2e51fc1575c57f3e5edc2232f"],["lib/codemirror/theme/bespin.css","cc414e4ec18bc89b3c79935b0e27fc20"],["lib/codemirror/theme/blackboard.css","cf9366960ff65c8101793bc64fe13e88"],["lib/codemirror/theme/cobalt.css","3488b576456693fd7ced2da0e10c8a16"],["lib/codemirror/theme/colorforth.css","b2ee8d2296277fc2811a7473ee4e9977"],["lib/codemirror/theme/dracula.css","e514d652ae86bfeaed34237b7d3afe44"],["lib/codemirror/theme/duotone-dark.css","02ec891b23125aaf625d978a39fd24ca"],["lib/codemirror/theme/duotone-light.css","608d11459665117d708651ce7f803fde"],["lib/codemirror/theme/eclipse.css","194369eec66630cfaf662ce5f0a193be"],["lib/codemirror/theme/elegant.css","0a4227e805a9d5f73a55dd248c1b052d"],["lib/codemirror/theme/erlang-dark.css","b5543f5273c968449760ab0d6a2af6dc"],["lib/codemirror/theme/hopscotch.css","b924ed31af30b1c68e5a01fc3c9b0553"],["lib/codemirror/theme/icecoder.css","576d776abdf7e28ea9f84e2eb161a20d"],["lib/codemirror/theme/isotope.css","7bb44bff5190c427de5ae750d6369633"],["lib/codemirror/theme/lesser-dark.css","da2c896bff035cec86fa98b6dc13f7cc"],["lib/codemirror/theme/liquibyte.css","9f37e7a4f3c02bec9bb735b78ed082d6"],["lib/codemirror/theme/material.css","11e812a3688805b5c187a6e6852bafe1"],["lib/codemirror/theme/mbo.css","55ff4bdd8a92c3dcbfd5421c532b3059"],["lib/codemirror/theme/mdn-like.css","79f8dabc5593d01d27bc824b801f9f05"],["lib/codemirror/theme/midnight.css","950e76dca6461ee1a2eac39f2d886613"],["lib/codemirror/theme/monokai.css","31c75ebee6311d49c046ffbbb91028f4"],["lib/codemirror/theme/neat.css","6b19894b9787c6791c250a95d0d4f8d6"],["lib/codemirror/theme/neo.css","2886072b53043c167e6f8765606c705c"],["lib/codemirror/theme/night.css","fe3ce7650a77e7e3887816dd7b6d880d"],["lib/codemirror/theme/panda-syntax.css","acbf94261e43c1f29c2252eb445de032"],["lib/codemirror/theme/paraiso-dark.css","3c24cee0dfac767713840b24e8359c99"],["lib/codemirror/theme/paraiso-light.css","e245bbfd22b4f61efe526ff13903f19e"],["lib/codemirror/theme/pastel-on-dark.css","48aae1a42733db57bd0a260ce0d83975"],["lib/codemirror/theme/railscasts.css","a5e7682d89da46244e5464d9572e24d8"],["lib/codemirror/theme/rubyblue.css","52bb601017a90bca522d66f6e82e73aa"],["lib/codemirror/theme/seti.css","f71668880eb1625f420ceaad670436f0"],["lib/codemirror/theme/solarized dark.css","4d05a166d713bb1ac24833061c1522d7"],["lib/codemirror/theme/solarized light.css","4d05a166d713bb1ac24833061c1522d7"],["lib/codemirror/theme/the-matrix.css","33c49ceeedafd0a08e712e465e3ad3ce"],["lib/codemirror/theme/tomorrow-night-bright.css","777d36e1c5bbfeb3bf2ca8dd607eee93"],["lib/codemirror/theme/tomorrow-night-eighties.css","5ceb5531fbe074d5190b55e8c725051e"],["lib/codemirror/theme/ttcn.css","d2cb74dfae563a10e9c286357429ea8b"],["lib/codemirror/theme/twilight.css","684040adf66ef89355cb7ebc6b54b00b"],["lib/codemirror/theme/vibrant-ink.css","f10004836fb29cc9a08c987d3e18938a"],["lib/codemirror/theme/xq-dark.css","60f162f0c4240e7352364d436b5598fa"],["lib/codemirror/theme/xq-light.css","447e80da7fe8c5c2bcf39127200cead2"],["lib/codemirror/theme/yeti.css","623dc805bc84dd6d25deef376593354e"],["lib/codemirror/theme/zenburn.css","94ad50bf3d048ed92cc513cd901dc685"],["lib/coffee-script.js","a43664b71b7b96e90046a605f6fa51a1"],["lib/emmet.js","6fff639e42ec8c00f4f4ff30b52e60df"],["lib/esprima.js","dfe041b0a8a5dda5c62ed8d2a1d3a666"],["lib/hint.min.css","0dc51e410a460622949f927dfda1bc32"],["lib/inlet.css","8242884724cfac965b53cf0a3d774c0b"],["lib/inlet.min.js","7e389291ff8decc675a32e376e318660"],["lib/jade.js","529e365c68f8d5efc4cea18be310bd76"],["lib/less.min.js","6fd457ee80aaf9aa8758fe8a2345c970"],["lib/marked.js","9f948a81f35613d44efa9322cbaf450d"],["lib/sass.js","1263518af3f8b2090c9b08d195bd20d9"],["lib/screenlog.js","dde029b72748bbc12532b309a717c2ca"],["lib/split.js","40ac1c1fba622660e3750405b18ab0bf"],["lib/stylus.min.js","58f6030903ab52f596fb407dcd3df34f"],["lib/typescript.js","cc0882a3185037052e21fa06a38ef077"],["script.js","eee81113b6fa6be92763be75915d4db4"],["style.css","2cbe0b075aa0936548d1eda9a01f86c0"],["vendor.css","6ed94306315b8aaf789c53091c23bb4b"],["vendor.js","43e7f646f4f0c6043e24a9e958fc7e29"]]; +var precacheConfig = [["FiraCode.ttf","fa1f8c8961adca519738d9518139579c"],["changelog.html","7f40f4b9a97ca60826e7ad09e401d570"],["icon-48.png","ca68956f464ed4fd2e09c66d5edaed5f"],["index.html","cd2ac689891747b6757fdd890f9368c3"],["lib/atomizer.browser.js","451f56bc105c5ad333445998b3c085a2"],["lib/babel-polyfill.min.js","60977959048c0f5ef5aa66d6eac61eb3"],["lib/babel.min.js","77a1a84bbc2661db874c738f9b3ba375"],["lib/code-blast.js","48f8f054be45d3ad5054a7c7f87be0ff"],["lib/codemirror/mode/coffeescript/coffeescript.js","dea87b9f4c669789c4760605d947f1a9"],["lib/codemirror/mode/css/css.js","6c9ca32a78c120340e588ed3df734138"],["lib/codemirror/mode/css/gss.html","9afa6e2f3a7daa6127a3f26e2e68005c"],["lib/codemirror/mode/css/gss_test.js","e40c6fd9abdc6edc2b29e521bda726e1"],["lib/codemirror/mode/css/less.html","a35ff50857d48bb2f4df8ac737f35d64"],["lib/codemirror/mode/css/scss.html","8c96251f27727a9b23b45c41511e23a0"],["lib/codemirror/mode/haml/haml.js","9abc1679e0f54dcdd62d2326ed6133f5"],["lib/codemirror/mode/htmlembedded/htmlembedded.js","67f745ab3879bf7bc3029ac75ea3e181"],["lib/codemirror/mode/htmlmixed/htmlmixed.js","2d6915b576f267e93f0e1cf72f31af37"],["lib/codemirror/mode/javascript/javascript.js","3b2f1591e3175a24846cb182943f2a40"],["lib/codemirror/mode/javascript/json-ld.html","a2a5069194b78b6b5523cace263cab06"],["lib/codemirror/mode/javascript/typescript.html","76c2ffb883a133aa0fc5cc75ec0c56f5"],["lib/codemirror/mode/jsx/jsx.js","7bee6944931c2cc6ccd99b50fca637db"],["lib/codemirror/mode/markdown/markdown.js","30dd4984e2e929429d70cf5174b35c5d"],["lib/codemirror/mode/meta.js","6e456ea5fd8920c85d5281bd1efecb4c"],["lib/codemirror/mode/pug/pug.js","e988fd72c82f3b11836f6a06f7452436"],["lib/codemirror/mode/sass/sass.js","bd31ac70e9a457abc2789c2b83a21984"],["lib/codemirror/mode/stylus/stylus.js","81e2d281ecbb1dcf5c86857097ae60a7"],["lib/codemirror/mode/xml/xml.js","80f64aaafa6af7844d14f32f3219bb26"],["lib/codemirror/theme/3024-day.css","73c8f41583b4b71dbe1e5eac5c96f1a9"],["lib/codemirror/theme/3024-night.css","745180be9a932f24c6c0dd4ebdf5a0ed"],["lib/codemirror/theme/abcdef.css","8004cb71fd65e58bdfa64fdd55241315"],["lib/codemirror/theme/ambiance-mobile.css","256f2dd130b80c6afaa40fddf700d12a"],["lib/codemirror/theme/ambiance.css","6a200e1f3976929816cf3ac4675c810a"],["lib/codemirror/theme/base16-dark.css","84b6347918411d58d7f9b65a7ee87f65"],["lib/codemirror/theme/base16-light.css","037c7f3d16fe6d5ae2baa532e334172b"],["lib/codemirror/theme/base2tone-meadow-dark.css","f9dd12e2e51fc1575c57f3e5edc2232f"],["lib/codemirror/theme/bespin.css","cc414e4ec18bc89b3c79935b0e27fc20"],["lib/codemirror/theme/blackboard.css","cf9366960ff65c8101793bc64fe13e88"],["lib/codemirror/theme/cobalt.css","3488b576456693fd7ced2da0e10c8a16"],["lib/codemirror/theme/colorforth.css","b2ee8d2296277fc2811a7473ee4e9977"],["lib/codemirror/theme/dracula.css","e514d652ae86bfeaed34237b7d3afe44"],["lib/codemirror/theme/duotone-dark.css","02ec891b23125aaf625d978a39fd24ca"],["lib/codemirror/theme/duotone-light.css","608d11459665117d708651ce7f803fde"],["lib/codemirror/theme/eclipse.css","194369eec66630cfaf662ce5f0a193be"],["lib/codemirror/theme/elegant.css","0a4227e805a9d5f73a55dd248c1b052d"],["lib/codemirror/theme/erlang-dark.css","b5543f5273c968449760ab0d6a2af6dc"],["lib/codemirror/theme/hopscotch.css","b924ed31af30b1c68e5a01fc3c9b0553"],["lib/codemirror/theme/icecoder.css","576d776abdf7e28ea9f84e2eb161a20d"],["lib/codemirror/theme/isotope.css","7bb44bff5190c427de5ae750d6369633"],["lib/codemirror/theme/lesser-dark.css","da2c896bff035cec86fa98b6dc13f7cc"],["lib/codemirror/theme/liquibyte.css","9f37e7a4f3c02bec9bb735b78ed082d6"],["lib/codemirror/theme/material.css","11e812a3688805b5c187a6e6852bafe1"],["lib/codemirror/theme/mbo.css","55ff4bdd8a92c3dcbfd5421c532b3059"],["lib/codemirror/theme/mdn-like.css","79f8dabc5593d01d27bc824b801f9f05"],["lib/codemirror/theme/midnight.css","950e76dca6461ee1a2eac39f2d886613"],["lib/codemirror/theme/monokai.css","31c75ebee6311d49c046ffbbb91028f4"],["lib/codemirror/theme/neat.css","6b19894b9787c6791c250a95d0d4f8d6"],["lib/codemirror/theme/neo.css","2886072b53043c167e6f8765606c705c"],["lib/codemirror/theme/night.css","fe3ce7650a77e7e3887816dd7b6d880d"],["lib/codemirror/theme/panda-syntax.css","acbf94261e43c1f29c2252eb445de032"],["lib/codemirror/theme/paraiso-dark.css","3c24cee0dfac767713840b24e8359c99"],["lib/codemirror/theme/paraiso-light.css","e245bbfd22b4f61efe526ff13903f19e"],["lib/codemirror/theme/pastel-on-dark.css","48aae1a42733db57bd0a260ce0d83975"],["lib/codemirror/theme/railscasts.css","a5e7682d89da46244e5464d9572e24d8"],["lib/codemirror/theme/rubyblue.css","52bb601017a90bca522d66f6e82e73aa"],["lib/codemirror/theme/seti.css","f71668880eb1625f420ceaad670436f0"],["lib/codemirror/theme/solarized dark.css","4d05a166d713bb1ac24833061c1522d7"],["lib/codemirror/theme/solarized light.css","4d05a166d713bb1ac24833061c1522d7"],["lib/codemirror/theme/the-matrix.css","33c49ceeedafd0a08e712e465e3ad3ce"],["lib/codemirror/theme/tomorrow-night-bright.css","777d36e1c5bbfeb3bf2ca8dd607eee93"],["lib/codemirror/theme/tomorrow-night-eighties.css","5ceb5531fbe074d5190b55e8c725051e"],["lib/codemirror/theme/ttcn.css","d2cb74dfae563a10e9c286357429ea8b"],["lib/codemirror/theme/twilight.css","684040adf66ef89355cb7ebc6b54b00b"],["lib/codemirror/theme/vibrant-ink.css","f10004836fb29cc9a08c987d3e18938a"],["lib/codemirror/theme/xq-dark.css","60f162f0c4240e7352364d436b5598fa"],["lib/codemirror/theme/xq-light.css","447e80da7fe8c5c2bcf39127200cead2"],["lib/codemirror/theme/yeti.css","623dc805bc84dd6d25deef376593354e"],["lib/codemirror/theme/zenburn.css","94ad50bf3d048ed92cc513cd901dc685"],["lib/coffee-script.js","a43664b71b7b96e90046a605f6fa51a1"],["lib/emmet.js","6fff639e42ec8c00f4f4ff30b52e60df"],["lib/esprima.js","dfe041b0a8a5dda5c62ed8d2a1d3a666"],["lib/hint.min.css","0dc51e410a460622949f927dfda1bc32"],["lib/inlet.css","8242884724cfac965b53cf0a3d774c0b"],["lib/inlet.min.js","7e389291ff8decc675a32e376e318660"],["lib/jade.js","529e365c68f8d5efc4cea18be310bd76"],["lib/less.min.js","6fd457ee80aaf9aa8758fe8a2345c970"],["lib/marked.js","9f948a81f35613d44efa9322cbaf450d"],["lib/sass.js","1263518af3f8b2090c9b08d195bd20d9"],["lib/screenlog.js","dde029b72748bbc12532b309a717c2ca"],["lib/split.js","40ac1c1fba622660e3750405b18ab0bf"],["lib/stylus.min.js","58f6030903ab52f596fb407dcd3df34f"],["lib/typescript.js","cc0882a3185037052e21fa06a38ef077"],["partials/changelog.html","ff90524091c37e22edb0c74e5c380bd4"],["partials/help-modal.html","deb25c0a3cd22ede36cdc82c25e601a7"],["partials/keyboard-shortcuts.html","d7c4124380a4eeb18968d55276d19591"],["partials/login-modal.html","5ff36373475a89699e0fe136c6ca2b6f"],["partials/onboard-modal.html","ea2a2d5af4f2a3898551477e758fdada"],["script.js","8732925d4793bb20e6dbc684225b722d"],["style.css","182d8b5ff77248bc6e3f2548b1beb800"],["vendor.css","6ed94306315b8aaf789c53091c23bb4b"]]; var cacheName = 'sw-precache-v3--' + (self.registration ? self.registration.scope : ''); diff --git a/app/style.css b/app/style.css index bfdf889..8f429a6 100644 --- a/app/style.css +++ b/app/style.css @@ -348,6 +348,9 @@ body > #demo-frame { .main-header__btn-wrap > a:hover { border-color: rgba(146, 151, 179, 0.5); } +.main-header__avatar-img { + border-radius: 50%; +} .logo { display: inline-block; height: 25px; @@ -956,6 +959,11 @@ transition: 0.25s ease; display: inline-block; } +body.is-logged-in .hide-on-login, +body:not(.is-logged-in) .hide-on-logout { + display: none; +} + /* Codemirror themes basic bg styles. This is here so that there is no big FOUC while the theme CSS file is loading */ .cm-s-paraiso-dark.CodeMirror { background: #2f1e2e; color: #b9b6b0; } diff --git a/app/vendor.js b/app/vendor.js index d756e17..7a0d348 100644 --- a/app/vendor.js +++ b/app/vendor.js @@ -70247,4 +70247,48 @@ return /******/ (function(modules) { // webpackBootstrap /***/ } /******/ ]) }); -; \ No newline at end of file +; +/*! + * @license Firebase v4.8.1 + * Build: rev-d8c20f0 + * Terms: https://firebase.google.com/terms/ + */ +var firebase=function(){var e=void 0===e?self:e;return function(t){function r(e){if(o[e])return o[e].exports;var n=o[e]={i:e,l:!1,exports:{}};return t[e].call(n.exports,n,n.exports,r),n.l=!0,n.exports}var n=e.webpackJsonpFirebase;e.webpackJsonpFirebase=function(e,o,a){for(var c,s,u,f=0,h=[];f1)for(var r=1;r>6|192,t[r++]=63&o|128):55296==(64512&o)&&n+1>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=63&o|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=63&o|128)}return t},o=function(e){for(var t=[],r=0,n=0;r191&&o<224){var i=e[r++];t[n++]=String.fromCharCode((31&o)<<6|63&i)}else if(o>239&&o<365){var i=e[r++],a=e[r++],c=e[r++],s=((7&o)<<18|(63&i)<<12|(63&a)<<6|63&c)-65536;t[n++]=String.fromCharCode(55296+(s>>10)),t[n++]=String.fromCharCode(56320+(1023&s))}else{var i=e[r++],a=e[r++];t[n++]=String.fromCharCode((15&o)<<12|(63&i)<<6|63&a)}}return t.join("")};t.base64={y:null,b:null,_:null,g: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.O();for(var r=t?this._:this.y,n=[],o=0;o>2,h=(3&i)<<4|c>>4,l=(15&c)<<2|u>>6,p=63&u;s||(p=64,a||(l=64)),n.push(r[f],r[h],r[l],r[p])}return n.join("")},encodeString:function(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString:function(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):o(this.decodeStringToByteArray(e,t))},decodeStringToByteArray:function(e,t){this.O();for(var r=t?this.g:this.b,n=[],o=0;o>4;if(n.push(l),64!=u){var p=c<<4&240|u>>2;if(n.push(p),64!=h){var d=u<<6&192|h;n.push(d)}}}return n},O:function(){if(!this.y){this.y={},this.b={},this._={},this.g={};for(var e=0;e=this.ENCODED_VALS_BASE.length&&(this.b[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.g[this.ENCODED_VALS.charAt(e)]=e)}}},t.base64Encode=function(e){var r=n(e);return t.base64.encodeByteArray(r,!0)},t.base64Decode=function(e){try{return t.base64.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}},function(e,t,r){"use strict";function n(e){return JSON.parse(e)}function o(e){return JSON.stringify(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.jsonEval=n,t.stringify=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.contains=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.safeGet=function(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]},t.forEach=function(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t(r,e[r])},t.extend=function(e,r){return t.forEach(r,function(t,r){e[t]=r}),e},t.clone=function(e){return t.extend({},e)},t.isNonNullObject=function(e){return"object"==typeof e&&null!==e},t.isEmpty=function(e){for(var t in e)return!1;return!0},t.getCount=function(e){var t=0;for(var r in e)t++;return t},t.map=function(e,t,r){var n={};for(var o in e)n[o]=t.call(r,e[o],o,e);return n},t.findKey=function(e,t,r){for(var n in e)if(t.call(r,e[n],n,e))return n},t.findValue=function(e,r,n){var o=t.findKey(e,r,n);return o&&e[o]},t.getAnyKey=function(e){for(var t in e)return t},t.getValues=function(e){var t=[],r=0;for(var n in e)t[r++]=e[n];return t},t.every=function(e,t){for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&!t(r,e[r]))return!1;return!0}},,,,,,,,,,,,,,,,,,,,,,,,,,function(e,t,r){r(58),e.exports=r(6).default},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(59),o=(r.n(n),r(63)),i=(r.n(o),r(64));r.n(i)},function(t,r,n){(function(t){var r=function(){if(void 0!==t)return t;if(void 0!==e)return e;if("undefined"!=typeof self)return self;throw Error("unable to locate global object")}();"undefined"==typeof Promise&&(r.Promise=Promise=n(60))}).call(r,n(12))},function(e,t,r){(function(t){!function(r){function n(){}function o(e,t){return function(){e.apply(t,arguments)}}function i(e){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this.T=[],h(e,this)}function a(e,t){for(;3===e._state;)e=e._value;if(0===e._state)return void e.T.push(t);e._handled=!0,i.A(function(){var r=1===e._state?t.onFulfilled:t.onRejected;if(null===r)return void(1===e._state?c:s)(t.promise,e._value);var n;try{n=r(e._value)}catch(e){return void s(t.promise,e)}c(t.promise,n)})}function c(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var r=t.then;if(t instanceof i)return e._state=3,e._value=t,void u(e);if("function"==typeof r)return void h(o(r,t),e)}e._state=1,e._value=t,u(e)}catch(t){s(e,t)}}function s(e,t){e._state=2,e._value=t,u(e)}function u(e){2===e._state&&0===e.T.length&&i.A(function(){e._handled||i.j(e._value)});for(var t=0,r=e.T.length;t=0&&(e.N=setTimeout(function(){e.M&&e.M()},t))},n(62),r.setImmediate=setImmediate,r.clearImmediate=clearImmediate},function(e,t,r){(function(e,t){!function(e,r){"use strict";function n(e){"function"!=typeof e&&(e=Function(""+e));for(var t=Array(arguments.length-1),r=0;r>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var n=arguments[1],o=0;o>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var n=arguments[1],o=0;o"}),r=this.serviceName+": "+r+" ("+o+").";var i=new a(o,r);for(var c in t)t.hasOwnProperty(c)&&"_"!==c.slice(-1)&&(i[c]=t[c]);return i},e}();t.ErrorFactory=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(29),o=r(30);t.decode=function(e){var t={},r={},i={},a="";try{var c=e.split(".");t=o.jsonEval(n.base64Decode(c[0])||""),r=o.jsonEval(n.base64Decode(c[1])||""),a=c[2],i=r.d||{},delete r.d}catch(e){}return{header:t,claims:r,data:i,signature:a}},t.isValidTimestamp=function(e){var r,n,o=t.decode(e).claims,i=Math.floor((new Date).getTime()/1e3);return"object"==typeof o&&(o.hasOwnProperty("nbf")?r=o.nbf:o.hasOwnProperty("iat")&&(r=o.iat),n=o.hasOwnProperty("exp")?o.exp:r+86400),i&&r&&n&&i>=r&&i<=n},t.issuedAtTime=function(e){var r=t.decode(e).claims;return"object"==typeof r&&r.hasOwnProperty("iat")?r.iat:null},t.isValidFormat=function(e){var r=t.decode(e),n=r.claims;return!!r.signature&&!!n&&"object"==typeof n&&n.hasOwnProperty("iat")},t.isAdmin=function(e){var r=t.decode(e).claims;return"object"==typeof r&&!0===r.admin}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(31);t.querystring=function(e){var t=[];return n.forEach(e,function(e,r){Array.isArray(r)?r.forEach(function(r){t.push(encodeURIComponent(e)+"="+encodeURIComponent(r))}):t.push(encodeURIComponent(e)+"="+encodeURIComponent(r))}),t.length?"&"+t.join("&"):""},t.querystringDecode=function(e){var t={};return e.replace(/^\?/,"").split("&").forEach(function(e){if(e){var r=e.split("=");t[r[0]]=r[1]}}),t}},function(e,t,r){"use strict";var n=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])};return function(t,r){function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}();Object.defineProperty(t,"__esModule",{value:!0});var o=r(72),i=function(e){function t(){var t=e.call(this)||this;t.D=[],t.I=[],t.x=[],t.F=[],t.L=0,t.R=0,t.blockSize=64,t.F[0]=128;for(var r=1;r>>31)}for(var i,a,c=this.D[0],s=this.D[1],u=this.D[2],f=this.D[3],h=this.D[4],n=0;n<80;n++){n<40?n<20?(i=f^s&(u^f),a=1518500249):(i=s^u^f,a=1859775393):n<60?(i=s&u|f&(s|u),a=2400959708):(i=s^u^f,a=3395469782);var o=(c<<5|c>>>27)+i+h+a+r[n]&4294967295;h=f,f=u,u=4294967295&(s<<30|s>>>2),s=c,c=o}this.D[0]=this.D[0]+c&4294967295,this.D[1]=this.D[1]+s&4294967295,this.D[2]=this.D[2]+u&4294967295,this.D[3]=this.D[3]+f&4294967295,this.D[4]=this.D[4]+h&4294967295},t.prototype.update=function(e,t){if(null!=e){void 0===t&&(t=e.length);for(var r=t-this.blockSize,n=0,o=this.I,i=this.L;n=56;r--)this.I[r]=255&t,t/=256;this.B(this.I);for(var n=0,r=0;r<5;r++)for(var o=24;o>=0;o-=8)e[n]=this.D[r]>>o&255,++n;return e},t}(o.Hash);t.Sha1=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){this.blockSize=-1}return e}();t.Hash=n},function(e,t,r){"use strict";function n(e,t){var r=new c(e,t);return r.subscribe.bind(r)}function o(e,t){return function(){for(var r=[],n=0;n 4. Need to update it?")}var o=e+" failed: ";return o+=n+" argument "}function o(e,t,r,o){if((!o||r)&&"string"!=typeof r)throw Error(n(e,t,o)+"must be a valid firebase namespace.")}function i(e,t,r,o){if((!o||r)&&"function"!=typeof r)throw Error(n(e,t,o)+"must be a valid function.")}function a(e,t,r,o){if((!o||r)&&("object"!=typeof r||null===r))throw Error(n(e,t,o)+"must be a valid context object.")}Object.defineProperty(t,"__esModule",{value:!0}),t.validateArgCount=function(e,t,r,n){var o;if(nr&&(o=0===r?"none":"no more than "+r),o){var i=e+" failed: Was called with "+n+(1===n?" argument.":" arguments.")+" Expects "+o+".";throw Error(i)}},t.errorPrefix=n,t.validateNamespace=o,t.validateCallback=i,t.validateContextObject=a},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(28);t.stringToByteArray=function(e){for(var t=[],r=0,o=0;o=55296&&i<=56319){var a=i-55296;o++,n.assert(o>6|192,t[r++]=63&i|128):i<65536?(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=63&i|128):(t[r++]=i>>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=63&i|128)}return t},t.stringLength=function(e){for(var t=0,r=0;r=55296&&n<=56319?(t+=4,r++):t+=3}return t}}])}().default; + +/*! + * @license Firebase v4.8.1 + * Build: rev-d8c20f0 + * Terms: https://firebase.google.com/terms/ + */ +try{webpackJsonpFirebase([4],{76:function(t,n,e){e(77)},77:function(t,n,e){(function(t){(function(){function t(t){return"string"==typeof t}function n(t){return"boolean"==typeof t}function i(){}function r(t){var n=typeof t;if("object"==n){if(!t)return"null";if(t instanceof Array)return"array";if(t instanceof Object)return n;var e=Object.prototype.toString.call(t);if("[object Window]"==e)return"object";if("[object Array]"==e||"number"==typeof t.length&&void 0!==t.splice&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("splice"))return"array";if("[object Function]"==e||void 0!==t.call&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("call"))return"function"}else if("function"==n&&void 0===t.call)return"object";return n}function o(t){return null===t}function a(t){return"array"==r(t)}function s(t){var n=r(t);return"array"==n||"object"==n&&"number"==typeof t.length}function u(t){return"function"==r(t)}function c(t){var n=typeof t;return"object"==n&&null!=t||"function"==n}function h(t,n,e){return t.call.apply(t.bind,arguments)}function f(t,n,e){if(!t)throw Error();if(2")&&(t=t.replace(vu,">")),-1!=t.indexOf('"')&&(t=t.replace(mu,""")),-1!=t.indexOf("'")&&(t=t.replace(gu,"'")),-1!=t.indexOf("\0")&&(t=t.replace(bu,"�")),t):t}function b(t,n){return-1!=t.indexOf(n)}function w(t,n){return tn?1:0}function y(t,n){n.unshift(t),v.call(this,m.apply(null,n)),n.shift()}function I(t,n){throw new y("Failure"+(t?": "+t:""),Array.prototype.slice.call(arguments,1))}function T(n,e){var i=n.length,r=t(n)?n.split(""):n;for(--i;0<=i;--i)i in r&&e.call(void 0,r[i],i,n)}function A(n){t:{for(var e=Ae,i=n.length,r=t(n)?n.split(""):n,o=0;oe?null:t(n)?n.charAt(e):n[e]}function k(t,n){return 0<=Iu(t,n)}function E(t,n){n=Iu(t,n);var e;return(e=0<=n)&&Array.prototype.splice.call(t,n,1),e}function N(t,n){var e=0;T(t,function(i,r){n.call(void 0,i,r,t)&&1==Array.prototype.splice.call(t,r,1).length&&e++})}function S(t){return Array.prototype.concat.apply([],arguments)}function O(t){var n=t.length;if(0"),s=s.join("")}return s=o.createElement(s),u&&(t(u)?s.className=u:a(u)?s.className=u.join(" "):Lt(s,u)),2i.keyCode||void 0!=i.returnValue)){t:{var r=!1;if(0==i.keyCode)try{i.keyCode=-1;break t}catch(t){r=!0}(r||void 0==i.returnValue)&&(i.returnValue=!0)}for(i=[],r=n.b;r;r=r.parentNode)i.push(r);for(t=t.type,r=i.length-1;0<=r;r--){n.b=i[r];var o=an(i[r],t,!0,n);e=e&&o}for(r=0;r>4),64!=a&&(n(o<<4&240|a>>2),64!=s&&n(a<<6&192|s))}}function Cn(){if(!Sc){Sc={},Oc={};for(var t=0;65>t;t++)Sc[t]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(t),Oc[Sc[t]]=t,62<=t&&(Oc["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.".charAt(t)]=t)}}function Rn(t,n){this.g=[],this.v=t,this.o=n||null,this.f=this.a=!1,this.c=void 0,this.u=this.w=this.i=!1,this.h=0,this.b=null,this.l=0}function _n(t,n,e){t.a=!0,t.c=e,t.f=!n,jn(t)}function Dn(t){if(t.a){if(!t.u)throw new Mn;t.u=!1}}function Ln(t,n){xn(t,null,n,void 0)}function xn(t,n,e,i){t.g.push([n,e,i]),t.a&&jn(t)}function Un(t){return ku(t.g,function(t){return u(t[1])})}function jn(t){if(t.h&&t.a&&Un(t)){var n=t.h,e=Cc[n];e&&(uu.clearTimeout(e.a),delete Cc[n]),t.h=0}t.b&&(t.b.l--,delete t.b),n=t.c;for(var i=e=!1;t.g.length&&!t.i;){var r=t.g.shift(),o=r[0],a=r[1];if(r=r[2],o=t.f?a:o)try{var s=o.call(r||t.o,n);void 0!==s&&(t.f=t.f&&(s==n||s instanceof Error),t.c=n=s),(q(n)||"function"==typeof uu.Promise&&n instanceof uu.Promise)&&(i=!0,t.i=!0)}catch(i){n=i,t.f=!0,Un(t)||(e=!0)}}t.c=n,i&&(s=l(t.m,t,!0),i=l(t.m,t,!1),n instanceof Rn?(xn(n,s,i),n.w=!0):n.then(s,i)),e&&(n=new Fn(n),Cc[n.a]=n,t.h=n.a)}function Mn(){v.call(this)}function Vn(){v.call(this)}function Fn(t){this.a=uu.setTimeout(l(this.c,this),0),this.b=t}function Kn(){this.b=-1}function qn(t,n){this.b=-1,this.b=Rc,this.f=uu.Uint8Array?new Uint8Array(this.b):Array(this.b),this.g=this.c=0,this.a=[],this.i=t,this.h=n,this.l=uu.Int32Array?new Int32Array(64):Array(64),Pc||(Pc=uu.Int32Array?new Int32Array(Uc):Uc),this.reset()}function Xn(t){for(var n=t.f,e=t.l,i=0,r=0;rn;n++){r=0|e[n-15],i=0|e[n-2];var o=(0|e[n-16])+((r>>>7|r<<25)^(r>>>18|r<<14)^r>>>3)|0,a=(0|e[n-7])+((i>>>17|i<<15)^(i>>>19|i<<13)^i>>>10)|0;e[n]=o+a|0}i=0|t.a[0],r=0|t.a[1];var s=0|t.a[2],u=0|t.a[3],c=0|t.a[4],h=0|t.a[5],f=0|t.a[6];for(o=0|t.a[7],n=0;64>n;n++){var l=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&r^i&s^r&s)|0;a=c&h^~c&f,o=o+((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))|0,a=a+(0|Pc[n])|0,a=o+(a+(0|e[n])|0)|0,o=f,f=h,h=c,c=u+a|0,u=s,s=r,r=i,i=a+l|0}t.a[0]=t.a[0]+i|0,t.a[1]=t.a[1]+r|0,t.a[2]=t.a[2]+s|0,t.a[3]=t.a[3]+u|0,t.a[4]=t.a[4]+c|0,t.a[5]=t.a[5]+h|0,t.a[6]=t.a[6]+f|0,t.a[7]=t.a[7]+o|0}function Bn(n,e,i){void 0===i&&(i=e.length);var r=0,o=n.c;if(t(e))for(;r=a&&a==(0|a)))throw Error("message must be a byte array");n.f[o++]=a,o==n.b&&(Xn(n),o=0)}}n.c=o,n.g+=i}function Hn(){qn.call(this,8,jc)}function Wn(n){if(n.P&&"function"==typeof n.P)return n.P();if(t(n))return n.split("");if(s(n)){for(var e=[],i=n.length,r=0;rn)throw Error("Bad port number "+n);t.i=n}else t.i=null}function Qn(t,n,e){n instanceof se?(t.a=n,ve(t.a,t.f)):(e||(n=oe(n,qc)),t.a=new se(n,0,t.f))}function te(t,n,e){t.a.set(n,e)}function ne(t,n){return t.a.get(n)}function ee(t){return t instanceof Yn?new Yn(t):new Yn(t,void 0)}function ie(t,n){var e=new Yn(null,void 0);return $n(e,"https"),t&&(e.b=t),n&&(e.g=n),e}function re(t,n){return t?n?decodeURI(t.replace(/%25/g,"%2525")):decodeURIComponent(t):""}function oe(n,e,i){return t(n)?(n=encodeURI(n).replace(e,ae),i&&(n=n.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),n):null}function ae(t){return t=t.charCodeAt(0),"%"+(t>>4&15).toString(16)+(15&t).toString(16)}function se(t,n,e){this.b=this.a=null,this.c=t||null,this.f=!!e}function ue(t){t.a||(t.a=new An,t.b=0,t.c&&Jn(t.c,function(n,e){he(t,decodeURIComponent(n.replace(/\+/g," ")),e)}))}function ce(t){var n=Gn(t);if(void 0===n)throw Error("Keys are undefined");var e=new se(null,0,void 0);t=Wn(t);for(var i=0;i2*t.c&&kn(t)))}function le(t,n){return ue(t),n=pe(t,n),En(t.a.b,n)}function de(t,n,e){fe(t,n),0t||Cu&&Mu&&!(9',t=_t(t),a.document.write(Rt(t)),a.document.close())):a=t.open(St(n),e,a),a)try{a.focus()}catch(t){}return a}function Je(t){return new Z(function(n){function e(){gn(2e3).then(function(){if(t&&!t.closed)return e();n()})}return e()})}function Ye(){var t=null;return new Z(function(n){"complete"==uu.document.readyState?n():(t=function(){n()},nn(window,"load",t))}).s(function(n){throw en(window,"load",t),n})}function $e(){return Ze(void 0)?Ye().then(function(){return new Z(function(t,n){var e=uu.document,i=setTimeout(function(){n(Error("Cordova framework is not ready."))},1e3);e.addEventListener("deviceready",function(){clearTimeout(i),t()},!1)})}):et(Error("Cordova must run in an Android or iOS file scheme."))}function Ze(t){return t=t||ri(),!("file:"!==ci()||!t.toLowerCase().match(/iphone|ipad|ipod|android/))}function Qe(){var t=uu.window;try{return!(!t||t==t.top)}catch(t){return!1}}function ti(){return au.INTERNAL.hasOwnProperty("reactNative")?"ReactNative":au.INTERNAL.hasOwnProperty("node")?"Node":"Browser"}function ni(){var t=ti();return"ReactNative"===t||"Node"===t}function ei(t){var n=t.toLowerCase();return b(n,"opera/")||b(n,"opr/")||b(n,"opios/")?"Opera":b(n,"iemobile")?"IEMobile":b(n,"msie")||b(n,"trident/")?"IE":b(n,"edge/")?"Edge":b(n,"firefox/")?th:b(n,"silk/")?"Silk":b(n,"blackberry")?"Blackberry":b(n,"webos")?"Webos":!b(n,"safari/")||b(n,"chrome/")||b(n,"crios/")||b(n,"android")?!b(n,"chrome/")&&!b(n,"crios/")||b(n,"edge/")?b(n,"android")?"Android":(t=t.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/))&&2==t.length?t[1]:"Other":nh:"Safari"}function ii(t,n){n=n||[];var e,i=[],r={};for(e in eh)r[eh[e]]=!0;for(e=0;en)throw Error("Short delay should be less than long delay!");this.c=t,this.b=n,t=e||ri(),i=i||ti(),this.a=We(t)||"ReactNative"===i}function wi(){var t=uu.document;return!t||void 0===t.visibilityState||"visible"==t.visibilityState}function yi(){var t=uu.document,n=null;return wi()||!t?nt():new Z(function(e){n=function(){wi()&&(t.removeEventListener("visibilitychange",n,!1),e())},t.addEventListener("visibilitychange",n,!1)}).s(function(e){throw t.removeEventListener("visibilitychange",n,!1),e})}function Ii(t){try{var n=new Date(parseInt(t,10));if(!isNaN(n.getTime())&&!/[^0-9]/.test(t))return n.toUTCString()}catch(t){}return null}function Ti(t,n,e){ih?Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:e}):t[n]=e}function Ai(t,n){if(n)for(var e in n)n.hasOwnProperty(e)&&Ti(t,e,n[e])}function ki(t){var n={};return Ai(n,t),n}function Ei(t){var n,e={};for(n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}function Ni(t,n){if(!n||!n.length)return!0;if(!t)return!1;for(var e=0;e Auth section -> Sign in method tab.",t):"http"==i||"https"==i?e=m("This domain (%s) is not authorized to run this operation. Add it to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.",t):n="operation-not-supported-in-this-environment",Pi.call(this,n,e)}function dr(t,n,e){Pi.call(this,t,e),t=n||{},t.sb&&Ti(this,"email",t.sb),t.Y&&Ti(this,"phoneNumber",t.Y),t.credential&&Ti(this,"credential",t.credential)}function pr(t){if(t.code){var n=t.code||"";0==n.indexOf(dh)&&(n=n.substring(dh.length));var e={credential:ur(t)};if(t.email)e.sb=t.email;else{if(!t.phoneNumber)return new Pi(n,t.message||void 0);e.Y=t.phoneNumber}return new dr(n,e,t.message)}return null}function vr(t){this.f=t}function mr(t,n,e){var i="Node"==ti();if(!(i=uu.XMLHttpRequest||i&&au.INTERNAL.node&&au.INTERNAL.node.XMLHttpRequest))throw new Pi("internal-error","The XMLHttpRequest compatibility library was not found.");this.b=t,t=n||{},this.i=t.secureTokenEndpoint||"https://securetoken.googleapis.com/v1/token",this.l=t.secureTokenTimeout||Ch,this.c=x(t.secureTokenHeaders||Rh),this.g=t.firebaseEndpoint||"https://www.googleapis.com/identitytoolkit/v3/relyingparty/",this.h=t.firebaseTimeout||_h,this.a=x(t.firebaseHeaders||Dh),e&&(this.a["X-Client-Version"]=e,this.c["X-Client-Version"]=e),this.f=new Me,this.o=new vr(i)}function gr(t,n){n?t.a["X-Firebase-Locale"]=n:delete t.a["X-Firebase-Locale"]}function br(t,n){n?(t.a["X-Client-Version"]=n,t.c["X-Client-Version"]=n):(delete t.a["X-Client-Version"],delete t.c["X-Client-Version"])}function wr(t,n,e,i,r,o,a){gi()?(He()?t=l(t.m,t):(Oh||(Oh=new Z(function(t,n){yr(t,n)})),t=l(t.u,t)),t(n,e,i,r,o,a)):e&&e(null)}function yr(t,n){((window.gapi||{}).client||{}).request?t():(uu[xh]=function(){((window.gapi||{}).client||{}).request?t():n(Error("CORS_UNSUPPORTED"))},Ln(De(kt(Lh,{onload:xh})),function(){n(Error("CORS_UNSUPPORTED"))}))}function Ir(t,n){return new Z(function(e,i){"refresh_token"==n.grant_type&&n.refresh_token||"authorization_code"==n.grant_type&&n.code?wr(t,t.i+"?key="+encodeURIComponent(t.b),function(t){t?t.error?i(Vr(t)):t.access_token&&t.refresh_token?e(t):i(new Pi("internal-error")):i(new Pi("network-request-failed"))},"POST",""+ce(n),t.c,t.l.get()):i(new Pi("internal-error"))})}function Tr(t,n,e,i,r,o){var a=ee(t.g+n);te(a,"key",t.b),o&&te(a,"cb",""+fu());var s="GET"==e;if(s)for(var u in i)i.hasOwnProperty(u)&&te(a,u,i[u]);return new Z(function(n,o){wr(t,""+a,function(t){t?t.error?o(Vr(t,r||{})):n(t):o(new Pi("network-request-failed"))},e,s?void 0:Mt(li(i)),t.a,t.h.get())})}function Ar(t){if(!Yc.test(t.email))throw new Pi("invalid-email")}function kr(t){"email"in t&&Ar(t)}function Er(t,n){return jr(t,Kh,{identifier:n,continueUri:ui()?qe():"http://localhost"}).then(function(t){return t.allProviders||[]})}function Nr(t){return jr(t,Gh,{}).then(function(t){return t.authorizedDomains||[]})}function Sr(t){if(!t[Ph])throw new Pi("internal-error")}function Or(t){if(t.phoneNumber||t.temporaryProof){if(!t.phoneNumber||!t.temporaryProof)throw new Pi("internal-error")}else{if(!t.sessionInfo)throw new Pi("missing-verification-id");if(!t.code)throw new Pi("missing-verification-code")}}function Pr(t,n){return jr(t,Yh,n)}function Cr(t,n,e){return jr(t,Xh,{idToken:n,deleteProvider:e})}function Rr(t){if(!t.requestUri||!t.sessionId&&!t.postBody)throw new Pi("internal-error")}function _r(t){var n=null;if(t.needConfirmation?(t.code="account-exists-with-different-credential",n=pr(t)):"FEDERATED_USER_ID_ALREADY_LINKED"==t.errorMessage?(t.code="credential-already-in-use",n=pr(t)):"EMAIL_EXISTS"==t.errorMessage?(t.code="email-already-in-use",n=pr(t)):t.errorMessage&&(n=Mr(t.errorMessage)),n)throw n;if(!t[Ph])throw new Pi("internal-error")}function Dr(t,n){return n.returnIdpCredential=!0,jr(t,tf,n)}function Lr(t,n){return n.returnIdpCredential=!0,jr(t,ef,n)}function xr(t,n){return n.returnIdpCredential=!0,n.autoCreate=!1,jr(t,nf,n)}function Ur(t){if(!t.oobCode)throw new Pi("invalid-action-code")}function jr(t,n,e){if(!Ni(e,n.ea))return et(new Pi("internal-error"));var i,r=n.zb||"POST";return nt(e).then(n.D).then(function(){return n.T&&(e.returnSecureToken=!0),Tr(t,n.endpoint,r,e,n.Pb,n.nb||!1)}).then(function(t){return i=t}).then(n.O).then(function(){if(!n.ga)return i;if(!(n.ga in i))throw new Pi("internal-error");return i[n.ga]})}function Mr(t){return Vr({error:{errors:[{message:t}],code:400,message:t}})}function Vr(t,n){var e=(t.error&&t.error.errors&&t.error.errors[0]||{}).reason||"",i={keyInvalid:"invalid-api-key",ipRefererBlocked:"app-not-authorized"};if(e=i[e]?new Pi(i[e]):null)return e;e=t.error&&t.error.message||"",i={INVALID_CUSTOM_TOKEN:"invalid-custom-token",CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_EMAIL:"invalid-email",INVALID_PASSWORD:"wrong-password",USER_DISABLED:"user-disabled",MISSING_PASSWORD:"internal-error",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",INVALID_MESSAGE_PAYLOAD:"invalid-message-payload",INVALID_RECIPIENT_EMAIL:"invalid-recipient-email",INVALID_SENDER:"invalid-sender",EMAIL_NOT_FOUND:"user-not-found",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",CORS_UNSUPPORTED:"cors-unsupported",DYNAMIC_LINK_NOT_ACTIVATED:"dynamic-link-not-activated",INVALID_APP_ID:"invalid-app-id",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",WEAK_PASSWORD:"weak-password",OPERATION_NOT_ALLOWED:"operation-not-allowed",USER_CANCELLED:"user-cancelled",CAPTCHA_CHECK_FAILED:"captcha-check-failed",INVALID_APP_CREDENTIAL:"invalid-app-credential",INVALID_CODE:"invalid-verification-code",INVALID_PHONE_NUMBER:"invalid-phone-number",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_APP_CREDENTIAL:"missing-app-credential",MISSING_CODE:"missing-verification-code",MISSING_PHONE_NUMBER:"missing-phone-number",MISSING_SESSION_INFO:"missing-verification-id",QUOTA_EXCEEDED:"quota-exceeded",SESSION_EXPIRED:"code-expired",INVALID_CONTINUE_URI:"invalid-continue-uri",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",MISSING_IOS_BUNDLE_ID:"missing-ios-bundle-id",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",INVALID_CERT_HASH:"invalid-cert-hash"},U(i,n||{}),n=(n=e.match(/^[^\s]+\s*:\s*(.*)$/))&&1n.c?Bn(n,xc,56-n.c):Bn(n,xc,n.b-(n.c-56));for(var i=63;56<=i;i--)n.f[i]=255&e,e/=256;for(Xn(n),i=e=0;i>r&255;return Sn(t)}function Mo(t,n,e,i){var r=Uo(),o=new hr(n,i,null,r,new Pi("no-auth-event")),a=oi("BuildInfo.packageName",uu);if("string"!=typeof a)throw new Pi("invalid-cordova-configuration");var s=oi("BuildInfo.displayName",uu),u={};if(ri().toLowerCase().match(/iphone|ipad|ipod/))u.ibi=a;else{if(!ri().toLowerCase().match(/android/))return et(new Pi("operation-not-supported-in-this-environment"));u.apn=a}s&&(u.appDisplayName=s),r=jo(r),u.sessionId=r;var c=Qr(t.u,t.i,t.l,n,e,null,i,t.m,u,t.o);return t.ba().then(function(){var n=t.h;return t.A.a.set(If,o.B(),n)}).then(function(){var n=oi("cordova.plugins.browsertab.isAvailable",uu);if("function"!=typeof n)throw new Pi("invalid-cordova-configuration");var e=null;n(function(n){if(n){if("function"!=typeof(e=oi("cordova.plugins.browsertab.openUrl",uu)))throw new Pi("invalid-cordova-configuration");e(c)}else{if("function"!=typeof(e=oi("cordova.InAppBrowser.open",uu)))throw new Pi("invalid-cordova-configuration");n=ri(),n=!(!n.match(/(iPad|iPhone|iPod).*OS 7_\d/i)&&!n.match(/(iPad|iPhone|iPod).*OS 8_\d/i)),t.a=e(c,n?"_blank":"_system","location=yes")}})})}function Vo(t,n){for(var e=0;et.f&&(t.a=t.f),n)}function da(t,n){pa(t),t.b=gn(la(t,n)).then(function(){return t.l?nt():yi()}).then(function(){return t.h()}).then(function(){da(t,!0)}).s(function(n){t.i(n)&&da(t,!1)})}function pa(t){t.b&&(t.b.cancel(),t.b=null)}function va(t){this.f=t,this.b=this.a=null,this.c=0}function ma(t,n){var e=n[Ph],i=n.refreshToken;n=ga(n.expiresIn),t.b=e,t.c=n,t.a=i}function ga(t){return fu()+1e3*parseInt(t,10)}function ba(t,n){return Ir(t.f,n).then(function(n){return t.b=n.access_token,t.c=ga(n.expires_in),t.a=n.refresh_token,{accessToken:t.b,expirationTime:t.c,refreshToken:t.a}}).s(function(n){throw"auth/user-token-expired"==n.code&&(t.a=null),n})}function wa(t,n){this.a=t||null,this.b=n||null,Ai(this,{lastSignInTime:Ii(n||null),creationTime:Ii(t||null)})}function ya(t){return new wa(t.a,t.b)}function Ia(t,n,e,i,r,o){Ai(this,{uid:t,displayName:i||null,photoURL:r||null,email:e||null,phoneNumber:o||null,providerId:n})}function Ta(t,n){Bt.call(this,t);for(var e in n)this[e]=n[e]}function Aa(t,n,e){this.A=[],this.G=t.apiKey,this.o=t.appName,this.w=t.authDomain||null,t=au.SDK_VERSION?ii(au.SDK_VERSION):null,this.c=new mr(this.G,Fr(jh),t),this.h=new va(this.c),Ra(this,n[Ph]),ma(this.h,n),Ti(this,"refreshToken",this.h.a),xa(this,e||{}),fn.call(this),this.I=!1,this.w&&si()&&(this.a=Qo(this.w,this.G,this.o)),this.N=[],this.i=null,this.l=Oa(this),this.U=l(this.Ga,this);var i=this;this.ha=null,this.ra=function(t){i.na(t.h)},this.W=null,this.R=[],this.qa=function(t){Ea(i,t.f)},this.V=null}function ka(t,n){t.W&&en(t.W,"languageCodeChanged",t.ra),(t.W=n)&&Zt(n,"languageCodeChanged",t.ra)}function Ea(t,n){t.R=n,br(t.c,au.SDK_VERSION?ii(au.SDK_VERSION,t.R):null)}function Na(t,n){t.V&&en(t.V,"frameworkChanged",t.qa),(t.V=n)&&Zt(n,"frameworkChanged",t.qa)}function Sa(t){try{return au.app(t.o).auth()}catch(n){throw new Pi("internal-error","No firebase.auth.Auth instance is available for the Firebase App '"+t.o+"'!")}}function Oa(t){return new fa(function(){return t.F(!0)},function(t){return!(!t||"auth/network-request-failed"!=t.code)},function(){var n=t.h.c-fu()-3e5;return 0r||r>=Of.length)throw new Pi("internal-error","Argument validator received an unsupported number of arguments.");e=Of[r],i=(i?"":e+" argument ")+(n.name?'"'+n.name+'" ':"")+"must be "+n.K+".";break t}i=null}}if(i)throw new Pi("argument-error",t+" failed: "+i)}function Ls(n,e){return{name:n||"",K:"a valid string",optional:!!e,M:t}}function xs(){return{name:"opt_forceRefresh",K:"a boolean",optional:!0,M:n}}function Us(t,n){return{name:t||"",K:"a valid object",optional:!!n,M:c}}function js(t,n){return{name:t||"",K:"a function",optional:!!n,M:u}}function Ms(t,n){return{name:t||"",K:"null",optional:!!n,M:o}}function Vs(){return{name:"",K:"an HTML element",optional:!1,M:function(t){return!!(t&&t instanceof Element)}}}function Fs(){return{name:"auth",K:"an instance of Firebase Auth",optional:!0,M:function(t){return!!(t&&t instanceof vs)}}}function Ks(){return{name:"app",K:"an instance of Firebase App",optional:!0,M:function(t){return!!(t&&t instanceof au.app.App)}}}function qs(t){return{name:t?t+"Credential":"credential",K:t?"a valid "+t+" credential":"a valid credential",optional:!1,M:function(n){if(!n)return!1;var e=!t||n.providerId===t;return!(!n.wa||!e)}}}function Xs(){return{name:"authProvider",K:"a valid Auth provider",optional:!1,M:function(t){return!!(t&&t.providerId&&t.hasOwnProperty&&t.hasOwnProperty("isOAuthProvider"))}}}function Bs(){return{name:"applicationVerifier",K:"an implementation of firebase.auth.ApplicationVerifier",optional:!1,M:function(n){return!!(n&&t(n.type)&&u(n.verify))}}}function Hs(t,n,e,i){return{name:e||"",K:t.K+" or "+n.K,optional:!!i,M:function(e){return t.M(e)||n.M(e)}}}function Ws(t,n,e,i,r,o){if(Ti(this,"type","recaptcha"),this.b=this.c=null,this.m=!1,this.l=n,this.a=e||{theme:"light",type:"image"},this.g=[],this.a[Rf])throw new Pi("argument-error","sitekey should not be provided for reCAPTCHA as one is automatically provisioned for the current project.");if(this.h="invisible"===this.a[_f],!Dt(n)||!this.h&&Dt(n).hasChildNodes())throw new Pi("argument-error","reCAPTCHA container is either not found or already contains inner elements!");this.u=new mr(t,o||null,r||null),this.o=i||function(){return null};var a=this;this.i=[];var s=this.a[Pf];this.a[Pf]=function(t){if(Gs(a,t),"function"==typeof s)s(t);else if("string"==typeof s){var n=oi(s,uu);"function"==typeof n&&n(t)}};var u=this.a[Cf];this.a[Cf]=function(){if(Gs(a,null),"function"==typeof u)u();else if("string"==typeof u){var t=oi(u,uu);"function"==typeof t&&t()}}}function Gs(t,n){for(var e=0;e>>0),hu=0,fu=Date.now||function(){return+new Date};p(v,Error),v.prototype.name="CustomError";var lu=String.prototype.trim?function(t){return t.trim()}:function(t){return t.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")},du=/&/g,pu=//g,mu=/"/g,gu=/'/g,bu=/\x00/g,wu=/[\x00&<>"']/;p(y,v),y.prototype.name="AssertionError";var yu,Iu=Array.prototype.indexOf?function(t,n,e){return Array.prototype.indexOf.call(t,n,e)}:function(n,e,i){if(i=null==i?0:0>i?Math.max(0,n.length+i):i,t(n))return t(e)&&1==e.length?n.indexOf(e,i):-1;for(;iparseFloat(xu)){Ou=ju+"";break t}}Ou=xu}var Mu,Vu={},Fu=uu.document;Mu=Fu&&Cu?V()||("CSS1Compat"==Fu.compatMode?parseInt(Ou,10):5):void 0,X.prototype.get=function(){if(0"),_t(""),_t("
");var oc={cellpadding:"cellPadding",cellspacing:"cellSpacing",colspan:"colSpan",frameborder:"frameBorder",height:"height",maxlength:"maxLength",nonce:"nonce",role:"role",rowspan:"rowSpan",type:"type",usemap:"useMap",valign:"vAlign",width:"width"},ac={'"':'\\"',"\\":"\\\\","/":"\\/","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\u000b"},sc=/\uffff/.test("￿")?/[\\\"\x00-\x1f\x7f-\uffff]/g:/[\\\"\x00-\x1f\x7f-\xff]/g,uc=0,cc={};qt.prototype.oa=!1,qt.prototype.ta=function(){if(this.Fa)for(;this.Fa.length;)this.Fa.shift()()};var hc=Object.freeze||function(t){return t},fc=!Cu||9<=+Mu,lc=Cu&&!F("9"),dc=function(){if(!uu.addEventListener||!Object.defineProperty)return!1;var t=!1,n=Object.defineProperty({},"passive",{get:function(){t=!0}});return uu.addEventListener("test",i,n),uu.removeEventListener("test",i,n),t}();Bt.prototype.c=function(){this.Bb=!1},p(Ht,Bt);var pc=hc({2:"touch",3:"pen",4:"mouse"});Ht.prototype.c=function(){Ht.ib.c.call(this);var t=this.a;if(t.preventDefault)t.preventDefault();else if(t.returnValue=!1,lc)try{(t.ctrlKey||112<=t.keyCode&&123>=t.keyCode)&&(t.keyCode=-1)}catch(t){}},Ht.prototype.g=function(){return this.a};var vc="closure_listenable_"+(1e6*Math.random()|0),mc=0,gc="closure_lm_"+(1e6*Math.random()|0),bc={},wc=0,yc="__closure_events_fn_"+(1e9*Math.random()>>>0);p(fn,qt),fn.prototype[vc]=!0,fn.prototype.removeEventListener=function(t,n,e,i){en(this,t,n,e,i)},fn.prototype.ta=function(){if(fn.ib.ta.call(this),this.u){var t,n=this.u,e=0;for(t in n.a){for(var i=n.a[t],r=0;r=In(this).value)for(u(n)&&(n=n()),t=new bn(t,n+"",this.f),e&&(t.a=e),e="log:"+t.b,(t=uu.console)&&t.timeStamp&&t.timeStamp(e),(t=uu.msWriteProfilerMark)&&t(e),e=this;e;)e=e.a};var Ec={},Nc=null;ou=An.prototype,ou.P=function(){kn(this);for(var t=[],n=0;n=--n.l&&n.cancel()}this.v?this.v.call(this.o,this):this.u=!0,this.a||(t=new Vn,Dn(this),_n(this,!1,t))}},Rn.prototype.m=function(t,n){this.i=!1,_n(this,t,n)},Rn.prototype.A=function(t){Dn(this),_n(this,!0,t)},Rn.prototype.then=function(t,n,e){var i,r,o=new Z(function(t,n){i=t,r=n});return xn(this,i,function(t){t instanceof Vn?o.cancel():r(t)}),o.then(t,n,e)},K(Rn),p(Mn,v),Mn.prototype.message="Deferred has already fired",Mn.prototype.name="AlreadyCalledError",p(Vn,v),Vn.prototype.message="Deferred was canceled",Vn.prototype.name="CanceledError",Fn.prototype.c=function(){throw delete Cc[this.a],this.b};var Pc,Cc={};p(qn,Kn);for(var Rc=64,_c=Rc-1,Dc=[],Lc=0;Lc<_c;Lc++)Dc[Lc]=0;var xc=S(128,Dc);qn.prototype.reset=function(){this.g=this.c=0,this.a=uu.Int32Array?new Int32Array(this.h):O(this.h)};var Uc=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];p(Hn,qn);var jc=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],Mc=/^(?:([^:\/?#.]+):)?(?:\/\/(?:([^\/?#]*)@)?([^\/#?]*?)(?::([0-9]+))?(?=[\/#?]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;Yn.prototype.toString=function(){var t=[],n=this.c;n&&t.push(oe(n,Vc,!0),":");var e=this.b;return(e||"file"==n)&&(t.push("//"),(n=this.l)&&t.push(oe(n,Vc,!0),"@"),t.push(encodeURIComponent(e+"").replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(e=this.i)&&t.push(":",e+"")),(e=this.g)&&(this.b&&"/"!=e.charAt(0)&&t.push("/"),t.push(oe(e,"/"==e.charAt(0)?Kc:Fc,!0))),(e=""+this.a)&&t.push("?",e),(e=this.h)&&t.push("#",oe(e,Xc)),t.join("")};var Vc=/[#\/\?@]/g,Fc=/[\#\?:]/g,Kc=/[\#\?]/g,qc=/[\#\?@]/g,Xc=/#/g;ou=se.prototype,ou.clear=function(){this.a=this.c=null,this.b=0},ou.forEach=function(t,n){ue(this),this.a.forEach(function(e,i){Tu(e,function(e){t.call(n,e,i,this)},this)},this)},ou.S=function(){ue(this);for(var t=this.a.P(),n=this.a.S(),e=[],i=0;ithis.c-3e4?this.a?ba(this,{grant_type:"refresh_token",refresh_token:this.a}):nt(null):nt({accessToken:this.b,expirationTime:this.c,refreshToken:this.a})},wa.prototype.B=function(){return{lastLoginAt:this.b,createdAt:this.a}},p(Ta,Bt),p(Aa,fn),Aa.prototype.na=function(t){this.ha=t,gr(this.c,t)},Aa.prototype.$=function(){return this.ha},Aa.prototype.Ka=function(){return O(this.R)},Aa.prototype.Ga=function(){this.l.b&&(pa(this.l),this.l.start())},Ti(Aa.prototype,"providerId","firebase"),ou=Aa.prototype,ou.reload=function(){var t=this;return Qa(this,ja(this).then(function(){return Xa(t).then(function(){return Da(t)}).then(Ua)}))},ou.F=function(t){var n=this;return Qa(this,ja(this).then(function(){return n.h.getToken(t)}).then(function(t){if(!t)throw new Pi("internal-error");return t.accessToken!=n.pa&&(Ra(n,t.accessToken),ln(n,new Ta("tokenChanged"))),Ka(n,"refreshToken",t.refreshToken),t.accessToken}))},ou.getToken=function(t){return rh["firebase.User.prototype.getToken is deprecated. Please use firebase.User.prototype.getIdToken instead."]||(rh["firebase.User.prototype.getToken is deprecated. Please use firebase.User.prototype.getIdToken instead."]=!0,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn("firebase.User.prototype.getToken is deprecated. Please use firebase.User.prototype.getIdToken instead.")),this.F(t)},ou.kc=function(t){if(!(t=t.users)||!t.length)throw new Pi("internal-error");t=t[0],xa(this,{uid:t.localId,displayName:t.displayName,photoURL:t.photoUrl,email:t.email,emailVerified:!!t.emailVerified,phoneNumber:t.phoneNumber,lastLoginAt:t.lastLoginAt,createdAt:t.createdAt});for(var n=Wa(t),e=0;ethis.o&&(this.o=0),0==this.o&&Os(this)&&Ca(Os(this)),this.removeAuthTokenListener(t)},ou.addAuthTokenListener=function(t){var n=this;this.m.push(t),_s(this,this.i.then(function(){n.l||k(n.m,t)&&t(Ps(n))}))},ou.removeAuthTokenListener=function(t){N(this.m,function(n){return n==t})},ou.delete=function(){this.l=!0;for(var t=0;tn?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r},t.each=function(e,t){if(Array.isArray(e))for(var n=0;n=Math.pow(2,-1022)?(a=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),i=a+1023,o=Math.round(e*Math.pow(2,52-a)-Math.pow(2,52))):(i=0,o=Math.round(e/Math.pow(2,-1074)))),u=[],s=52;s;s-=1)u.push(o%2?1:0),o=Math.floor(o/2);for(s=11;s;s-=1)u.push(i%2?1:0),i=Math.floor(i/2);u.push(n?1:0),u.reverse(),l=u.join("");var h="";for(s=0;s<64;s+=8){var c=parseInt(l.substr(s,8),2).toString(16);1===c.length&&(c="0"+c),h+=c}return h.toLowerCase()},t.isChromeExtensionContentScript=function(){return!("object"!=typeof window||!window.chrome||!window.chrome.extension||/^chrome/.test(window.location.href))},t.isWindowsStoreApp=function(){return"object"==typeof Windows&&"object"==typeof Windows.UI},t.errorForServerCode=function(e,t){var n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"==e?n="Client doesn't have permission to access the desired data.":"unavailable"==e&&(n="The service is unavailable");var r=Error(e+" at "+t.path+": "+n);return r.code=e.toUpperCase(),r},t.e=RegExp("^-?\\d{1,10}$"),t.tryParseInt=function(e){if(t.e.test(e)){var n=+e;if(n>=-2147483648&&n<=2147483647)return n}return null},t.exceptionGuard=function(e){try{e()}catch(e){setTimeout(function(){var n=e.stack||"";throw t.warn("Exception was thrown by user callback.",n),e},Math.floor(0))}},t.callUserCallback=function(e){for(var n=[],r=1;r=0},t.exportPropGetter=function(e,t,n){Object.defineProperty(e,t,{get:n})},t.setTimeoutNonBlocking=function(e,t){var n=setTimeout(e,t);return"object"==typeof n&&n.unref&&n.unref(),n}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),i=n(0),o=function(){function e(e,t){if(void 0===t){this.n=e.split("/");for(var n=0,r=0;r0&&(this.n[n]=this.n[r],n++);this.n.length=n,this.i=0}else this.n=e,this.i=t}return Object.defineProperty(e,"Empty",{get:function(){return new e("")},enumerable:!0,configurable:!0}),e.prototype.getFront=function(){return this.i>=this.n.length?null:this.n[this.i]},e.prototype.getLength=function(){return this.n.length-this.i},e.prototype.popFront=function(){var t=this.i;return t=this.n.length)return null;for(var t=[],n=this.i;n0&&n.push(i[r]);return new e(n,0)},e.prototype.isEmpty=function(){return this.i>=this.n.length},e.relativePath=function(t,n){var r=t.getFront(),i=n.getFront();if(null===r)return n;if(r===i)return e.relativePath(t.popFront(),n.popFront());throw Error("INTERNAL ERROR: innerPath ("+n+") is not within outerPath ("+t+")")},e.comparePaths=function(e,t){for(var n=e.slice(),i=t.slice(),o=0;oe.getLength())return!1;for(;t0&&(this.l+=1),this.u.push(e),this.l+=i.stringLength(e),this.f()},e.prototype.pop=function(){var e=this.u.pop();this.l-=i.stringLength(e),this.u.length>0&&(this.l-=1)},e.prototype.f=function(){if(this.l>e.MAX_PATH_LENGTH_BYTES)throw Error(this.o+"has a key path longer than "+e.MAX_PATH_LENGTH_BYTES+" bytes ("+this.l+").");if(this.u.length>e.MAX_PATH_DEPTH)throw Error(this.o+"path specified exceeds the maximum depth that can be written ("+e.MAX_PATH_DEPTH+") or object contains a cycle "+this.toErrorString())},e.prototype.toErrorString=function(){return 0==this.u.length?"":"in property '"+this.u.join(".")+"'"},e}();t.ValidationPath=a},function(e,t,n){"use strict";function r(e){a=e}function i(e){s=e}var o=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();Object.defineProperty(t,"__esModule",{value:!0});var a,s,u=n(15),l=n(1),h=n(5),c=n(16);t.setNodeFromJSON=r,t.setMaxNode=i;var p=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype.compare=function(e,t){var n=e.node.getPriority(),r=t.node.getPriority(),i=n.compareTo(r);return 0===i?l.nameCompare(e.name,t.name):i},t.prototype.isDefinedOn=function(e){return!e.getPriority().isEmpty()},t.prototype.indexedValueChanged=function(e,t){return!e.getPriority().equals(t.getPriority())},t.prototype.minPost=function(){return h.NamedNode.MIN},t.prototype.maxPost=function(){return new h.NamedNode(l.MAX_NAME,new c.LeafNode("[PRIORITY-POST]",s))},t.prototype.makePost=function(e,t){var n=a(e);return new h.NamedNode(t,new c.LeafNode("[PRIORITY-POST]",n))},t.prototype.toString=function(){return".priority"},t}(u.Index);t.PriorityIndex=p,t.PRIORITY_INDEX=new p},function(e,t,n){"use strict";var r=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();Object.defineProperty(t,"__esModule",{value:!0});var i,o=n(0),a=n(1),s=n(17),u=n(5),l=n(37),h=n(3),c=n(10),p=n(39),d=n(16),f=n(41),_=function(){function e(e,t,n){this._=e,this.y=t,this.g=n,this.m=null,this.y&&l.validatePriorityNode(this.y),this._.isEmpty()&&o.assert(!this.y||this.y.isEmpty(),"An empty node cannot have a priority")}return Object.defineProperty(e,"EMPTY_NODE",{get:function(){return i||(i=new e(new s.SortedMap(f.NAME_COMPARATOR),null,p.IndexMap.Default))},enumerable:!0,configurable:!0}),e.prototype.isLeafNode=function(){return!1},e.prototype.getPriority=function(){return this.y||i},e.prototype.updatePriority=function(t){return this._.isEmpty()?this:new e(this._,t,this.g)},e.prototype.getImmediateChild=function(e){if(".priority"===e)return this.getPriority();var t=this._.get(e);return null===t?i:t},e.prototype.getChild=function(e){var t=e.getFront();return null===t?this:this.getImmediateChild(t).getChild(e.popFront())},e.prototype.hasChild=function(e){return null!==this._.get(e)},e.prototype.updateImmediateChild=function(t,n){if(o.assert(n,"We should always be passing snapshot nodes"),".priority"===t)return this.updatePriority(n);var r=new u.NamedNode(t,n),a=void 0,s=void 0,l=void 0;return n.isEmpty()?(a=this._.remove(t),s=this.g.removeFromIndexes(r,this._)):(a=this._.insert(t,n),s=this.g.addToIndexes(r,this._)),l=a.isEmpty()?i:this.y,new e(a,l,s)},e.prototype.updateChild=function(e,t){var n=e.getFront();if(null===n)return t;o.assert(".priority"!==e.getFront()||1===e.getLength(),".priority must be the last token in a path");var r=this.getImmediateChild(n).updateChild(e.popFront(),t);return this.updateImmediateChild(n,r)},e.prototype.isEmpty=function(){return this._.isEmpty()},e.prototype.numChildren=function(){return this._.count()},e.prototype.val=function(t){if(this.isEmpty())return null;var n={},r=0,i=0,o=!0;if(this.forEachChild(h.PRIORITY_INDEX,function(a,s){n[a]=s.val(t),r++,o&&e.e.test(a)?i=Math.max(i,+a):o=!1}),!t&&o&&i<2*r){var a=[];for(var s in n)a[s]=n[s];return a}return t&&!this.getPriority().isEmpty()&&(n[".priority"]=this.getPriority().val()),n},e.prototype.hash=function(){if(null===this.m){var e="";this.getPriority().isEmpty()||(e+="priority:"+l.priorityHashText(this.getPriority().val())+":"),this.forEachChild(h.PRIORITY_INDEX,function(t,n){var r=n.hash();""!==r&&(e+=":"+t+":"+r)}),this.m=""===e?"":a.sha1(e)}return this.m},e.prototype.getPredecessorChildName=function(e,t,n){var r=this.C(n);if(r){var i=r.getPredecessorKey(new u.NamedNode(e,t));return i?i.name:null}return this._.getPredecessorKey(e)},e.prototype.getFirstChildName=function(e){var t=this.C(e);if(t){var n=t.minKey();return n&&n.name}return this._.minKey()},e.prototype.getFirstChild=function(e){var t=this.getFirstChildName(e);return t?new u.NamedNode(t,this._.get(t)):null},e.prototype.getLastChildName=function(e){var t=this.C(e);if(t){var n=t.maxKey();return n&&n.name}return this._.maxKey()},e.prototype.getLastChild=function(e){var t=this.getLastChildName(e);return t?new u.NamedNode(t,this._.get(t)):null},e.prototype.forEachChild=function(e,t){var n=this.C(e);return n?n.inorderTraversal(function(e){return t(e.name,e.node)}):this._.inorderTraversal(t)},e.prototype.getIterator=function(e){return this.getIteratorFrom(e.minPost(),e)},e.prototype.getIteratorFrom=function(e,t){var n=this.C(t);if(n)return n.getIteratorFrom(e,function(e){return e});for(var r=this._.getIteratorFrom(e.name,u.NamedNode.Wrap),i=r.peek();null!=i&&t.compare(i,e)<0;)r.getNext(),i=r.peek();return r},e.prototype.getReverseIterator=function(e){return this.getReverseIteratorFrom(e.maxPost(),e)},e.prototype.getReverseIteratorFrom=function(e,t){var n=this.C(t);if(n)return n.getReverseIteratorFrom(e,function(e){return e});for(var r=this._.getReverseIteratorFrom(e.name,u.NamedNode.Wrap),i=r.peek();null!=i&&t.compare(i,e)>0;)r.getNext(),i=r.peek();return r},e.prototype.compareTo=function(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===t.MAX_NODE?-1:0},e.prototype.withIndex=function(t){if(t===c.KEY_INDEX||this.g.hasIndex(t))return this;var n=this.g.addIndex(t,this._);return new e(this._,this.y,n)},e.prototype.isIndexed=function(e){return e===c.KEY_INDEX||this.g.hasIndex(e)},e.prototype.equals=function(e){if(e===this)return!0;if(e.isLeafNode())return!1;var t=e;if(this.getPriority().equals(t.getPriority())){if(this._.count()===t._.count()){for(var n=this.getIterator(h.PRIORITY_INDEX),r=t.getIterator(h.PRIORITY_INDEX),i=n.getNext(),o=r.getNext();i&&o;){if(i.name!==o.name||!i.node.equals(o.node))return!1;i=n.getNext(),o=r.getNext()}return null===i&&null===o}return!1}return!1},e.prototype.C=function(e){return e===c.KEY_INDEX?null:this.g.get(""+e)},e.e=/^(0|[1-9]\d*)$/,e}();t.ChildrenNode=_;var y=function(e){function t(){return e.call(this,new s.SortedMap(f.NAME_COMPARATOR),_.EMPTY_NODE,p.IndexMap.Default)||this}return r(t,e),t.prototype.compareTo=function(e){return e===this?0:1},t.prototype.equals=function(e){return e===this},t.prototype.getPriority=function(){return this},t.prototype.getImmediateChild=function(e){return _.EMPTY_NODE},t.prototype.isEmpty=function(){return!1},t}(_);t.MaxNode=y,t.MAX_NODE=new y,Object.defineProperties(u.NamedNode,{MIN:{value:new u.NamedNode(a.MIN_NAME,_.EMPTY_NODE)},MAX:{value:new u.NamedNode(a.MAX_NAME,t.MAX_NODE)}}),c.KeyIndex.__EMPTY_NODE=_.EMPTY_NODE,d.LeafNode.__childrenNodeConstructor=_,l.setMaxNode(t.MAX_NODE),h.setMaxNode(t.MAX_NODE)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e,t){this.name=e,this.node=t}return e.Wrap=function(t,n){return new e(t,n)},e}();t.NamedNode=r},,function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(2),i=n(0),o=n(1),a=n(0),s=n(0);t.N=/[\[\].#$\/\u0000-\u001F\u007F]/,t.P=/[\[\].#$\u0000-\u001F\u007F]/,t.S=10485760,t.isValidKey=function(e){return"string"==typeof e&&0!==e.length&&!t.N.test(e)},t.isValidPathString=function(e){return"string"==typeof e&&0!==e.length&&!t.P.test(e)},t.isValidRootPathString=function(e){return e&&(e=e.replace(/^\/*\.info(\/|$)/,"/")),t.isValidPathString(e)},t.isValidPriority=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!o.isInvalidJSONNumber(e)||e&&"object"==typeof e&&i.contains(e,".sv")},t.validateFirebaseDataArg=function(e,n,r,i,o){o&&void 0===r||t.validateFirebaseData(a.errorPrefix(e,n,o),r,i)},t.validateFirebaseData=function(e,n,a){var u=a instanceof r.Path?new r.ValidationPath(a,e):a;if(void 0===n)throw Error(e+"contains undefined "+u.toErrorString());if("function"==typeof n)throw Error(e+"contains a function "+u.toErrorString()+" with contents = "+n);if(o.isInvalidJSONNumber(n))throw Error(e+"contains "+n+" "+u.toErrorString());if("string"==typeof n&&n.length>t.S/3&&s.stringLength(n)>t.S)throw Error(e+"contains a string greater than "+t.S+" utf8 bytes "+u.toErrorString()+" ('"+n.substring(0,50)+"...')");if(n&&"object"==typeof n){var l=!1,h=!1;if(i.forEach(n,function(n,r){if(".value"===n)l=!0;else if(".priority"!==n&&".sv"!==n&&(h=!0,!t.isValidKey(n)))throw Error(e+" contains an invalid key ("+n+") "+u.toErrorString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');u.push(n),t.validateFirebaseData(e,r,u),u.pop()}),l&&h)throw Error(e+' contains ".value" child '+u.toErrorString()+" in addition to actual children.")}},t.validateFirebaseMergePaths=function(e,n){var i,o;for(i=0;i=0,"Unknown leaf type: "+n),i.assert(a>=0,"Unknown leaf type: "+r),o===a?"object"===r?0:this.T0},e.prototype.peek=function(){if(0===this.O.length)return null;var e=this.O[this.O.length-1];return this.R?this.R(e.key,e.value):{key:e.key,value:e.value}},e}();t.SortedMapIterator=r;var i=function(){function e(t,n,r,i,o){this.key=t,this.value=n,this.color=null!=r?r:e.RED,this.left=null!=i?i:a.EMPTY_NODE,this.right=null!=o?o:a.EMPTY_NODE}return e.prototype.copy=function(t,n,r,i,o){return new e(null!=t?t:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=i?i:this.left,null!=o?o:this.right)},e.prototype.count=function(){return this.left.count()+1+this.right.count()},e.prototype.isEmpty=function(){return!1},e.prototype.inorderTraversal=function(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)},e.prototype.reverseTraversal=function(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)},e.prototype.A=function(){return this.left.isEmpty()?this:this.left.A()},e.prototype.minKey=function(){return this.A().key},e.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},e.prototype.insert=function(e,t,n){var r,i;return i=this,r=n(e,i.key),i=r<0?i.copy(null,null,null,i.left.insert(e,t,n),null):0===r?i.copy(null,t,null,null,null):i.copy(null,null,null,null,i.right.insert(e,t,n)),i.D()},e.prototype.M=function(){if(this.left.isEmpty())return a.EMPTY_NODE;var e=this;return e.left.L()||e.left.left.L()||(e=e.F()),e=e.copy(null,null,null,e.left.M(),null),e.D()},e.prototype.remove=function(e,t){var n,r;if(n=this,t(e,n.key)<0)n.left.isEmpty()||n.left.L()||n.left.left.L()||(n=n.F()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.L()&&(n=n.x()),n.right.isEmpty()||n.right.L()||n.right.left.L()||(n=n.k()),0===t(e,n.key)){if(n.right.isEmpty())return a.EMPTY_NODE;r=n.right.A(),n=n.copy(r.key,r.value,null,null,n.right.M())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.D()},e.prototype.L=function(){return this.color},e.prototype.D=function(){var e=this;return e.right.L()&&!e.left.L()&&(e=e.W()),e.left.L()&&e.left.left.L()&&(e=e.x()),e.left.L()&&e.right.L()&&(e=e.j()),e},e.prototype.F=function(){var e=this.j();return e.right.left.L()&&(e=e.copy(null,null,null,null,e.right.x()),e=e.W(),e=e.j()),e},e.prototype.k=function(){var e=this.j();return e.left.left.L()&&(e=e.x(),e=e.j()),e},e.prototype.W=function(){var t=this.copy(null,null,e.RED,null,this.right.left);return this.right.copy(null,null,this.color,t,null)},e.prototype.x=function(){var t=this.copy(null,null,e.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,t)},e.prototype.j=function(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)},e.prototype.V=function(){var e=this.Q();return Math.pow(2,e)<=this.count()+1},e.prototype.Q=function(){var e;if(this.L()&&this.left.L())throw Error("Red node has red child("+this.key+","+this.value+")");if(this.right.L())throw Error("Right child of ("+this.key+","+this.value+") is red");if((e=this.left.Q())!==this.right.Q())throw Error("Black depths differ");return e+(this.L()?0:1)},e.RED=!0,e.BLACK=!1,e}();t.LLRBNode=i;var o=function(){function e(){}return e.prototype.copy=function(e,t,n,r,i){return this},e.prototype.insert=function(e,t,n){return new i(e,t,null)},e.prototype.remove=function(e,t){return this},e.prototype.count=function(){return 0},e.prototype.isEmpty=function(){return!0},e.prototype.inorderTraversal=function(e){return!1},e.prototype.reverseTraversal=function(e){return!1},e.prototype.minKey=function(){return null},e.prototype.maxKey=function(){return null},e.prototype.Q=function(){return 0},e.prototype.L=function(){return!1},e}();t.LLRBEmptyNode=o;var a=function(){function e(t,n){void 0===n&&(n=e.EMPTY_NODE),this.U=t,this.B=n}return e.prototype.insert=function(t,n){return new e(this.U,this.B.insert(t,n,this.U).copy(null,null,i.BLACK,null,null))},e.prototype.remove=function(t){return new e(this.U,this.B.remove(t,this.U).copy(null,null,i.BLACK,null,null))},e.prototype.get=function(e){for(var t,n=this.B;!n.isEmpty();){if(0===(t=this.U(e,n.key)))return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null},e.prototype.getPredecessorKey=function(e){for(var t,n=this.B,r=null;!n.isEmpty();){if(0===(t=this.U(e,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:t>0&&(r=n,n=n.right)}throw Error("Attempted to find predecessor key for a nonexistent key. What gives?")},e.prototype.isEmpty=function(){return this.B.isEmpty()},e.prototype.count=function(){return this.B.count()},e.prototype.minKey=function(){return this.B.minKey()},e.prototype.maxKey=function(){return this.B.maxKey()},e.prototype.inorderTraversal=function(e){return this.B.inorderTraversal(e)},e.prototype.reverseTraversal=function(e){return this.B.reverseTraversal(e)},e.prototype.getIterator=function(e){return new r(this.B,null,this.U,!1,e)},e.prototype.getIteratorFrom=function(e,t){return new r(this.B,e,this.U,!1,t)},e.prototype.getReverseIteratorFrom=function(e,t){return new r(this.B,e,this.U,!0,t)},e.prototype.getReverseIterator=function(e){return new r(this.B,null,this.U,!0,e)},e.EMPTY_NODE=new o,e}();t.SortedMap=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(43),i=n(11),o=n(2),a=n(44),s=n(86),u=n(97),l=n(0),h=n(1),c=n(0),p=n(98),d=n(25),f=n(100),_=n(49),y=n(101),v=n(50),g=n(106),m=n(32),C=function(){function e(e,t,n){var r=this;this.H=e,this.app=n,this.dataUpdateCount=0,this.G=null,this.K=new y.EventQueue,this.Y=1,this.X=null,this.z=new a.SparseSnapshotTree,this.J=null;var i=new p.AuthTokenProvider(n);if(this.$=d.StatsManager.getCollection(e),t||h.beingCrawled())this.Z=new g.ReadonlyRestClient(this.H,this.ee.bind(this),i),setTimeout(this.te.bind(this,!0),0);else{var o=n.options.databaseAuthVariableOverride;if(void 0!==o&&null!==o){if("object"!=typeof o)throw Error("Only objects are supported for option databaseAuthVariableOverride");try{l.stringify(o)}catch(e){throw Error("Invalid authOverride provided: "+e)}}this.J=new v.PersistentConnection(this.H,this.ee.bind(this),this.te.bind(this),this.ne.bind(this),i,o),this.Z=this.J}i.addTokenChangeListener(function(e){r.Z.refreshAuthToken(e)}),this.re=d.StatsManager.getOrCreateReporter(e,function(){return new f.StatsReporter(r.$,r.Z)}),this.ie(),this.oe=new u.SnapshotHolder,this.ae=new s.SyncTree({startListening:function(e,t,n,i){var o=[],a=r.oe.getNode(e.path);return a.isEmpty()||(o=r.ae.applyServerOverwrite(e.path,a),setTimeout(function(){i("ok")},0)),o},stopListening:function(){}}),this.se("connected",!1),this.ue=new s.SyncTree({startListening:function(e,t,n,i){return r.Z.listen(e,n,t,function(t,n){var o=i(t,n);r.K.raiseEventsForChangedPath(e.path,o)}),[]},stopListening:function(e,t){r.Z.unlisten(e,t)}})}return e.prototype.toString=function(){return(this.H.secure?"https://":"http://")+this.H.host},e.prototype.name=function(){return this.H.namespace},e.prototype.serverTime=function(){var e=this.oe.getNode(new o.Path(".info/serverTimeOffset")),t=e.val()||0;return(new Date).getTime()+t},e.prototype.generateServerValues=function(){return r.generateWithValues({timestamp:this.serverTime()})},e.prototype.ee=function(e,t,n,r){this.dataUpdateCount++;var a=new o.Path(e);t=this.X?this.X(e,t):t;var s=[];if(r)if(n){var u=c.map(t,function(e){return i.nodeFromJSON(e)});s=this.ue.applyTaggedQueryMerge(a,u,r)}else{var l=i.nodeFromJSON(t);s=this.ue.applyTaggedQueryOverwrite(a,l,r)}else if(n){var h=c.map(t,function(e){return i.nodeFromJSON(e)});s=this.ue.applyServerMerge(a,h)}else{var p=i.nodeFromJSON(t);s=this.ue.applyServerOverwrite(a,p)}var d=a;s.length>0&&(d=this.le(a)),this.K.raiseEventsForChangedPath(d,s)},e.prototype.he=function(e){this.X=e},e.prototype.te=function(e){this.se("connected",e),!1===e&&this.ce()},e.prototype.ne=function(e){var t=this;h.each(e,function(e,n){t.se(n,e)})},e.prototype.se=function(e,t){var n=new o.Path("/.info/"+e),r=i.nodeFromJSON(t);this.oe.updateSnapshot(n,r);var a=this.ae.applyServerOverwrite(n,r);this.K.raiseEventsForChangedPath(n,a)},e.prototype.pe=function(){return this.Y++},e.prototype.setWithPriority=function(e,t,n,o){var a=this;this.de("set",{path:""+e,value:t,priority:n});var s=this.generateServerValues(),u=i.nodeFromJSON(t,n),l=r.resolveDeferredValueSnapshot(u,s),c=this.pe(),p=this.ue.applyUserOverwrite(e,l,c,!0);this.K.queueEvents(p),this.Z.put(""+e,u.val(!0),function(t,n){var r="ok"===t;r||h.warn("set at "+e+" failed: "+t);var i=a.ue.ackUserWrite(c,!r);a.K.raiseEventsForChangedPath(e,i),a.callOnCompleteCallback(o,t,n)});var d=this.fe(e);this.le(d),this.K.raiseEventsForChangedPath(d,[])},e.prototype.update=function(e,t,n){var o=this;this.de("update",{path:""+e,value:t});var a=!0,s=this.generateServerValues(),u={};if(c.forEach(t,function(e,t){a=!1;var n=i.nodeFromJSON(t);u[e]=r.resolveDeferredValueSnapshot(n,s)}),a)h.log("update() called with empty data. Don't do anything."),this.callOnCompleteCallback(n,"ok");else{var l=this.pe(),p=this.ue.applyUserMerge(e,u,l);this.K.queueEvents(p),this.Z.merge(""+e,t,function(t,r){var i="ok"===t;i||h.warn("update at "+e+" failed: "+t);var a=o.ue.ackUserWrite(l,!i),s=a.length>0?o.le(e):e;o.K.raiseEventsForChangedPath(s,a),o.callOnCompleteCallback(n,t,r)}),c.forEach(t,function(t){var n=o.fe(e.child(t));o.le(n)}),this.K.raiseEventsForChangedPath(e,[])}},e.prototype.ce=function(){var e=this;this.de("onDisconnectEvents");var t=this.generateServerValues(),n=r.resolveDeferredValueTree(this.z,t),i=[];n.forEachTree(o.Path.Empty,function(t,n){i=i.concat(e.ue.applyServerOverwrite(t,n));var r=e.fe(t);e.le(r)}),this.z=new a.SparseSnapshotTree,this.K.raiseEventsForChangedPath(o.Path.Empty,i)},e.prototype.onDisconnectCancel=function(e,t){var n=this;this.Z.onDisconnectCancel(""+e,function(r,i){"ok"===r&&n.z.forget(e),n.callOnCompleteCallback(t,r,i)})},e.prototype.onDisconnectSet=function(e,t,n){var r=this,o=i.nodeFromJSON(t);this.Z.onDisconnectPut(""+e,o.val(!0),function(t,i){"ok"===t&&r.z.remember(e,o),r.callOnCompleteCallback(n,t,i)})},e.prototype.onDisconnectSetWithPriority=function(e,t,n,r){var o=this,a=i.nodeFromJSON(t,n);this.Z.onDisconnectPut(""+e,a.val(!0),function(t,n){"ok"===t&&o.z.remember(e,a),o.callOnCompleteCallback(r,t,n)})},e.prototype.onDisconnectUpdate=function(e,t,n){var r=this;if(c.isEmpty(t))return h.log("onDisconnect().update() called with empty data. Don't do anything."),void this.callOnCompleteCallback(n,"ok");this.Z.onDisconnectMerge(""+e,t,function(o,a){"ok"===o&&c.forEach(t,function(t,n){var o=i.nodeFromJSON(n);r.z.remember(e.child(t),o)}),r.callOnCompleteCallback(n,o,a)})},e.prototype.addEventCallbackForQuery=function(e,t){var n;n=".info"===e.path.getFront()?this.ae.addEventRegistration(e,t):this.ue.addEventRegistration(e,t),this.K.raiseEventsAtPath(e.path,n)},e.prototype.removeEventCallbackForQuery=function(e,t){var n;n=".info"===e.path.getFront()?this.ae.removeEventRegistration(e,t):this.ue.removeEventRegistration(e,t),this.K.raiseEventsAtPath(e.path,n)},e.prototype.interrupt=function(){this.J&&this.J.interrupt("repo_interrupt")},e.prototype.resume=function(){this.J&&this.J.resume("repo_interrupt")},e.prototype.stats=function(e){if(void 0===e&&(e=!1),"undefined"!=typeof console){var t;e?(this.G||(this.G=new _.StatsListener(this.$)),t=this.G.get()):t=this.$.get();var n=Object.keys(t).reduce(function(e,t){return Math.max(t.length,e)},0);c.forEach(t,function(e,t){for(var r=e.length;r0){var i=n[r];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch(e){}t+="/"+i}return t}Object.defineProperty(t,"__esModule",{value:!0});var i=n(2),o=n(34),a=n(1);t.parseRepoInfo=function(e){var n=t.parseURL(e),r=n.subdomain;"firebase"===n.domain&&a.fatal(n.host+" is no longer supported. Please use .firebaseio.com instead"),r&&"undefined"!=r||a.fatal("Cannot parse Firebase url. Please use https://.firebaseio.com"),n.secure||a.warnIfPageIsSecure();var s="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new o.RepoInfo(n.host,n.secure,r,s),path:new i.Path(n.pathString)}},t.parseURL=function(e){var t="",n="",i="",o="",a=!0,s="https",u=443;if("string"==typeof e){var l=e.indexOf("//");l>=0&&(s=e.substring(0,l-1),e=e.substring(l+2));var h=e.indexOf("/");-1===h&&(h=e.length),t=e.substring(0,h),o=r(e.substring(h));var c=t.split(".");3===c.length?(n=c[1],i=c[0].toLowerCase()):2===c.length&&(n=c[0]),(l=t.indexOf(":"))>=0&&(a="https"===s||"wss"===s,u=parseInt(t.substring(l+1),10))}return{host:t,port:u,domain:n,subdomain:i,secure:a,scheme:s,pathString:o}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(0),o=n(13),a=n(14),s=function(){function e(e,t,n,r,i){void 0===i&&(i=""),this.secure=t,this.namespace=n,this.webSocketOnly=r,this.persistenceKey=i,this.host=e.toLowerCase(),this.domain=this.host.substr(this.host.indexOf(".")+1),this.internalHost=o.PersistentStorage.get("host:"+e)||this.host}return e.prototype.needsQueryParam=function(){return this.host!==this.internalHost},e.prototype.isCacheableHost=function(){return"s-"===this.internalHost.substr(0,2)},e.prototype.isDemoHost=function(){return"firebaseio-demo.com"===this.domain},e.prototype.isCustomHost=function(){return"firebaseio.com"!==this.domain&&"firebaseio-demo.com"!==this.domain},e.prototype.updateHost=function(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&o.PersistentStorage.set("host:"+this.host,this.internalHost))},e.prototype.connectionURL=function(e,t){r.assert("string"==typeof e,"typeof type must == string"),r.assert("object"==typeof t,"typeof params must == object");var n;if(e===a.WEBSOCKET)n=(this.secure?"wss://":"ws://")+this.internalHost+"/.ws?";else{if(e!==a.LONG_POLLING)throw Error("Unknown connection type: "+e);n=(this.secure?"https://":"http://")+this.internalHost+"/.lp?"}this.needsQueryParam()&&(t.ns=this.namespace);var o=[];return i.forEach(t,function(e,t){o.push(e+"="+t)}),n+o.join("&")},e.prototype.toString=function(){var e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e},e.prototype.toURLString=function(){return(this.secure?"https://":"http://")+this.host},e}();t.RepoInfo=s},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(7),o=n(1),a=n(0),s=function(){function e(e,t){this.Ie=e,this.Oe=t}return e.prototype.cancel=function(e){r.validateArgCount("OnDisconnect.cancel",0,1,arguments.length),r.validateCallback("OnDisconnect.cancel",1,e,!0);var t=new a.Deferred;return this.Ie.onDisconnectCancel(this.Oe,t.wrapCallback(e)),t.promise},e.prototype.remove=function(e){r.validateArgCount("OnDisconnect.remove",0,1,arguments.length),i.validateWritablePath("OnDisconnect.remove",this.Oe),r.validateCallback("OnDisconnect.remove",1,e,!0);var t=new a.Deferred;return this.Ie.onDisconnectSet(this.Oe,null,t.wrapCallback(e)),t.promise},e.prototype.set=function(e,t){r.validateArgCount("OnDisconnect.set",1,2,arguments.length),i.validateWritablePath("OnDisconnect.set",this.Oe),i.validateFirebaseDataArg("OnDisconnect.set",1,e,this.Oe,!1),r.validateCallback("OnDisconnect.set",2,t,!0);var n=new a.Deferred;return this.Ie.onDisconnectSet(this.Oe,e,n.wrapCallback(t)),n.promise},e.prototype.setWithPriority=function(e,t,n){r.validateArgCount("OnDisconnect.setWithPriority",2,3,arguments.length),i.validateWritablePath("OnDisconnect.setWithPriority",this.Oe),i.validateFirebaseDataArg("OnDisconnect.setWithPriority",1,e,this.Oe,!1),i.validatePriority("OnDisconnect.setWithPriority",2,t,!1),r.validateCallback("OnDisconnect.setWithPriority",3,n,!0);var o=new a.Deferred;return this.Ie.onDisconnectSetWithPriority(this.Oe,e,t,o.wrapCallback(n)),o.promise},e.prototype.update=function(e,t){if(r.validateArgCount("OnDisconnect.update",1,2,arguments.length),i.validateWritablePath("OnDisconnect.update",this.Oe),Array.isArray(e)){for(var n={},s=0;s3e4&&(this.nt=v),this._t=null}}else this.de("Window isn't visible. Delaying reconnect."),this.nt=this.rt,this.ft=(new Date).getTime();var t=(new Date).getTime()-this.ft,n=Math.max(0,this.nt-t);n=Math.random()*n,this.de("Trying to reconnect in "+n+"ms"),this.yt(n),this.nt=Math.min(this.rt,1.3*this.nt)}this.te(!1)},t.prototype.Ft=function(){if(this.Wt()){this.de("Making a connection attempt"),this.ft=(new Date).getTime(),this._t=null;var e=this.wt.bind(this),n=this.At.bind(this),r=this.xt.bind(this),i=this.id+":"+t.jt++,o=this,a=this.lastSessionId,l=!1,h=null,c=function(){h?h.close():(l=!0,r())},p=function(e){s.assert(h,"sendRequest call when we're not connected not allowed."),h.sendRequest(e)};this.lt={close:c,sendRequest:p};var _=this.ct;this.ct=!1,this.Ke.getToken(_).then(function(t){l?u.log("getToken() completed but was canceled"):(u.log("getToken() completed. Creating connection."),o.ht=t&&t.accessToken,h=new d.Connection(i,o.H,e,n,r,function(e){u.warn(e+" ("+o.H+")"),o.interrupt("server_kill")},a))}).then(null,function(e){o.de("Failed to get token: "+e),l||(f.CONSTANTS.NODE_ADMIN&&u.warn(e),c())})}},t.prototype.interrupt=function(e){u.log("Interrupting connection for reason: "+e),this.ze[e]=!0,this.lt?this.lt.close():(this.ot&&(clearTimeout(this.ot),this.ot=null),this.tt&&this.xt())},t.prototype.resume=function(e){u.log("Resuming connection for reason: "+e),delete this.ze[e],o.isEmpty(this.ze)&&(this.nt=v,this.lt||this.yt(0))},t.prototype.Dt=function(e){var t=e-(new Date).getTime();this.ne({serverTimeOffset:t})},t.prototype.kt=function(){for(var e=0;e=3&&(this.nt=3e4,this.Ke.notifyForInvalidToken())},t.prototype.Ot=function(e){this.it?this.it(e):"msg"in e&&"undefined"!=typeof console&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))},t.prototype.Lt=function(){var e=this;this.tryAuth(),o.forEach(this.Je,function(t,n){o.forEach(n,function(t,n){e.mt(n)})});for(var t=0;t0,"Requires a non-empty array")}return e.prototype.trigger=function(e){for(var t=[],n=1;n0&&(this.rn=r.setTimeoutNonBlocking(function(){e.rn=null,e.nn||(e.Yt&&e.Yt.bytesReceived>102400?(e.de("Connection exceeded healthy timeout but has received "+e.Yt.bytesReceived+" bytes. Marking connection healthy."),e.nn=!0,e.Yt.markConnectionHealthy()):e.Yt&&e.Yt.bytesSent>10240?e.de("Connection exceeded healthy timeout but has sent "+e.Yt.bytesSent+" bytes. Leaving connection alive."):(e.de("Closing unhealthy connection after timeout."),e.close()))},Math.floor(o)))},e.prototype.Xt=function(){return"c:"+this.id+":"+this.connectionCount++},e.prototype.$t=function(e){var t=this;return function(n){e===t.Yt?t.in(n):e===t.tn?(t.de("Secondary connection lost."),t.an()):t.de("closing an old connection")}},e.prototype.Jt=function(e){var t=this;return function(n){2!=t.Ht&&(e===t.en?t.sn(n):e===t.tn?t.un(n):t.de("message on old connection"))}},e.prototype.sendRequest=function(e){var t={t:"d",d:e};this.ln(t)},e.prototype.tryCleanupConnection=function(){this.Zt===this.tn&&this.en===this.tn&&(this.de("cleaning up and promoting a connection: "+this.tn.connId),this.Yt=this.tn,this.tn=null)},e.prototype.hn=function(e){if("t"in e){var t=e.t;"a"===t?this.cn():"r"===t?(this.de("Got a reset on secondary, closing it"),this.tn.close(),this.Zt!==this.tn&&this.en!==this.tn||this.close()):"o"===t&&(this.de("got pong on secondary."),this.pn--,this.cn())}},e.prototype.un=function(e){var t=r.requireKey("t",e),n=r.requireKey("d",e);if("c"==t)this.hn(n);else{if("d"!=t)throw Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}},e.prototype.cn=function(){this.pn<=0?(this.de("Secondary connection is healthy."),this.nn=!0,this.tn.markConnectionHealthy(),this.dn()):(this.de("sending ping on secondary."),this.tn.send({t:"c",d:{t:"p",d:{}}}))},e.prototype.dn=function(){this.tn.start(),this.de("sending client ack on secondary"),this.tn.send({t:"c",d:{t:"a",d:{}}}),this.de("Ending transmission on primary"),this.Yt.send({t:"c",d:{t:"n",d:{}}}),this.Zt=this.tn,this.tryCleanupConnection()},e.prototype.sn=function(e){var t=r.requireKey("t",e),n=r.requireKey("d",e);"c"==t?this.fn(n):"d"==t&&this.wt(n)},e.prototype.wt=function(e){this._n(),this.Ut(e)},e.prototype._n=function(){this.nn||--this.zt<=0&&(this.de("Primary connection is healthy."),this.nn=!0,this.Yt.markConnectionHealthy())},e.prototype.fn=function(e){var t=r.requireKey("t",e);if("d"in e){var n=e.d;if("h"===t)this.yn(n);else if("n"===t){this.de("recvd end transmission on primary"),this.en=this.tn;for(var i=0;idocument.domain="'+document.domain+'";<\/script>');var h=""+u+"";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(h),this.myIFrame.doc.close()}catch(e){r.log("frame writing exception"),e.stack&&r.log(e.stack),r.log(e)}}}return e.Dn=function(){var e=document.createElement("iframe");if(e.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(e);try{e.contentWindow.document||r.log("No IE domain setting required")}catch(n){var t=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+t+"';document.close();})())"}return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e},e.prototype.close=function(){var n=this;if(this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.innerHTML="",setTimeout(function(){null!==n.myIFrame&&(document.body.removeChild(n.myIFrame),n.myIFrame=null)},Math.floor(0))),l.isNodeSdk()&&this.myID){var r={};r[t.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM]="t",r[t.FIREBASE_LONGPOLL_ID_PARAM]=this.myID,r[t.FIREBASE_LONGPOLL_PW_PARAM]=this.myPW;var i=this.urlFn(r);e.nodeRestRequest(i)}var o=this.onDisconnect;o&&(this.onDisconnect=null,o())},e.prototype.startLongPoll=function(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.Mn(););},e.prototype.Mn=function(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.count()<(this.pendingSegs.length>0?2:1)){this.currentSerial++;var e={};e[t.FIREBASE_LONGPOLL_ID_PARAM]=this.myID,e[t.FIREBASE_LONGPOLL_PW_PARAM]=this.myPW,e[t.FIREBASE_LONGPOLL_SERIAL_PARAM]=this.currentSerial;for(var n=this.urlFn(e),r="",i=0;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+30+r.length<=1870;){var o=this.pendingSegs.shift();r=r+"&"+t.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM+i+"="+o.seg+"&"+t.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET+i+"="+o.ts+"&"+t.FIREBASE_LONGPOLL_DATA_PARAM+i+"="+o.d,i++}return n+=r,this.Ln(n,this.currentSerial),!0}return!1},e.prototype.enqueueSegment=function(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.Mn()},e.prototype.Ln=function(e,t){var n=this;this.outstandingRequests.add(t,1);var r=function(){n.outstandingRequests.remove(t),n.Mn()},i=setTimeout(r,Math.floor(25e3)),o=function(){clearTimeout(i),r()};this.addTag(e,o)},e.prototype.addTag=function(e,t){var n=this;l.isNodeSdk()?this.doNodeLongPoll(e,t):setTimeout(function(){try{if(!n.sendNewPolls)return;var i=n.myIFrame.doc.createElement("script");i.type="text/javascript",i.async=!0,i.src=e,i.onload=i.onreadystatechange=function(){var e=i.readyState;e&&"loaded"!==e&&"complete"!==e||(i.onload=i.onreadystatechange=null,i.parentNode&&i.parentNode.removeChild(i),t())},i.onerror=function(){r.log("Long-poll script failed to load: "+e),n.sendNewPolls=!1,n.close()},n.myIFrame.doc.body.appendChild(i)}catch(e){}},Math.floor(1))},e}();t.FirebaseIFrameScriptHolder=c},function(e,t,n){"use strict";(function(e){function r(e){d=e}Object.defineProperty(t,"__esModule",{value:!0});var i=n(6),o=n(0),a=n(1),s=n(25),u=n(14),l=n(0),h=n(13),c=n(0),p=n(0),d=null;"undefined"!=typeof MozWebSocket?d=MozWebSocket:"undefined"!=typeof WebSocket&&(d=WebSocket),t.setWebSocketImpl=r;var f=function(){function t(e,n,r,i){this.connId=e,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.de=a.logWrapper(this.connId),this.$=s.StatsManager.getCollection(n),this.connURL=t.Fn(n,r,i)}return t.Fn=function(e,t,n){var r={};return r[u.VERSION_PARAM]=u.PROTOCOL_VERSION,!p.isNodeSdk()&&"undefined"!=typeof location&&location.href&&-1!==location.href.indexOf(u.FORGE_DOMAIN)&&(r[u.REFERER_PARAM]=u.FORGE_REF),t&&(r[u.TRANSPORT_SESSION_PARAM]=t),n&&(r[u.LAST_SESSION_PARAM]=n),e.connectionURL(u.WEBSOCKET,r)},t.prototype.open=function(t,n){var r=this;this.onDisconnect=n,this.onMessage=t,this.de("Websocket connecting to "+this.connURL),this.bn=!1,h.PersistentStorage.set("previous_websocket_failure",!0);try{if(p.isNodeSdk()){var o=l.CONSTANTS.NODE_ADMIN?"AdminNode":"Node",a={headers:{"User-Agent":"Firebase/"+u.PROTOCOL_VERSION+"/"+i.default.SDK_VERSION+"/"+e.platform+"/"+o}},s=e.env,c=0==this.connURL.indexOf("wss://")?s.HTTPS_PROXY||s.https_proxy:s.HTTP_PROXY||s.http_proxy;c&&(a.proxy={origin:c}),this.mySock=new d(this.connURL,[],a)}else this.mySock=new d(this.connURL)}catch(e){this.de("Error instantiating WebSocket.");var f=e.message||e.data;return f&&this.de(f),void this.wn()}this.mySock.onopen=function(){r.de("Websocket connected."),r.bn=!0},this.mySock.onclose=function(){r.de("Websocket connection was disconnected."),r.mySock=null,r.wn()},this.mySock.onmessage=function(e){r.handleIncomingFrame(e)},this.mySock.onerror=function(e){r.de("WebSocket error. Closing connection.");var t=e.message||e.data;t&&r.de(t),r.wn()}},t.prototype.start=function(){},t.forceDisallow=function(){t.On=!0},t.isAvailable=function(){var e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){var n=/Android ([0-9]{0,}\.[0-9]{0,})/,r=navigator.userAgent.match(n);r&&r.length>1&&parseFloat(r[1])<4.4&&(e=!0)}return!e&&null!==d&&!t.On},t.previouslyFailed=function(){return h.PersistentStorage.isInMemoryStorage||!0===h.PersistentStorage.get("previous_websocket_failure")},t.prototype.markConnectionHealthy=function(){h.PersistentStorage.remove("previous_websocket_failure")},t.prototype.xn=function(e){if(this.frames.push(e),this.frames.length==this.totalFrames){var t=this.frames.join("");this.frames=null;var n=c.jsonEval(t);this.onMessage(n)}},t.prototype.kn=function(e){this.totalFrames=e,this.frames=[]},t.prototype.Wn=function(e){if(o.assert(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=+e;if(!isNaN(t))return this.kn(t),null}return this.kn(1),e},t.prototype.handleIncomingFrame=function(e){if(null!==this.mySock){var t=e.data;if(this.bytesReceived+=t.length,this.$.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.xn(t);else{var n=this.Wn(t);null!==n&&this.xn(n)}}},t.prototype.send=function(e){this.resetKeepAlive();var t=c.stringify(e);this.bytesSent+=t.length,this.$.incrementCounter("bytes_sent",t.length);var n=a.splitStringBySize(t,16384);n.length>1&&this.jn(n.length+"");for(var r=0;r=0;a--)s[a]=e.charAt(i%64),i=Math.floor(i/64);r.assert(0===i,"Cannot push at time == 0");var u=s.join("");if(o){for(a=11;a>=0&&63===n[a];a--)n[a]=0;n[a]++}else for(a=0;a<12;a++)n[a]=Math.floor(64*Math.random());for(a=0;a<12;a++)u+=e.charAt(n[a]);return r.assert(20===u.length,"nextPushId: Length should be 20."),u}}()},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(22),i=n(85),o=n(0),a=n(0),s=function(){function e(e,t,n){this.Xn=e,this.zn=t,this.Jn=n}return e.prototype.respondsTo=function(e){return"value"===e},e.prototype.createEvent=function(e,t){var n=t.getQueryParams().getIndex();return new i.DataEvent("value",this,new r.DataSnapshot(e.snapshotNode,t.getRef(),n))},e.prototype.getEventRunner=function(e){var t=this.Jn;if("cancel"===e.getEventType()){a.assert(this.zn,"Raising a cancel event on a listener with no cancel callback");var n=this.zn;return function(){n.call(t,e.error)}}var r=this.Xn;return function(){r.call(t,e.snapshot)}},e.prototype.createCancelEvent=function(e,t){return this.zn?new i.CancelEvent(this,e,t):null},e.prototype.matches=function(t){return t instanceof e&&(!t.Xn||!this.Xn||t.Xn===this.Xn&&t.Jn===this.Jn)},e.prototype.hasAnyCallback=function(){return null!==this.Xn},e}();t.ValueEventRegistration=s;var u=function(){function e(e,t,n){this.$n=e,this.zn=t,this.Jn=n}return e.prototype.respondsTo=function(e){var t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,o.contains(this.$n,t)},e.prototype.createCancelEvent=function(e,t){return this.zn?new i.CancelEvent(this,e,t):null},e.prototype.createEvent=function(e,t){a.assert(null!=e.childName,"Child events should have a childName.");var n=t.getRef().child(e.childName),o=t.getQueryParams().getIndex();return new i.DataEvent(e.type,this,new r.DataSnapshot(e.snapshotNode,n,o),e.prevName)},e.prototype.getEventRunner=function(e){var t=this.Jn;if("cancel"===e.getEventType()){a.assert(this.zn,"Raising a cancel event on a listener with no cancel callback");var n=this.zn;return function(){n.call(t,e.error)}}var r=this.$n[e.eventType];return function(){r.call(t,e.snapshot,e.prevName)}},e.prototype.matches=function(t){if(t instanceof e){if(!this.$n||!t.$n)return!0;if(this.Jn===t.Jn){var n=o.getCount(t.$n);if(n===o.getCount(this.$n)){if(1===n){var r=o.getAnyKey(t.$n),i=o.getAnyKey(this.$n);return!(i!==r||t.$n[r]&&this.$n[i]&&t.$n[r]!==this.$n[i])}return o.every(this.$n,function(e,n){return t.$n[e]===n})}}}return!1},e.prototype.hasAnyCallback=function(){return null!==this.$n},e}();t.ChildEventRegistration=u},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=function(){function e(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}return e.prototype.getPath=function(){var e=this.snapshot.getRef();return"value"===this.eventType?e.path:e.getParent().path},e.prototype.getEventType=function(){return this.eventType},e.prototype.getEventRunner=function(){return this.eventRegistration.getEventRunner(this)},e.prototype.toString=function(){return this.getPath()+":"+this.eventType+":"+r.stringify(this.snapshot.exportVal())},e}();t.DataEvent=i;var o=function(){function e(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}return e.prototype.getPath=function(){return this.path},e.prototype.getEventType=function(){return"cancel"},e.prototype.getEventRunner=function(){return this.eventRegistration.getEventRunner(this)},e.prototype.toString=function(){return this.path+":cancel"},e}();t.CancelEvent=o},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(1),o=n(87),a=n(4),s=n(0),u=n(23),l=n(88),h=n(89),c=n(8),p=n(46),d=n(2),f=n(47),_=n(95),y=function(){function e(e){this.Zn=e,this.er=u.ImmutableTree.Empty,this.tr=new _.WriteTree,this.nr={},this.rr={}}return e.prototype.applyUserOverwrite=function(e,t,n,r){return this.tr.addOverwrite(e,t,n,r),r?this.ir(new p.Overwrite(c.OperationSource.User,e,t)):[]},e.prototype.applyUserMerge=function(e,t,n){this.tr.addMerge(e,t,n);var r=u.ImmutableTree.fromObject(t);return this.ir(new h.Merge(c.OperationSource.User,e,r))},e.prototype.ackUserWrite=function(e,t){void 0===t&&(t=!1);var n=this.tr.getWrite(e);if(this.tr.removeWrite(e)){var r=u.ImmutableTree.Empty;return null!=n.snap?r=r.set(d.Path.Empty,!0):s.forEach(n.children,function(e,t){r=r.set(new d.Path(e),t)}),this.ir(new o.AckUserWrite(n.path,r,t))}return[]},e.prototype.applyServerOverwrite=function(e,t){return this.ir(new p.Overwrite(c.OperationSource.Server,e,t))},e.prototype.applyServerMerge=function(e,t){var n=u.ImmutableTree.fromObject(t);return this.ir(new h.Merge(c.OperationSource.Server,e,n))},e.prototype.applyListenComplete=function(e){return this.ir(new l.ListenComplete(c.OperationSource.Server,e))},e.prototype.applyTaggedQueryOverwrite=function(t,n,r){var i=this.or(r);if(null!=i){var o=e.ar(i),a=o.path,s=o.queryId,u=d.Path.relativePath(a,t),l=new p.Overwrite(c.OperationSource.forServerTaggedQuery(s),u,n);return this.sr(a,l)}return[]},e.prototype.applyTaggedQueryMerge=function(t,n,r){var i=this.or(r);if(i){var o=e.ar(i),a=o.path,s=o.queryId,l=d.Path.relativePath(a,t),p=u.ImmutableTree.fromObject(n),f=new h.Merge(c.OperationSource.forServerTaggedQuery(s),l,p);return this.sr(a,f)}return[]},e.prototype.applyTaggedListenComplete=function(t,n){var r=this.or(n);if(r){var i=e.ar(r),o=i.path,a=i.queryId,s=d.Path.relativePath(o,t),u=new l.ListenComplete(c.OperationSource.forServerTaggedQuery(a),s);return this.sr(o,u)}return[]},e.prototype.addEventRegistration=function(t,n){var i=t.path,o=null,s=!1;this.er.foreachOnPath(i,function(e,t){var n=d.Path.relativePath(e,i);o=o||t.getCompleteServerCache(n),s=s||t.hasCompleteView()});var u=this.er.get(i);u?(s=s||u.hasCompleteView(),o=o||u.getCompleteServerCache(d.Path.Empty)):(u=new f.SyncPoint,this.er=this.er.set(i,u));var l;null!=o?l=!0:(l=!1,o=a.ChildrenNode.EMPTY_NODE,this.er.subtree(i).foreachChild(function(e,t){var n=t.getCompleteServerCache(d.Path.Empty);n&&(o=o.updateImmediateChild(e,n))}));var h=u.viewExistsForQuery(t);if(!h&&!t.getQueryParams().loadsAllData()){var c=e.ur(t);r.assert(!(c in this.rr),"View does not exist, but we have a tag");var p=e.lr();this.rr[c]=p,this.nr["_"+p]=c}var _=this.tr.childWrites(i),y=u.addEventRegistration(t,n,_,o,l);if(!h&&!s){var v=u.viewForQuery(t);y=y.concat(this.hr(t,v))}return y},e.prototype.removeEventRegistration=function(t,n,r){var i=this,o=t.path,a=this.er.get(o),s=[];if(a&&("default"===t.queryIdentifier()||a.viewExistsForQuery(t))){var u=a.removeEventRegistration(t,n,r);a.isEmpty()&&(this.er=this.er.remove(o));var l=u.removed;s=u.events;var h=-1!==l.findIndex(function(e){return e.getQueryParams().loadsAllData()}),c=this.er.findOnPath(o,function(e,t){return t.hasCompleteView()});if(h&&!c){var p=this.er.subtree(o);if(!p.isEmpty())for(var d=this.cr(p),f=0;f0&&!r&&(h?this.Zn.stopListening(e.dr(t),null):l.forEach(function(t){var n=i.rr[e.ur(t)];i.Zn.stopListening(e.dr(t),n)})),this._r(l)}return s},e.prototype.calcCompleteEventCache=function(e,t){var n=this.tr,r=this.er.findOnPath(e,function(t,n){var r=d.Path.relativePath(t,e),i=n.getCompleteServerCache(r);if(i)return i});return n.calcCompleteEventCache(e,r,t,!0)},e.prototype.cr=function(e){return e.fold(function(e,t,n){if(t&&t.hasCompleteView())return[t.getCompleteView()];var r=[];return t&&(r=t.getQueryViews()),s.forEach(n,function(e,t){r=r.concat(t)}),r})},e.prototype._r=function(t){for(var n=0;n0||!e.getEventCache().isFullyInitialized()||i&&!r.getNode().equals(o)||!r.getNode().getPriority().equals(o.getPriority()))&&n.push(a.Change.valueChange(t.getCompleteEventSnap()))}},e.prototype.Lr=function(e,t,n,r,o){var a=e.getEventCache();if(null!=n.shadowingWrite(t))return e;var u=void 0,l=void 0;if(t.isEmpty())if(i.assert(e.getServerCache().isFullyInitialized(),"If change path is empty, we must have complete server data"),e.getServerCache().isFiltered()){var h=e.getCompleteServerSnap(),c=h instanceof s.ChildrenNode?h:s.ChildrenNode.EMPTY_NODE,p=n.calcCompleteEventChildren(c);u=this.Sr.updateFullNode(e.getEventCache().getNode(),p,o)}else{var d=n.calcCompleteEventCache(e.getCompleteServerSnap());u=this.Sr.updateFullNode(e.getEventCache().getNode(),d,o)}else{var f=t.getFront();if(".priority"==f){i.assert(1==t.getLength(),"Can't have a priority with additional path components");var _=a.getNode();l=e.getServerCache().getNode();var y=n.calcEventCacheAfterServerOverwrite(t,_,l);u=null!=y?this.Sr.updatePriority(_,y):a.getNode()}else{var v=t.popFront(),g=void 0;if(a.isCompleteForChild(f)){l=e.getServerCache().getNode();var m=n.calcEventCacheAfterServerOverwrite(t,a.getNode(),l);g=null!=m?a.getNode().getImmediateChild(f).updateChild(v,m):a.getNode().getImmediateChild(f)}else g=n.calcCompleteChild(f,e.getServerCache());u=null!=g?this.Sr.updateChild(a.getNode(),f,g,v,r,o):a.getNode()}}return e.updateEventSnap(u,a.isFullyInitialized()||t.isEmpty(),this.Sr.filtersNodes())},e.prototype.wr=function(e,t,n,r,i,o,a){var s,u=e.getServerCache(),l=o?this.Sr:this.Sr.getIndexedFilter();if(t.isEmpty())s=l.updateFullNode(u.getNode(),n,null);else if(l.filtersNodes()&&!u.isFiltered()){var h=u.getNode().updateChild(t,n);s=l.updateFullNode(u.getNode(),h,null)}else{var p=t.getFront();if(!u.isCompleteForPath(t)&&t.getLength()>1)return e;var d=t.popFront(),f=u.getNode().getImmediateChild(p),_=f.updateChild(d,n);s=".priority"==p?l.updatePriority(u.getNode(),_):l.updateChild(u.getNode(),p,_,d,c.NO_COMPLETE_CHILD_SOURCE,null)}var y=e.updateServerSnap(s,u.isFullyInitialized()||t.isEmpty(),l.filtersNodes()),v=new c.WriteTreeCompleteChildSource(r,y,i);return this.Lr(y,t,r,v,a)},e.prototype.Tr=function(e,t,n,r,i,o){var a,u,l=e.getEventCache(),h=new c.WriteTreeCompleteChildSource(r,e,i);if(t.isEmpty())u=this.Sr.updateFullNode(e.getEventCache().getNode(),n,o),a=e.updateEventSnap(u,!0,this.Sr.filtersNodes());else{var p=t.getFront();if(".priority"===p)u=this.Sr.updatePriority(e.getEventCache().getNode(),n),a=e.updateEventSnap(u,l.isFullyInitialized(),l.isFiltered());else{var d=t.popFront(),f=l.getNode().getImmediateChild(p),_=void 0;if(d.isEmpty())_=n;else{var y=h.getCompleteChild(p);_=null!=y?".priority"===d.getBack()&&y.getChild(d.parent()).isEmpty()?y:y.updateChild(d,n):s.ChildrenNode.EMPTY_NODE}if(f.equals(_))a=e;else{var v=this.Sr.updateChild(l.getNode(),p,_,d,h,o);a=e.updateEventSnap(v,l.isFullyInitialized(),this.Sr.filtersNodes())}}}return a},e.Fr=function(e,t){return e.getEventCache().isCompleteForChild(t)},e.prototype.Ir=function(t,n,r,i,o,a){var s=this,u=t;return r.foreach(function(r,l){var h=n.child(r);e.Fr(t,h.getFront())&&(u=s.Tr(u,h,l,i,o,a))}),r.foreach(function(r,l){var h=n.child(r);e.Fr(t,h.getFront())||(u=s.Tr(u,h,l,i,o,a))}),u},e.prototype.xr=function(e,t){return t.foreach(function(t,n){e=e.updateChild(t,n)}),e},e.prototype.Rr=function(e,t,n,r,i,o,a){var s=this;if(e.getServerCache().getNode().isEmpty()&&!e.getServerCache().isFullyInitialized())return e;var u,c=e;u=t.isEmpty()?n:l.ImmutableTree.Empty.setTree(t,n);var p=e.getServerCache().getNode();return u.children.inorderTraversal(function(t,n){if(p.hasChild(t)){var u=e.getServerCache().getNode().getImmediateChild(t),l=s.xr(u,n);c=s.wr(c,new h.Path(t),l,r,i,o,a)}}),u.children.inorderTraversal(function(t,n){var u=!e.getServerCache().isCompleteForChild(t)&&null==n.value;if(!p.hasChild(t)&&!u){var l=e.getServerCache().getNode().getImmediateChild(t),d=s.xr(l,n);c=s.wr(c,new h.Path(t),d,r,i,o,a)}}),c},e.prototype.Ar=function(e,t,n,r,i,o){if(null!=r.shadowingWrite(t))return e;var a=e.getServerCache().isFiltered(),s=e.getServerCache();if(null!=n.value){if(t.isEmpty()&&s.isFullyInitialized()||s.isCompleteForPath(t))return this.wr(e,t,s.getNode().getChild(t),r,i,a,o);if(t.isEmpty()){var c=l.ImmutableTree.Empty;return s.getNode().forEachChild(u.KEY_INDEX,function(e,t){c=c.set(new h.Path(e),t)}),this.Rr(e,t,c,r,i,a,o)}return e}var p=l.ImmutableTree.Empty;return n.foreach(function(e,n){var r=t.child(e);s.isCompleteForPath(r)&&(p=p.set(e,s.getNode().getChild(r)))}),this.Rr(e,t,p,r,i,a,o)},e.prototype.Dr=function(e,t,n,r){var i=e.getServerCache(),o=e.updateServerSnap(i.getNode(),i.isFullyInitialized()||t.isEmpty(),i.isFiltered());return this.Lr(o,t,n,c.NO_COMPLETE_CHILD_SOURCE,r)},e.prototype.Or=function(e,t,n,r,o){var a;if(null!=n.shadowingWrite(t))return e;var u=new c.WriteTreeCompleteChildSource(n,e,r),l=e.getEventCache().getNode(),p=void 0;if(t.isEmpty()||".priority"===t.getFront()){var d=void 0;if(e.getServerCache().isFullyInitialized())d=n.calcCompleteEventCache(e.getCompleteServerSnap());else{var f=e.getServerCache().getNode();i.assert(f instanceof s.ChildrenNode,"serverChildren would be complete if leaf node"),d=n.calcCompleteEventChildren(f)}d=d,p=this.Sr.updateFullNode(l,d,o)}else{var _=t.getFront(),y=n.calcCompleteChild(_,e.getServerCache());null==y&&e.getServerCache().isCompleteForChild(_)&&(y=l.getImmediateChild(_)),p=null!=y?this.Sr.updateChild(l,_,y,t.popFront(),u,o):e.getEventCache().getNode().hasChild(_)?this.Sr.updateChild(l,_,s.ChildrenNode.EMPTY_NODE,t.popFront(),u,o):l,p.isEmpty()&&e.getServerCache().isFullyInitialized()&&(a=n.calcCompleteEventCache(e.getCompleteServerSnap()),a.isLeafNode()&&(p=this.Sr.updateFullNode(p,a,o)))}return a=e.getServerCache().isFullyInitialized()||null!=n.shadowingWrite(h.Path.Empty),e.updateEventSnap(p,a,this.Sr.filtersNodes())},e}();t.ViewProcessor=d},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(9),o=n(0),a=function(){function e(){this.kr={}}return e.prototype.trackChildChange=function(e){var t=e.type,n=e.childName;o.assert(t==i.Change.CHILD_ADDED||t==i.Change.CHILD_CHANGED||t==i.Change.CHILD_REMOVED,"Only child changes supported for tracking"),o.assert(".priority"!==n,"Only non-priority child changes can be tracked.");var a=r.safeGet(this.kr,n);if(a){var s=a.type;if(t==i.Change.CHILD_ADDED&&s==i.Change.CHILD_REMOVED)this.kr[n]=i.Change.childChangedChange(n,e.snapshotNode,a.snapshotNode);else if(t==i.Change.CHILD_REMOVED&&s==i.Change.CHILD_ADDED)delete this.kr[n];else if(t==i.Change.CHILD_REMOVED&&s==i.Change.CHILD_CHANGED)this.kr[n]=i.Change.childRemovedChange(n,a.oldSnap);else if(t==i.Change.CHILD_CHANGED&&s==i.Change.CHILD_ADDED)this.kr[n]=i.Change.childAddedChange(n,e.snapshotNode);else{if(t!=i.Change.CHILD_CHANGED||s!=i.Change.CHILD_CHANGED)throw o.assertionError("Illegal combination of changes: "+e+" occurred after "+a);this.kr[n]=i.Change.childChangedChange(n,e.snapshotNode,a.oldSnap)}}else this.kr[n]=e},e.prototype.getChanges=function(){return r.getValues(this.kr)},e}();t.ChildChangeAccumulator=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(19),i=function(){function e(){}return e.prototype.getCompleteChild=function(e){return null},e.prototype.getChildAfterChild=function(e,t,n){return null},e}();t.Wr=i,t.NO_COMPLETE_CHILD_SOURCE=new i;var o=function(){function e(e,t,n){void 0===n&&(n=null),this.jr=e,this.Nr=t,this.Vr=n}return e.prototype.getCompleteChild=function(e){var t=this.Nr.getEventCache();if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);var n=null!=this.Vr?new r.CacheNode(this.Vr,!0,!1):this.Nr.getServerCache();return this.jr.calcCompleteChild(e,n)},e.prototype.getChildAfterChild=function(e,t,n){var r=null!=this.Vr?this.Vr:this.Nr.getCompleteServerSnap(),i=this.jr.calcIndexedSlice(r,t,1,n,e);return 0===i.length?null:i[0]},e}();t.WriteTreeCompleteChildSource=o},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(5),i=n(9),o=n(0),a=function(){function e(e){this.mr=e,this.me=this.mr.getQueryParams().getIndex()}return e.prototype.generateEventsForChanges=function(e,t,n){var r=this,o=[],a=[];return e.forEach(function(e){e.type===i.Change.CHILD_CHANGED&&r.me.indexedValueChanged(e.oldSnap,e.snapshotNode)&&a.push(i.Change.childMovedChange(e.childName,e.snapshotNode))}),this.Qr(o,i.Change.CHILD_REMOVED,e,n,t),this.Qr(o,i.Change.CHILD_ADDED,e,n,t),this.Qr(o,i.Change.CHILD_MOVED,a,n,t),this.Qr(o,i.Change.CHILD_CHANGED,e,n,t),this.Qr(o,i.Change.VALUE,e,n,t),o},e.prototype.Qr=function(e,t,n,r,i){var o=this,a=n.filter(function(e){return e.type===t});a.sort(this.qr.bind(this)),a.forEach(function(t){var n=o.Ur(t,i);r.forEach(function(r){r.respondsTo(t.type)&&e.push(r.createEvent(n,o.mr))})})},e.prototype.Ur=function(e,t){return"value"===e.type||"child_removed"===e.type?e:(e.prevName=t.getPredecessorChildName(e.childName,e.snapshotNode,this.me),e)},e.prototype.qr=function(e,t){if(null==e.childName||null==t.childName)throw o.assertionError("Should only compare child_ events.");var n=new r.NamedNode(e.childName,e.snapshotNode),i=new r.NamedNode(t.childName,t.snapshotNode);return this.me.compare(n,i)},e}();t.EventGenerator=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(0),o=n(2),a=n(96),s=n(3),u=n(4),l=function(){function e(){this.Br=a.CompoundWrite.Empty,this.Hr=[],this.Gr=-1}return e.prototype.childWrites=function(e){return new h(e,this)},e.prototype.addOverwrite=function(e,t,n,r){i.assert(n>this.Gr,"Stacking an older write on top of newer ones"),void 0===r&&(r=!0),this.Hr.push({path:e,snap:t,writeId:n,visible:r}),r&&(this.Br=this.Br.addWrite(e,t)),this.Gr=n},e.prototype.addMerge=function(e,t,n){i.assert(n>this.Gr,"Stacking an older merge on top of newer ones"),this.Hr.push({path:e,children:t,writeId:n,visible:!0}),this.Br=this.Br.addWrites(e,t),this.Gr=n},e.prototype.getWrite=function(e){for(var t=0;t=0,"removeWrite called with nonexistent writeId.");var o=this.Hr[n];this.Hr.splice(n,1);for(var a=o.visible,s=!1,u=this.Hr.length-1;a&&u>=0;){var l=this.Hr[u];l.visible&&(u>=n&&this.Kr(l,o.path)?a=!1:o.path.contains(l.path)&&(s=!0)),u--}if(a){if(s)return this.Yr(),!0;if(o.snap)this.Br=this.Br.removeWrite(o.path);else{var h=o.children;r.forEach(h,function(e){t.Br=t.Br.removeWrite(o.path.child(e))})}return!0}return!1},e.prototype.getCompleteWriteData=function(e){return this.Br.getCompleteNode(e)},e.prototype.calcCompleteEventCache=function(t,n,r,i){if(r||i){var a=this.Br.childCompoundWrite(t);if(!i&&a.isEmpty())return n;if(i||null!=n||a.hasCompleteWrite(o.Path.Empty)){var s=function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(e.path.contains(t)||t.contains(e.path))},l=e.Xr(this.Hr,s,t),h=n||u.ChildrenNode.EMPTY_NODE;return l.apply(h)}return null}var c=this.Br.getCompleteNode(t);if(null!=c)return c;var p=this.Br.childCompoundWrite(t);if(p.isEmpty())return n;if(null!=n||p.hasCompleteWrite(o.Path.Empty)){var h=n||u.ChildrenNode.EMPTY_NODE;return p.apply(h)}return null},e.prototype.calcCompleteEventChildren=function(e,t){var n=u.ChildrenNode.EMPTY_NODE,r=this.Br.getCompleteNode(e);if(r)return r.isLeafNode()||r.forEachChild(s.PRIORITY_INDEX,function(e,t){n=n.updateImmediateChild(e,t)}),n;if(t){var i=this.Br.childCompoundWrite(e);return t.forEachChild(s.PRIORITY_INDEX,function(e,t){var r=i.childCompoundWrite(new o.Path(e)).apply(t);n=n.updateImmediateChild(e,r)}),i.getCompleteChildren().forEach(function(e){n=n.updateImmediateChild(e.name,e.node)}),n}return this.Br.childCompoundWrite(e).getCompleteChildren().forEach(function(e){n=n.updateImmediateChild(e.name,e.node)}),n},e.prototype.calcEventCacheAfterServerOverwrite=function(e,t,n,r){i.assert(n||r,"Either existingEventSnap or existingServerSnap must exist");var o=e.child(t);if(this.Br.hasCompleteWrite(o))return null;var a=this.Br.childCompoundWrite(o);return a.isEmpty()?r.getChild(t):a.apply(r.getChild(t))},e.prototype.calcCompleteChild=function(e,t,n){var r=e.child(t),i=this.Br.getCompleteNode(r);return null!=i?i:n.isCompleteForChild(t)?this.Br.childCompoundWrite(r).apply(n.getNode().getImmediateChild(t)):null},e.prototype.shadowingWrite=function(e){return this.Br.getCompleteNode(e)},e.prototype.calcIndexedSlice=function(e,t,n,r,i,a){var s,u=this.Br.childCompoundWrite(e),l=u.getCompleteNode(o.Path.Empty);if(null!=l)s=l;else{if(null==t)return[];s=u.apply(t)}if(s=s.withIndex(a),s.isEmpty()||s.isLeafNode())return[];for(var h=[],c=a.getCompare(),p=i?s.getReverseIteratorFrom(n,a):s.getIteratorFrom(n,a),d=p.getNext();d&&h.length0?this.Gr=this.Hr[this.Hr.length-1].writeId:this.Gr=-1},e.zr=function(e){return e.visible},e.Xr=function(e,t,n){for(var s=a.CompoundWrite.Empty,u=0;u0&&r.contains(e.ri,t)&&(n[t]=i,o=!0)}),o&&this.Z.reportStats(n),i.setTimeoutNonBlocking(this.ii.bind(this),Math.floor(2*Math.random()*3e5))},e}();t.StatsReporter=u},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),i=function(){function e(){this.oi=[],this.ai=0}return e.prototype.queueEvents=function(e){for(var t=null,n=0;n0)return this.ci[0];throw Error("No transports available")},e.prototype.upgradeTransport=function(){return this.ci.length>1?this.ci[1]:null},e}();t.TransportManager=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),i=function(){function e(e){this.Ut=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}return e.prototype.closeAfter=function(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse=200&&h.status<300){try{e=a.jsonEval(h.responseText)}catch(e){o.warn("Failed to parse JSON response for "+l+": "+h.responseText)}n(null,e)}else 401!==h.status&&404!==h.status&&o.warn("Got unsuccessful REST response for "+l+" Status: "+h.status),n(h.status);n=null}},h.open("GET",l,!0),h.send()})},t}(l.ServerActions);t.ReadonlyRestClient=h},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=n(1),o=n(10),a=n(3),s=n(38),u=n(42),l=n(24),h=n(108),c=n(56),p=n(0),d=function(){function e(){this.fi=!1,this._i=!1,this.yi=!1,this.vi=!1,this.gi=!1,this.mi=0,this.Ci="",this.Ei=null,this.Ni="",this.Pi=null,this.bi="",this.me=a.PRIORITY_INDEX}return e.prototype.hasStart=function(){return this._i},e.prototype.isViewFromLeft=function(){return""===this.Ci?this._i:this.Ci===e.Si.VIEW_FROM_LEFT},e.prototype.getIndexStartValue=function(){return r.assert(this._i,"Only valid if start has been set"),this.Ei},e.prototype.getIndexStartName=function(){return r.assert(this._i,"Only valid if start has been set"),this.yi?this.Ni:i.MIN_NAME},e.prototype.hasEnd=function(){return this.vi},e.prototype.getIndexEndValue=function(){return r.assert(this.vi,"Only valid if end has been set"),this.Pi},e.prototype.getIndexEndName=function(){return r.assert(this.vi,"Only valid if end has been set"),this.gi?this.bi:i.MAX_NAME},e.prototype.hasLimit=function(){return this.fi},e.prototype.hasAnchoredLimit=function(){return this.fi&&""!==this.Ci},e.prototype.getLimit=function(){return r.assert(this.fi,"Only valid if limit has been set"),this.mi},e.prototype.getIndex=function(){return this.me},e.prototype.Ti=function(){var t=new e;return t.fi=this.fi,t.mi=this.mi,t._i=this._i,t.Ei=this.Ei,t.yi=this.yi,t.Ni=this.Ni,t.vi=this.vi,t.Pi=this.Pi,t.gi=this.gi,t.bi=this.bi,t.me=this.me,t.Ci=this.Ci,t},e.prototype.limit=function(e){var t=this.Ti();return t.fi=!0,t.mi=e,t.Ci="",t},e.prototype.limitToFirst=function(t){var n=this.Ti();return n.fi=!0,n.mi=t,n.Ci=e.Si.VIEW_FROM_LEFT,n},e.prototype.limitToLast=function(t){var n=this.Ti();return n.fi=!0,n.mi=t,n.Ci=e.Si.VIEW_FROM_RIGHT,n},e.prototype.startAt=function(e,t){var n=this.Ti();return n._i=!0,void 0===e&&(e=null),n.Ei=e,null!=t?(n.yi=!0,n.Ni=t):(n.yi=!1,n.Ni=""),n},e.prototype.endAt=function(e,t){var n=this.Ti();return n.vi=!0,void 0===e&&(e=null),n.Pi=e,void 0!==t?(n.gi=!0,n.bi=t):(n.gi=!1,n.bi=""),n},e.prototype.orderBy=function(e){var t=this.Ti();return t.me=e,t},e.prototype.getQueryObject=function(){var t=e.Si,n={};if(this._i&&(n[t.INDEX_START_VALUE]=this.Ei,this.yi&&(n[t.INDEX_START_NAME]=this.Ni)),this.vi&&(n[t.INDEX_END_VALUE]=this.Pi,this.gi&&(n[t.INDEX_END_NAME]=this.bi)),this.fi){n[t.LIMIT]=this.mi;var r=this.Ci;""===r&&(r=this.isViewFromLeft()?t.VIEW_FROM_LEFT:t.VIEW_FROM_RIGHT),n[t.VIEW_FROM]=r}return this.me!==a.PRIORITY_INDEX&&(n[t.INDEX]=""+this.me),n},e.prototype.loadsAllData=function(){return!(this._i||this.vi||this.fi)},e.prototype.isDefault=function(){return this.loadsAllData()&&this.me==a.PRIORITY_INDEX},e.prototype.getNodeFilter=function(){return this.loadsAllData()?new l.IndexedFilter(this.getIndex()):this.hasLimit()?new h.LimitedFilter(this):new c.RangedFilter(this)},e.prototype.toRestQueryStringParameters=function(){var t=e.wi,n={};if(this.isDefault())return n;var i;return this.me===a.PRIORITY_INDEX?i=t.PRIORITY_INDEX:this.me===s.VALUE_INDEX?i=t.VALUE_INDEX:this.me===o.KEY_INDEX?i=t.KEY_INDEX:(r.assert(this.me instanceof u.PathIndex,"Unrecognized index type!"),i=""+this.me),n[t.ORDER_BY]=p.stringify(i),this._i&&(n[t.START_AT]=p.stringify(this.Ei),this.yi&&(n[t.START_AT]+=","+p.stringify(this.Ni))),this.vi&&(n[t.END_AT]=p.stringify(this.Pi),this.gi&&(n[t.END_AT]+=","+p.stringify(this.bi))),this.fi&&(this.isViewFromLeft()?n[t.LIMIT_TO_FIRST]=this.mi:n[t.LIMIT_TO_LAST]=this.mi),n},e.Si={INDEX_START_VALUE:"sp",INDEX_START_NAME:"sn",INDEX_END_VALUE:"ep",INDEX_END_NAME:"en",LIMIT:"l",VIEW_FROM:"vf",VIEW_FROM_LEFT:"l",VIEW_FROM_RIGHT:"r",INDEX:"i"},e.wi={ORDER_BY:"orderBy",PRIORITY_INDEX:"$priority",VALUE_INDEX:"$value",KEY_INDEX:"$key",START_AT:"startAt",END_AT:"endAt",LIMIT_TO_FIRST:"limitToFirst",LIMIT_TO_LAST:"limitToLast"},e.DEFAULT=new e,e}();t.QueryParams=d},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(56),i=n(4),o=n(5),a=n(0),s=n(9),u=function(){function e(e){this.Ii=new r.RangedFilter(e),this.me=e.getIndex(),this.mi=e.getLimit(),this.Ri=!e.isViewFromLeft()}return e.prototype.updateChild=function(e,t,n,r,a,s){return this.Ii.matches(new o.NamedNode(t,n))||(n=i.ChildrenNode.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()=0)return null!=u&&u.trackChildChange(s.Change.childChangedChange(t,n,_)),c.updateImmediateChild(t,n);null!=u&&u.trackChildChange(s.Change.childRemovedChange(t,_));var g=c.updateImmediateChild(t,i.ChildrenNode.EMPTY_NODE);return null!=y&&this.Ii.matches(y)?(null!=u&&u.trackChildChange(s.Change.childAddedChange(y.name,y.node)),g.updateImmediateChild(y.name,y.node)):g}return n.isEmpty()?e:f&&l(d,p)>=0?(null!=u&&(u.trackChildChange(s.Change.childRemovedChange(d.name,d.node)),u.trackChildChange(s.Change.childAddedChange(t,n))),c.updateImmediateChild(t,n).updateImmediateChild(d.name,i.ChildrenNode.EMPTY_NODE)):e},e}();t.LimitedFilter=u},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r,i=n(0),o=n(21),a=n(22),s=n(2),u=n(110),l=n(3),h=n(1),c=n(43),p=n(7),d=n(0),f=n(11),_=n(4),y=n(18);!function(e){e[e.RUN=0]="RUN",e[e.SENT=1]="SENT",e[e.COMPLETED=2]="COMPLETED",e[e.SENT_NEEDS_ABORT=3]="SENT_NEEDS_ABORT",e[e.NEEDS_ABORT=4]="NEEDS_ABORT"}(r=t.TransactionStatus||(t.TransactionStatus={})),y.Repo.Ai=25,y.Repo.prototype.ie=function(){this.Di=new u.Tree},y.Repo.prototype.startTransaction=function(e,t,n,s){this.de("transaction on "+e);var u=function(){},y=new o.Reference(this,e);y.on("value",u);var v=function(){y.off("value",u)},g={path:e,update:t,onComplete:n,status:null,order:h.LUIDGenerator(),applyLocally:s,retryCount:0,unwatcher:v,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},m=this.Mi(e);g.currentInputSnapshot=m;var C=g.update(m.val());if(void 0===C){if(g.unwatcher(),g.currentOutputSnapshotRaw=null,g.currentOutputSnapshotResolved=null,g.onComplete){var E=new a.DataSnapshot(g.currentInputSnapshot,new o.Reference(this,g.path),l.PRIORITY_INDEX);g.onComplete(null,!1,E)}}else{p.validateFirebaseData("transaction failed: Data returned ",C,g.path),g.status=r.RUN;var N=this.Di.subTree(e),P=N.getValue()||[];P.push(g),N.setValue(P);var b=void 0;"object"==typeof C&&null!==C&&d.contains(C,".priority")?(b=d.safeGet(C,".priority"),i.assert(p.isValidPriority(b),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):b=(this.ue.calcCompleteEventCache(e)||_.ChildrenNode.EMPTY_NODE).getPriority().val(),b=b;var S=this.generateServerValues(),T=f.nodeFromJSON(C,b),w=c.resolveDeferredValueSnapshot(T,S);g.currentOutputSnapshotRaw=T,g.currentOutputSnapshotResolved=w,g.currentWriteId=this.pe();var I=this.ue.applyUserOverwrite(e,w,g.currentWriteId,g.applyLocally);this.K.raiseEventsForChangedPath(e,I),this.Li()}},y.Repo.prototype.Mi=function(e,t){return this.ue.calcCompleteEventCache(e,t)||_.ChildrenNode.EMPTY_NODE},y.Repo.prototype.Li=function(e){var t=this;if(void 0===e&&(e=this.Di),e||this.Fi(e),null!==e.getValue()){var n=this.xi(e);i.assert(n.length>0,"Sending zero length transaction queue"),n.every(function(e){return e.status===r.RUN})&&this.ki(e.path(),n)}else e.hasChildren()&&e.forEachChild(function(e){t.Li(e)})},y.Repo.prototype.ki=function(e,t){for(var n=this,u=t.map(function(e){return e.currentWriteId}),c=this.Mi(e,u),p=c,d=c.hash(),f=0;f=y.Repo.Ai)E=!0,N="maxretry",u=u.concat(this.ue.ackUserWrite(m.currentWriteId,!0));else{var P=this.Mi(m.path,v);m.currentInputSnapshot=P;var b=e[g].update(P.val());if(void 0!==b){p.validateFirebaseData("transaction failed: Data returned ",b,m.path);var S=f.nodeFromJSON(b),T="object"==typeof b&&null!=b&&d.contains(b,".priority");T||(S=S.updatePriority(P.getPriority()));var w=m.currentWriteId,I=this.generateServerValues(),R=c.resolveDeferredValueSnapshot(S,I);m.currentOutputSnapshotRaw=S,m.currentOutputSnapshotResolved=R,m.currentWriteId=this.pe(),v.splice(v.indexOf(w),1),u=u.concat(this.ue.applyUserOverwrite(m.path,R,m.currentWriteId,m.applyLocally)),u=u.concat(this.ue.ackUserWrite(w,!0))}else E=!0,N="nodata",u=u.concat(this.ue.ackUserWrite(m.currentWriteId,!0))}if(this.K.raiseEventsForChangedPath(t,u),u=[],E&&(e[g].status=r.COMPLETED,function(e){setTimeout(e,Math.floor(0))}(e[g].unwatcher),e[g].onComplete))if("nodata"===N){var O=new o.Reference(this,e[g].path),A=e[g].currentInputSnapshot,D=new a.DataSnapshot(A,O,l.PRIORITY_INDEX);n.push(e[g].onComplete.bind(null,null,!1,D))}else n.push(e[g].onComplete.bind(null,Error(N),!1,null))}this.Fi(this.Di);for(var g=0;g0?n:null)}e.forEachChild(function(e){t.Fi(e)})},y.Repo.prototype.fe=function(e){var t=this,n=this.Wi(e).path(),r=this.Di.subTree(e);return r.forEachAncestor(function(e){t.Qi(e)}),this.Qi(r),r.forEachDescendant(function(e){t.Qi(e)}),n},y.Repo.prototype.Qi=function(e){var t=e.getValue();if(null!==t){for(var n=[],o=[],a=-1,s=0;s0},e.prototype.isEmpty=function(){return null===this.getValue()&&!this.hasChildren()},e.prototype.forEachChild=function(t){var n=this;o.forEach(this._e.children,function(r,i){t(new e(r,n,i))})},e.prototype.forEachDescendant=function(e,t,n){t&&!n&&e(this),this.forEachChild(function(t){t.forEachDescendant(e,!0,n)}),t&&n&&e(this)},e.prototype.forEachAncestor=function(e,t){for(var n=t?this:this.parent();null!==n;){if(e(n))return!0;n=n.parent()}return!1},e.prototype.forEachImmediateDescendantWithValue=function(e){this.forEachChild(function(t){null!==t.getValue()?e(t):t.forEachImmediateDescendantWithValue(e)})},e.prototype.path=function(){return new i.Path(null===this.Ui?this.qi:this.Ui.path()+"/"+this.qi)},e.prototype.name=function(){return this.qi},e.prototype.parent=function(){return this.Ui},e.prototype.Bi=function(){null!==this.Ui&&this.Ui.Hi(this.qi,this)},e.prototype.Hi=function(e,t){var n=t.isEmpty(),r=o.contains(this._e.children,e);n&&r?(delete this._e.children[e],this._e.childCount--,this.Bi()):n||r||(this._e.children[e]=t._e,this._e.childCount++,this.Bi())},e}();t.Tree=s},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(54),i=n(53);t.forceLongPolling=function(){r.WebSocketConnection.forceDisallow(),i.BrowserPollConnection.forceAllow()},t.forceWebSockets=function(){i.BrowserPollConnection.forceDisallow()},t.isWebSocketsAvailable=function(){return r.WebSocketConnection.isAvailable()},t.setSecurityDebugCallback=function(e,t){e.repo.J.it=t},t.stats=function(e,t){e.repo.stats(t)},t.statsIncrementCounter=function(e,t){e.repo.statsIncrementCounter(t)},t.dataUpdateCount=function(e){return e.repo.dataUpdateCount},t.interceptServerData=function(e,t){return e.repo.he(t)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(34),i=n(50),o=n(26),a=n(52);t.DataConnection=i.PersistentConnection,i.PersistentConnection.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},i.PersistentConnection.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},t.RealTimeConnection=a.Connection,t.hijackHash=function(e){var t=i.PersistentConnection.prototype.put;return i.PersistentConnection.prototype.put=function(n,r,i,o){void 0!==o&&(o=e()),t.call(this,n,r,i,o)},function(){i.PersistentConnection.prototype.put=t}},t.ConnectionTarget=r.RepoInfo,t.queryIdentifier=function(e){return e.queryIdentifier()},t.listens=function(e){return e.repo.J.Je},t.forceRestClient=function(e){o.RepoManager.getInstance().forceRestClient(e)}}],[78])}catch(e){throw Error("Cannot instantiate firebase-database.js - be sure to load firebase-app.js first.")} + +/*! + * @license Firebase v4.8.1 + * Build: rev-d8c20f0 + * Terms: https://firebase.google.com/terms/ + */ +try{webpackJsonpFirebase([3],{116:function(e,t,r){r(117)},117:function(e,t,r){"use strict";function n(e){var t=new Uint8Array(e);return window.btoa(String.fromCharCode.apply(null,t))}function o(e){var t=function(e){return self&&"ServiceWorkerGlobalScope"in self?new A(e):new k(e)},r={Messaging:k};e.INTERNAL.registerService("messaging",t,r)}Object.defineProperty(t,"__esModule",{value:!0});var i,s=r(0),a={AVAILABLE_IN_WINDOW:"only-available-in-window",AVAILABLE_IN_SW:"only-available-in-sw",SHOULD_BE_INHERITED:"should-be-overriden",BAD_SENDER_ID:"bad-sender-id",INCORRECT_GCM_SENDER_ID:"incorrect-gcm-sender-id",PERMISSION_DEFAULT:"permission-default",PERMISSION_BLOCKED:"permission-blocked",UNSUPPORTED_BROWSER:"unsupported-browser",NOTIFICATIONS_BLOCKED:"notifications-blocked",FAILED_DEFAULT_REGISTRATION:"failed-serviceworker-registration",SW_REGISTRATION_EXPECTED:"sw-registration-expected",GET_SUBSCRIPTION_FAILED:"get-subscription-failed",INVALID_SAVED_TOKEN:"invalid-saved-token",SW_REG_REDUNDANT:"sw-reg-redundant",TOKEN_SUBSCRIBE_FAILED:"token-subscribe-failed",TOKEN_SUBSCRIBE_NO_TOKEN:"token-subscribe-no-token",TOKEN_SUBSCRIBE_NO_PUSH_SET:"token-subscribe-no-push-set",USE_SW_BEFORE_GET_TOKEN:"use-sw-before-get-token",INVALID_DELETE_TOKEN:"invalid-delete-token",DELETE_TOKEN_NOT_FOUND:"delete-token-not-found",DELETE_SCOPE_NOT_FOUND:"delete-scope-not-found",BG_HANDLER_FUNCTION_EXPECTED:"bg-handler-function-expected",NO_WINDOW_CLIENT_TO_MSG:"no-window-client-to-msg",UNABLE_TO_RESUBSCRIBE:"unable-to-resubscribe",NO_FCM_TOKEN_FOR_RESUBSCRIBE:"no-fcm-token-for-resubscribe",FAILED_TO_DELETE_TOKEN:"failed-to-delete-token",NO_SW_IN_REG:"no-sw-in-reg",BAD_SCOPE:"bad-scope",BAD_VAPID_KEY:"bad-vapid-key",BAD_SUBSCRIPTION:"bad-subscription",BAD_TOKEN:"bad-token",BAD_PUSH_SET:"bad-push-set",FAILED_DELETE_VAPID_KEY:"failed-delete-vapid-key"},c=(i={},i[a.AVAILABLE_IN_WINDOW]="This method is available in a Window context.",i[a.AVAILABLE_IN_SW]="This method is available in a service worker context.",i["should-be-overriden"]="This method should be overriden by extended classes.",i["bad-sender-id"]="Please ensure that 'messagingSenderId' is set correctly in the options passed into firebase.initializeApp().",i["permission-default"]="The required permissions were not granted and dismissed instead.",i["permission-blocked"]="The required permissions were not granted and blocked instead.",i["unsupported-browser"]="This browser doesn't support the API's required to use the firebase SDK.",i["notifications-blocked"]="Notifications have been blocked.",i[a.FAILED_DEFAULT_REGISTRATION]="We are unable to register the default service worker. {$browserErrorMessage}",i["sw-registration-expected"]="A service worker registration was the expected input.",i["get-subscription-failed"]="There was an error when trying to get any existing Push Subscriptions.",i["invalid-saved-token"]="Unable to access details of the saved token.",i["sw-reg-redundant"]="The service worker being used for push was made redundant.",i["token-subscribe-failed"]="A problem occured while subscribing the user to FCM: {$message}",i["token-subscribe-no-token"]="FCM returned no token when subscribing the user to push.",i["token-subscribe-no-push-set"]="FCM returned an invalid response when getting an FCM token.",i["use-sw-before-get-token"]="You must call useServiceWorker() before calling getToken() to ensure your service worker is used.",i["invalid-delete-token"]="You must pass a valid token into deleteToken(), i.e. the token from getToken().",i["delete-token-not-found"]="The deletion attempt for token could not be performed as the token was not found.",i["delete-scope-not-found"]="The deletion attempt for service worker scope could not be performed as the scope was not found.",i["bg-handler-function-expected"]="The input to setBackgroundMessageHandler() must be a function.",i["no-window-client-to-msg"]="An attempt was made to message a non-existant window client.",i["unable-to-resubscribe"]="There was an error while re-subscribing the FCM token for push messaging. Will have to resubscribe the user on next visit. {$message}",i["no-fcm-token-for-resubscribe"]="Could not find an FCM token and as a result, unable to resubscribe. Will have to resubscribe the user on next visit.",i["failed-to-delete-token"]="Unable to delete the currently saved token.",i["no-sw-in-reg"]="Even though the service worker registration was successful, there was a problem accessing the service worker itself.",i["incorrect-gcm-sender-id"]="Please change your web app manifest's 'gcm_sender_id' value to '103953800507' to use Firebase messaging.",i["bad-scope"]="The service worker scope must be a string with at least one character.",i["bad-vapid-key"]="The public VAPID key must be a string with at least one character.",i["bad-subscription"]="The subscription must be a valid PushSubscription.",i["bad-token"]="The FCM Token used for storage / lookup was not a valid token string.",i["bad-push-set"]="The FCM push set used for storage / lookup was not not a valid push set string.",i["failed-delete-vapid-key"]="The VAPID key could not be deleted.",i),u={codes:a,map:c},_=function(e){return n(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")},d=[4,51,148,247,223,161,235,177,220,3,162,94,21,113,219,72,211,46,237,237,178,52,219,183,71,58,12,143,196,204,225,111,60,140,132,223,171,182,102,62,242,12,212,139,254,227,249,118,47,20,28,99,8,106,111,45,177,26,149,176,206,55,192,156,110],f={userVisibleOnly:!0,applicationServerKey:new Uint8Array(d)},h={ENDPOINT:"https://fcm.googleapis.com",APPLICATION_SERVER_KEY:d,SUBSCRIPTION_OPTIONS:f},p="fcm_token_object_Store",l=function(){function e(){this.e=new s.ErrorFactory("messaging","Messaging",u.map),this.t=null}return e.prototype.r=function(){return this.t?this.t:(this.t=new Promise(function(t,r){var n=indexedDB.open(e.DB_NAME,1);n.onerror=function(e){r(e.target.error)},n.onsuccess=function(e){t(e.target.result)},n.onupgradeneeded=function(e){var t=e.target.result,r=t.createObjectStore(p,{keyPath:"swScope"});r.createIndex("fcmSenderId","fcmSenderId",{unique:!1}),r.createIndex("fcmToken","fcmToken",{unique:!0})}}),this.t)},e.prototype.closeDatabase=function(){var e=this;return this.t?this.t.then(function(t){t.close(),e.t=null}):Promise.resolve()},e.prototype.getTokenDetailsFromToken=function(e){return this.r().then(function(t){return new Promise(function(r,n){var o=t.transaction([p]),i=o.objectStore(p),s=i.index("fcmToken"),a=s.get(e);a.onerror=function(e){n(e.target.error)},a.onsuccess=function(e){r(e.target.result)}})})},e.prototype.n=function(e){return this.r().then(function(t){return new Promise(function(r,n){var o=t.transaction([p]),i=o.objectStore(p),s=i.get(e);s.onerror=function(e){n(e.target.error)},s.onsuccess=function(e){r(e.target.result)}})})},e.prototype.o=function(e){return this.r().then(function(t){return new Promise(function(r,n){var o=t.transaction([p]),i=o.objectStore(p),s=[],a=i.openCursor();a.onerror=function(e){n(e.target.error)},a.onsuccess=function(t){var n=t.target.result;n?(n.value.fcmSenderId===e&&s.push(n.value),n.continue()):r(s)}})})},e.prototype.subscribeToFCM=function(e,t,r){var n=this,o=_(t.getKey("p256dh")),i=_(t.getKey("auth")),s="authorized_entity="+e+"&endpoint="+t.endpoint+"&encryption_key="+o+"&encryption_auth="+i;r&&(s+="&pushSet="+r);var a=new Headers;a.append("Content-Type","application/x-www-form-urlencoded");var c={method:"POST",headers:a,body:s};return fetch(h.ENDPOINT+"/fcm/connect/subscribe",c).then(function(e){return e.json()}).then(function(e){var t=e;if(t.error){var r=t.error.message;throw n.e.create(u.codes.TOKEN_SUBSCRIBE_FAILED,{message:r})}if(!t.token)throw n.e.create(u.codes.TOKEN_SUBSCRIBE_NO_TOKEN);if(!t.pushSet)throw n.e.create(u.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET);return{token:t.token,pushSet:t.pushSet}})},e.prototype.i=function(e,t){return e.endpoint===t.endpoint&&_(e.getKey("auth"))===t.auth&&_(e.getKey("p256dh"))===t.p256dh},e.prototype.s=function(e,t,r,n,o){var i={swScope:t.scope,endpoint:r.endpoint,auth:_(r.getKey("auth")),p256dh:_(r.getKey("p256dh")),fcmToken:n,fcmPushSet:o,fcmSenderId:e};return this.r().then(function(e){return new Promise(function(t,r){var n=e.transaction([p],"readwrite"),o=n.objectStore(p),s=o.put(i);s.onerror=function(e){r(e.target.error)},s.onsuccess=function(e){t()}})})},e.prototype.getSavedToken=function(e,t){var r=this;return t instanceof ServiceWorkerRegistration?"string"!=typeof e||0===e.length?Promise.reject(this.e.create(u.codes.BAD_SENDER_ID)):this.o(e).then(function(r){if(0!==r.length){var n=r.findIndex(function(r){return t.scope===r.swScope&&e===r.fcmSenderId});if(-1!==n)return r[n]}}).then(function(e){if(e)return t.pushManager.getSubscription().catch(function(e){throw r.e.create(u.codes.GET_SUBSCRIPTION_FAILED)}).then(function(t){if(t&&r.i(t,e))return e.fcmToken})}):Promise.reject(this.e.create(u.codes.SW_REGISTRATION_EXPECTED))},e.prototype.createToken=function(e,t){var r=this;if("string"!=typeof e||0===e.length)return Promise.reject(this.e.create(u.codes.BAD_SENDER_ID));if(!(t instanceof ServiceWorkerRegistration))return Promise.reject(this.e.create(u.codes.SW_REGISTRATION_EXPECTED));var n,o;return t.pushManager.getSubscription().then(function(e){return e||t.pushManager.subscribe(h.SUBSCRIPTION_OPTIONS)}).then(function(t){return n=t,r.subscribeToFCM(e,n)}).then(function(i){return o=i,r.s(e,t,n,o.token,o.pushSet)}).then(function(){return o.token})},e.prototype.deleteToken=function(e){var t=this;return"string"!=typeof e||0===e.length?Promise.reject(this.e.create(u.codes.INVALID_DELETE_TOKEN)):this.getTokenDetailsFromToken(e).then(function(e){if(!e)throw t.e.create(u.codes.DELETE_TOKEN_NOT_FOUND);return t.r().then(function(r){return new Promise(function(n,o){var i=r.transaction([p],"readwrite"),s=i.objectStore(p),a=s.delete(e.swScope);a.onerror=function(e){o(e.target.error)},a.onsuccess=function(r){if(0===r.target.result)return void o(t.e.create(u.codes.FAILED_TO_DELETE_TOKEN));n(e)}})})})},e}(),g=l,E="messagingSenderId",T=function(){function e(e){var t=this;if(this.e=new s.ErrorFactory("messaging","Messaging",u.map),!e.options[E]||"string"!=typeof e.options[E])throw this.e.create(u.codes.BAD_SENDER_ID);this.a=e.options[E],this.c=new g,this.app=e,this.INTERNAL={},this.INTERNAL.delete=function(){return t.delete}}return e.prototype.getToken=function(){var e=this,t=this.u();return"granted"!==t?"denied"===t?Promise.reject(this.e.create(u.codes.NOTIFICATIONS_BLOCKED)):Promise.resolve(null):this._().then(function(t){return e.c.getSavedToken(e.a,t).then(function(r){return r||e.c.createToken(e.a,t)})})},e.prototype.deleteToken=function(e){var t=this;return this.c.deleteToken(e).then(function(){return t._().then(function(e){if(e)return e.pushManager.getSubscription()}).then(function(e){if(e)return e.unsubscribe()})})},e.prototype._=function(){throw this.e.create(u.codes.SHOULD_BE_INHERITED)},e.prototype.requestPermission=function(){throw this.e.create(u.codes.AVAILABLE_IN_WINDOW)},e.prototype.useServiceWorker=function(e){throw this.e.create(u.codes.AVAILABLE_IN_WINDOW)},e.prototype.onMessage=function(e,t,r){throw this.e.create(u.codes.AVAILABLE_IN_WINDOW)},e.prototype.onTokenRefresh=function(e,t,r){throw this.e.create(u.codes.AVAILABLE_IN_WINDOW)},e.prototype.setBackgroundMessageHandler=function(e){throw this.e.create(u.codes.AVAILABLE_IN_SW)},e.prototype.delete=function(){return this.c.closeDatabase()},e.prototype.u=function(){return Notification.permission},e.prototype.getTokenManager=function(){return this.c},e}(),S=T,b={TYPE_OF_MSG:"firebase-messaging-msg-type",DATA:"firebase-messaging-msg-data"},v={PUSH_MSG_RECEIVED:"push-msg-received",NOTIFICATION_CLICKED:"notification-clicked"},I=function(e,t){return r={},r[b.TYPE_OF_MSG]=e,r[b.DATA]=t,r;var r},m={PARAMS:b,TYPES_OF_MSG:v,createNewMsg:I},y={path:"/firebase-messaging-sw.js",scope:"/firebase-cloud-messaging-push-scope"},N=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])};return function(t,r){function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),w=function(e){function t(t){var r=e.call(this,t)||this;return r.d=null,r.f=Object(s.createSubscribe)(function(e){r.d=e}),r.h=null,r.p=Object(s.createSubscribe)(function(e){r.h=e}),r.l(),r}return N(t,e),t.prototype.getToken=function(){var t=this;return this.g()?this.T().then(function(){return e.prototype.getToken.call(t)}):Promise.reject(this.e.create(u.codes.UNSUPPORTED_BROWSER))},t.prototype.T=function(){var e=this;if(this.S)return this.S;var t=document.querySelector('link[rel="manifest"]');return this.S=t?fetch(t.href).then(function(e){return e.json()}).catch(function(){return Promise.resolve()}).then(function(t){if(t&&t.gcm_sender_id&&"103953800507"!==t.gcm_sender_id)throw e.e.create(u.codes.INCORRECT_GCM_SENDER_ID)}):Promise.resolve(),this.S},t.prototype.requestPermission=function(){var e=this;return"granted"===Notification.permission?Promise.resolve():new Promise(function(t,r){var n=function(n){return"granted"===n?t():r("denied"===n?e.e.create(u.codes.PERMISSION_BLOCKED):e.e.create(u.codes.PERMISSION_DEFAULT))},o=Notification.requestPermission(function(e){o||n(e)});o&&o.then(n)})},t.prototype.useServiceWorker=function(e){if(!(e instanceof ServiceWorkerRegistration))throw this.e.create(u.codes.SW_REGISTRATION_EXPECTED);if(void 0!==this.b)throw this.e.create(u.codes.USE_SW_BEFORE_GET_TOKEN);this.b=e},t.prototype.onMessage=function(e,t,r){return this.f(e,t,r)},t.prototype.onTokenRefresh=function(e,t,r){return this.p(e,t,r)},t.prototype.v=function(e){var t=this,r=e.installing||e.waiting||e.active;return new Promise(function(n,o){if(!r)return void o(t.e.create(u.codes.NO_SW_IN_REG));if("activated"===r.state)return void n(e);if("redundant"===r.state)return void o(t.e.create(u.codes.SW_REG_REDUNDANT));var i=function(){if("activated"===r.state)n(e);else{if("redundant"!==r.state)return;o(t.e.create(u.codes.SW_REG_REDUNDANT))}r.removeEventListener("statechange",i)};r.addEventListener("statechange",i)})},t.prototype._=function(){var e=this;return this.b?this.v(this.b):(this.b=null,navigator.serviceWorker.register(y.path,{scope:y.scope}).catch(function(t){throw e.e.create(u.codes.FAILED_DEFAULT_REGISTRATION,{browserErrorMessage:t.message})}).then(function(t){return e.v(t).then(function(){return e.b=t,t.update(),t})}))},t.prototype.l=function(){var e=this;"serviceWorker"in navigator&&navigator.serviceWorker.addEventListener("message",function(t){if(t.data&&t.data[m.PARAMS.TYPE_OF_MSG]){var r=t.data;switch(r[m.PARAMS.TYPE_OF_MSG]){case m.TYPES_OF_MSG.PUSH_MSG_RECEIVED:case m.TYPES_OF_MSG.NOTIFICATION_CLICKED:var n=r[m.PARAMS.DATA];e.d.next(n)}}},!1)},t.prototype.g=function(){return"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")},t}(S),k=w,O=this&&this.__extends||function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])};return function(t,r){function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),D=function(e){function t(t){var r=e.call(this,t)||this;return self.addEventListener("push",function(e){return r.I(e)},!1),self.addEventListener("pushsubscriptionchange",function(e){return r.m(e)},!1),self.addEventListener("notificationclick",function(e){return r.y(e)},!1),r.N=null,r}return O(t,e),t.prototype.I=function(e){var t,r=this;try{t=e.data.json()}catch(e){return}var n=this.w().then(function(e){if(e){if(t.notification||r.N)return r.k(t)}else{var n=r.O(t);if(n){var o=n.title||"";return self.registration.showNotification(o,n)}if(r.N)return r.N(t)}});e.waitUntil(n)},t.prototype.m=function(e){var t=this,r=this.getToken().then(function(e){if(!e)throw t.e.create(u.codes.NO_FCM_TOKEN_FOR_RESUBSCRIBE);var r=null,n=t.getTokenManager();return n.getTokenDetailsFromToken(e).then(function(e){if(!(r=e))throw t.e.create(u.codes.INVALID_SAVED_TOKEN);return self.registration.pushManager.subscribe(h.SUBSCRIPTION_OPTIONS)}).then(function(e){return n.subscribeToFCM(r.fcmSenderId,e,r.fcmPushSet)}).catch(function(e){return n.deleteToken(r.fcmToken).then(function(){throw t.e.create(u.codes.UNABLE_TO_RESUBSCRIBE,{message:e})})})});e.waitUntil(r)},t.prototype.y=function(e){var t=this;if(e.notification&&e.notification.data&&e.notification.data.FCM_MSG){e.stopImmediatePropagation(),e.notification.close();var r=e.notification.data.FCM_MSG,n=r.notification.click_action;if(n){var o=this.D(n).then(function(e){return e||self.clients.openWindow(n)}).then(function(e){if(e){r.notification,delete r.notification;var n=m.createNewMsg(m.TYPES_OF_MSG.NOTIFICATION_CLICKED,r);return t.A(e,n)}});e.waitUntil(o)}}},t.prototype.O=function(e){if(e&&"object"==typeof e.notification){var t=Object.assign({},e.notification);return t.data=(r={},r.FCM_MSG=e,r),t;var r}},t.prototype.setBackgroundMessageHandler=function(e){if(e&&"function"!=typeof e)throw this.e.create(u.codes.BG_HANDLER_FUNCTION_EXPECTED);this.N=e},t.prototype.D=function(e){var t=new URL(e).href;return self.clients.matchAll({type:"window",includeUncontrolled:!0}).then(function(e){for(var r=null,n=0;n>6,128|63&r);else if(55296==(64512&r)){var o=n>18,128|r>>12&63,128|r>>6&63,128|63&r)}else e.push(239,191,189)}else 56320==(64512&r)?e.push(239,191,189):e.push(224|r>>12,128|r>>6&63,128|63&r)}return new Uint8Array(e)}function T(t){var e;try{e=decodeURIComponent(t)}catch(t){throw y(ne.DATA_URL,"Malformed data URL.")}return U(e)}function A(t,e){switch(t){case ne.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r){var o=n?"-":"_";throw y(t,"Invalid character '"+o+"' found: is it base64url encoded?")}break;case ne.BASE64URL:var i=-1!==e.indexOf("+"),a=-1!==e.indexOf("/");if(i||a){var o=i?"+":"/";throw y(t,"Invalid character '"+o+"' found: is it base64 encoded?")}e=e.replace(/-/g,"+").replace(/_/g,"/")}var s;try{s=atob(e)}catch(e){throw y(t,"Invalid character found")}for(var u=new Uint8Array(s.length),c=0;c=e.length)&&t.substring(t.length-e.length)===e}function S(t){switch(t){case ae.RUNNING:case ae.PAUSING:case ae.CANCELING:return se.RUNNING;case ae.PAUSED:return se.PAUSED;case ae.SUCCESS:return se.SUCCESS;case ae.CANCELED:return se.CANCELED;case ae.ERROR:default:return se.ERROR}}function k(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function I(t,e){for(var n in t)k(t,n)&&e(n,t[n])}function L(t){if(null==t)return{};var e={};return I(t,function(t,n){e[t]=n}),e}function P(t){return new Promise(t)}function x(t){return Promise.resolve(t)}function D(t){return Promise.reject(t)}function M(t){return null!=t}function W(t){return void 0!==t}function B(t){return"function"==typeof t}function G(t){return"object"==typeof t}function j(t){return G(t)&&null!==t}function q(t){return G(t)&&!Array.isArray(t)}function F(t){return"string"==typeof t||t instanceof String}function H(t){return"number"==typeof t||t instanceof Number}function z(t){return X()&&t instanceof Blob}function X(){return"undefined"!=typeof Blob}function V(t){var e;try{e=JSON.parse(t)}catch(t){return null}return q(e)?e:null}function K(t){if(0==t.length)return null;var e=t.lastIndexOf("/");return-1===e?"":t.slice(0,e)}function Z(t,e){var n=e.split("/").filter(function(t){return t.length>0}).join("/");return 0===t.length?n:t+"/"+n}function J(t){var e=t.lastIndexOf("/",t.length-2);return-1===e?t:t.slice(e+1)}function Q(t){return Vt+Zt+t}function Y(t){return Kt+Zt+t}function $(t){return Vt+Jt+t}function tt(t){var e=encodeURIComponent,n="?";return I(t,function(t,r){var o=e(t)+"="+e(r);n=n+o+"&"}),n=n.slice(0,-1)}function et(t,e){return e}function nt(t){return!F(t)||t.length<2?t:(t=t,J(t))}function rt(){function t(t,e){return nt(e)}function e(t,e){return M(e)?+e:e}function n(t,e){if(!(F(e)&&e.length>0))return[];var n=encodeURIComponent;return e.split(",").map(function(e){var r=t.bucket,o=t.fullPath;return Y("/b/"+n(r)+"/o/"+n(o))+tt({alt:"media",token:e})})}if(pe)return pe;var r=[];r.push(new he("bucket")),r.push(new he("generation")),r.push(new he("metageneration")),r.push(new he("name","fullPath",!0));var o=new he("name");o.xform=t,r.push(o);var i=new he("size");return i.xform=e,r.push(i),r.push(new he("timeCreated")),r.push(new he("updated")),r.push(new he("md5Hash",null,!0)),r.push(new he("cacheControl",null,!0)),r.push(new he("contentDisposition",null,!0)),r.push(new he("contentEncoding",null,!0)),r.push(new he("contentLanguage",null,!0)),r.push(new he("contentType",null,!0)),r.push(new he("metadata","customMetadata",!0)),r.push(new he("downloadTokens","downloadURLs",!1,n)),pe=r}function ot(t,e){function n(){var n=t.bucket,r=t.fullPath,o=new le(n,r);return e.makeStorageReference(o)}Object.defineProperty(t,"ref",{get:n})}function it(t,e,n){var r={};r.type="file";for(var o=n.length,i=0;i=0))throw"Expected a number 0 or greater."}return new fe(t)}function _t(t,e){function n(e){if(!(null===e||M(e)&&e instanceof Object))throw"Expected an Object.";void 0!==t&&null!==t&&t(e)}return new fe(n,e)}function vt(t){function e(t){if(null!==t&&!B(t))throw"Expected a Function."}return new fe(e,t)}function bt(){return"undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0}function mt(){for(var t=[],e=0;e0&&(h=Math.min(h,o));var p=c.current,_=p+h,v=h===l?"upload, finalize":"upload",b={"X-Goog-Upload-Command":v,"X-Goog-Upload-Offset":c.current},m=r.slice(p,_);if(null===m)throw f();var g=e.maxUploadRetryTime(),y=new _e(n,"POST",u,g);return y.headers=b,y.body=m.uploadData(),y.progressCallback=s||null,y.errorHandler=Tt(t),y}function Mt(t){return function(){for(var e=[],n=0;n0&&(t.Authorization="Firebase "+e)}function jt(t){var e=void 0!==Xt.default?Xt.default.SDK_VERSION:"AppManager";t["X-Firebase-Storage-Version"]="webjs/"+e}function qt(t,e,n){var r=tt(t.urlParams),o=t.url+r,i=L(t.headers);return Gt(i,e),jt(i),new Ue(o,t.method,i,t.body,t.successCodes,t.additionalRetryCodes,t.handler,t.errorHandler,t.timeout,t.progressCallback,n)}function Ft(t,e,n){return new Ae(t,new ce,n)}function Ht(t){var e={TaskState:se,TaskEvent:ie,StringFormat:ne,Storage:Ae,Reference:ye};t.INTERNAL.registerService(Oe,Ft,e,void 0,!0)}Object.defineProperty(e,"__esModule",{value:!0});var zt,Xt=n(6),Vt="https://firebasestorage.googleapis.com",Kt="https://firebasestorage.googleapis.com",Zt="/v0",Jt="/v0",Qt=12e4,Yt=6e4,$t=-9007199254740991,te=function(){function t(t,e){this.t=r(t),this.e="Firebase Storage: "+e,this.n=null,this.r="FirebaseError"}return t.prototype.codeProp=function(){return this.code},t.prototype.codeEquals=function(t){return r(t)===this.codeProp()},t.prototype.serverResponseProp=function(){return this.n},t.prototype.setServerResponseProp=function(t){this.n=t},Object.defineProperty(t.prototype,"name",{get:function(){return this.r},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"code",{get:function(){return this.t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"message",{get:function(){return this.e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"serverResponse",{get:function(){return this.n},enumerable:!0,configurable:!0}),t}(),ee={UNKNOWN:"unknown",OBJECT_NOT_FOUND:"object-not-found",BUCKET_NOT_FOUND:"bucket-not-found",PROJECT_NOT_FOUND:"project-not-found",QUOTA_EXCEEDED:"quota-exceeded",UNAUTHENTICATED:"unauthenticated",UNAUTHORIZED:"unauthorized",RETRY_LIMIT_EXCEEDED:"retry-limit-exceeded",INVALID_CHECKSUM:"invalid-checksum",CANCELED:"canceled",INVALID_EVENT_NAME:"invalid-event-name",INVALID_URL:"invalid-url",INVALID_DEFAULT_BUCKET:"invalid-default-bucket",NO_DEFAULT_BUCKET:"no-default-bucket",CANNOT_SLICE_BLOB:"cannot-slice-blob",SERVER_FILE_WRONG_SIZE:"server-file-wrong-size",NO_DOWNLOAD_URL:"no-download-url",INVALID_ARGUMENT:"invalid-argument",INVALID_ARGUMENT_COUNT:"invalid-argument-count",APP_DELETED:"app-deleted",INVALID_ROOT_OPERATION:"invalid-root-operation",INVALID_FORMAT:"invalid-format",INTERNAL_ERROR:"internal-error"},ne={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"},re=function(){function t(t,e){this.data=t,this.contentType=e||null}return t}(),oe=function(){function t(t){this.base64=!1,this.contentType=null;var e=t.match(/^data:([^,]+)?,/);if(null===e)throw y(ne.DATA_URL,"Must be formatted 'data:[][;base64],");var n=e[1]||null;null!=n&&(this.base64=C(n,";base64"),this.contentType=this.base64?n.substring(0,n.length-7):n),this.rest=t.substring(t.indexOf(",")+1)}return t}(),ie={STATE_CHANGED:"state_changed"},ae={RUNNING:"running",PAUSING:"pausing",PAUSED:"paused",SUCCESS:"success",CANCELING:"canceling",CANCELED:"canceled",ERROR:"error"},se={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};!function(t){t[t.NO_ERROR=0]="NO_ERROR",t[t.NETWORK_ERROR=1]="NETWORK_ERROR",t[t.ABORT=2]="ABORT"}(zt||(zt={}));var ue=function(){function t(){var t=this;this.o=!1,this.i=new XMLHttpRequest,this.a=zt.NO_ERROR,this.s=P(function(e,n){t.i.addEventListener("abort",function(n){t.a=zt.ABORT,e(t)}),t.i.addEventListener("error",function(n){t.a=zt.NETWORK_ERROR,e(t)}),t.i.addEventListener("load",function(n){e(t)})})}return t.prototype.send=function(t,e,n,r){var o=this;if(this.o)throw R("cannot .send() more than once");return this.o=!0,this.i.open(e,t,!0),M(r)&&I(r,function(t,e){o.i.setRequestHeader(t,""+e)}),M(n)?this.i.send(n):this.i.send(),this.s},t.prototype.getErrorCode=function(){if(!this.o)throw R("cannot .getErrorCode() before sending");return this.a},t.prototype.getStatus=function(){if(!this.o)throw R("cannot .getStatus() before sending");try{return this.i.status}catch(t){return-1}},t.prototype.getResponseText=function(){if(!this.o)throw R("cannot .getResponseText() before sending");return this.i.responseText},t.prototype.abort=function(){this.i.abort()},t.prototype.getResponseHeader=function(t){return this.i.getResponseHeader(t)},t.prototype.addUploadProgressListener=function(t){M(this.i.upload)&&this.i.upload.addEventListener("progress",t)},t.prototype.removeUploadProgressListener=function(t){M(this.i.upload)&&this.i.upload.removeEventListener("progress",t)},t}(),ce=function(){function t(){}return t.prototype.createXhrIo=function(){return new ue},t}(),le=function(){function t(t,e){this.bucket=t,this.u=e}return Object.defineProperty(t.prototype,"path",{get:function(){return this.u},enumerable:!0,configurable:!0}),t.prototype.fullServerUrl=function(){var t=encodeURIComponent;return"/b/"+t(this.bucket)+"/o/"+t(this.path)},t.prototype.bucketOnlyServerUrl=function(){return"/b/"+encodeURIComponent(this.bucket)+"/o"},t.makeFromBucketSpec=function(e){var n;try{n=t.makeFromUrl(e)}catch(n){return new t(e,"")}if(""===n.path)return n;throw p(e)},t.makeFromUrl=function(e){function n(t){"/"===t.path.charAt(t.path.length-1)&&(t.u=t.u.slice(0,-1))}function r(t){t.u=decodeURIComponent(t.path)}for(var o=null,i=RegExp("^gs://([A-Za-z0-9.\\-]+)(/(.*))?$","i"),a={bucket:1,path:3},s=RegExp("^https?://firebasestorage\\.googleapis\\.com/v[A-Za-z0-9_]+/b/([A-Za-z0-9.\\-]+)/o(/([^?#]*).*)?$","i"),u={bucket:1,path:3},c=[{regex:i,indices:a,postModify:n},{regex:s,indices:u,postModify:r}],l=0;l262144},t.prototype.M=function(){this.k===ae.RUNNING&&null===this.m&&(this.C?null===this.b?this.G():this.f?this.j():this.d?this.q():this.F():this.H())},t.prototype.z=function(t){var e=this;this.U.getAuthToken().then(function(n){switch(e.k){case ae.RUNNING:t(n);break;case ae.CANCELING:e.P(ae.CANCELED);break;case ae.PAUSING:e.P(ae.PAUSED)}})},t.prototype.G=function(){var t=this;this.z(function(e){var n=Pt(t.U,t.T,t.O,t.A,t.N),r=t.U.makeRequest(n,e);t.m=r,r.getPromise().then(function(e){t.m=null,t.b=e,t.f=!1,t.L()},t.I)})},t.prototype.j=function(){var t=this,e=this.b;this.z(function(n){var r=xt(t.U,t.T,e,t.A),o=t.U.makeRequest(r,n);t.m=o,o.getPromise().then(function(e){e=e,t.m=null,t.B(e.current),t.f=!1,e.finalized&&(t.d=!0),t.L()},t.I)})},t.prototype.F=function(){var t=this,e=262144*this.g,n=new ve(this.p,this.A.size()),r=this.b;this.z(function(o){var i;try{i=Dt(t.T,t.U,r,t.A,e,t.O,n,t.W())}catch(e){return t.v=e,void t.P(ae.ERROR)}var a=t.U.makeRequest(i,o);t.m=a,a.getPromise().then(function(e){t.X(),t.m=null,t.B(e.current),e.finalized?(t.N=e.metadata,t.P(ae.SUCCESS)):t.L()},t.I)})},t.prototype.X=function(){262144*this.g<33554432&&(this.g*=2)},t.prototype.q=function(){var t=this;this.z(function(e){var n=Nt(t.U,t.T,t.O),r=t.U.makeRequest(n,e);t.m=r,r.getPromise().then(function(e){t.m=null,t.N=e,t.P(ae.SUCCESS)},t.x)})},t.prototype.H=function(){var t=this;this.z(function(e){var n=It(t.U,t.T,t.O,t.A,t.N),r=t.U.makeRequest(n,e);t.m=r,r.getPromise().then(function(e){t.m=null,t.N=e,t.B(t.A.size()),t.P(ae.SUCCESS)},t.I)})},t.prototype.B=function(t){var e=this.p;this.p=t,this.p!==e&&this.V()},t.prototype.P=function(t){if(this.k!==t)switch(t){case ae.CANCELING:case ae.PAUSING:this.k=t,null!==this.m&&this.m.cancel();break;case ae.RUNNING:var e=this.k===ae.PAUSED;this.k=t,e&&(this.V(),this.M());break;case ae.PAUSED:this.k=t,this.V();break;case ae.CANCELED:this.v=l(),this.k=t,this.V();break;case ae.ERROR:case ae.SUCCESS:this.k=t,this.V()}},t.prototype.L=function(){switch(this.k){case ae.PAUSING:this.P(ae.PAUSED);break;case ae.CANCELING:this.P(ae.CANCELED);break;case ae.RUNNING:this.M()}},Object.defineProperty(t.prototype,"snapshot",{get:function(){var t=S(this.k);return new me(this.p,this.A.size(),t,this.N,this,this.w)},enumerable:!0,configurable:!0}),t.prototype.on=function(t,e,n,r){function o(e){if(t!==ie.STATE_CHANGED)throw"Expected one of the event types: ["+ie.STATE_CHANGED+"]."}function i(t){try{return void c(t)}catch(t){}try{if(l(t),!(W(t.next)||W(t.error)||W(t.complete)))throw"";return}catch(t){throw u}}function a(t){function e(e,n,o){null!==t&&ct("on",t,arguments);var i=new be(e,n,r);return h.K(i),function(){h.Z(i)}}return e}function s(t){if(null===t)throw u;i(t)}void 0===e&&(e=void 0),void 0===n&&(n=void 0),void 0===r&&(r=void 0);var u="Expected a function or an Object with one of `next`, `error`, `complete` properties.",c=vt(!0).validator,l=_t(null,!0).validator;ct("on",[ht(o),_t(i,!0),vt(!0),vt(!0)],arguments);var h=this,p=[_t(s),vt(!0),vt(!0)];return W(e)||W(n)||W(r)?a(null)(e,n,r):a(p)},t.prototype.then=function(t,e){return this.D.then(t,e)},t.prototype.catch=function(t){return this.then(null,t)},t.prototype.K=function(t){this._.push(t),this.J(t)},t.prototype.Z=function(t){Et(this._,t)},t.prototype.V=function(){var t=this;this.Q(),Rt(this._).forEach(function(e){t.J(e)})},t.prototype.Q=function(){if(null!==this.y){var t=!0;switch(S(this.k)){case se.SUCCESS:Mt(this.y.bind(null,this.snapshot))();break;case se.CANCELED:case se.ERROR:Mt(this.R.bind(null,this.v))();break;default:t=!1}t&&(this.y=null,this.R=null)}},t.prototype.J=function(t){switch(S(this.k)){case se.RUNNING:case se.PAUSED:null!==t.next&&Mt(t.next.bind(t,this.snapshot))();break;case se.SUCCESS:null!==t.complete&&Mt(t.complete.bind(t))();break;case se.CANCELED:case se.ERROR:null!==t.error&&Mt(t.error.bind(t,this.v))();break;default:null!==t.error&&Mt(t.error.bind(t,this.v))()}},t.prototype.resume=function(){ct("resume",[],arguments);var t=this.k===ae.PAUSED||this.k===ae.PAUSING;return t&&this.P(ae.RUNNING),t},t.prototype.pause=function(){ct("pause",[],arguments);var t=this.k===ae.RUNNING;return t&&this.P(ae.PAUSING),t},t.prototype.cancel=function(){ct("cancel",[],arguments);var t=this.k===ae.RUNNING||this.k===ae.PAUSING;return t&&this.P(ae.CANCELING),t},t}(),ye=function(){function t(t,e){this.authWrapper=t,this.location=e instanceof le?e:le.makeFromUrl(e)}return t.prototype.toString=function(){return ct("toString",[],arguments),"gs://"+this.location.bucket+"/"+this.location.path},t.prototype.newRef=function(e,n){return new t(e,n)},t.prototype.mappings=function(){return rt()},t.prototype.child=function(t){ct("child",[ht()],arguments);var e=Z(this.location.path,t),n=new le(this.location.bucket,e);return this.newRef(this.authWrapper,n)},Object.defineProperty(t.prototype,"parent",{get:function(){var t=K(this.location.path);if(null===t)return null;var e=new le(this.location.bucket,t);return this.newRef(this.authWrapper,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"root",{get:function(){var t=new le(this.location.bucket,"");return this.newRef(this.authWrapper,t)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bucket",{get:function(){return this.location.bucket},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fullPath",{get:function(){return this.location.path},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return J(this.location.path)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"storage",{get:function(){return this.authWrapper.service()},enumerable:!0,configurable:!0}),t.prototype.put=function(t,e){return void 0===e&&(e=null),ct("put",[pt(),ft(!0)],arguments),this.Y("put"),new ge(this,this.authWrapper,this.location,this.mappings(),new de(t),e)},t.prototype.putString=function(t,e,n){void 0===e&&(e=ne.RAW),ct("putString",[ht(),ht(E,!0),ft(!0)],arguments),this.Y("putString");var r=w(e,t),o=L(n);return!M(o.contentType)&&M(r.contentType)&&(o.contentType=r.contentType),new ge(this,this.authWrapper,this.location,this.mappings(),new de(r.data,!0),o)},t.prototype.delete=function(){ct("delete",[],arguments),this.Y("delete");var t=this;return this.authWrapper.getAuthToken().then(function(e){var n=Ct(t.authWrapper,t.location);return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.getMetadata=function(){ct("getMetadata",[],arguments),this.Y("getMetadata");var t=this;return this.authWrapper.getAuthToken().then(function(e){var n=Nt(t.authWrapper,t.location,t.mappings());return t.authWrapper.makeRequest(n,e).getPromise()})},t.prototype.updateMetadata=function(t){ct("updateMetadata",[ft()],arguments),this.Y("updateMetadata");var e=this;return this.authWrapper.getAuthToken().then(function(n){var r=Ot(e.authWrapper,e.location,t,e.mappings());return e.authWrapper.makeRequest(r,n).getPromise()})},t.prototype.getDownloadURL=function(){return ct("getDownloadURL",[],arguments),this.Y("getDownloadURL"),this.getMetadata().then(function(t){var e=t.downloadURLs[0];if(M(e))return e;throw _()})},t.prototype.Y=function(t){if(""===this.location.path)throw g(t)},t}(),Re=function(){function t(t){this.D=D(t)}return t.prototype.getPromise=function(){return this.D},t.prototype.cancel=function(t){void 0===t&&(t=!1)},t}(),Ee=function(){function t(){this.$={},this.tt=$t}return t.prototype.addRequest=function(t){function e(){delete r.$[n]}var n=this.tt;this.tt++,this.$[n]=t;var r=this;t.getPromise().then(e,e)},t.prototype.clear=function(){I(this.$,function(t,e){e&&e.cancel(!0)}),this.$={}},t}(),we=function(){function t(e,n,r,o,i){if(this.et=null,this.nt=!1,this.rt=e,null!==this.rt){var a=this.rt.options;M(a)&&(this.et=t.ot(a))}this.it=n,this.at=r,this.st=i,this.ut=o,this.ct=Qt,this.lt=Yt,this.ht=new Ee}return t.ot=function(t){var e=t.storageBucket||null;return null==e?null:le.makeFromBucketSpec(e).bucket},t.prototype.getAuthToken=function(){return null!==this.rt&&M(this.rt.INTERNAL)&&M(this.rt.INTERNAL.getToken)?this.rt.INTERNAL.getToken().then(function(t){return null!==t?t.accessToken:null},function(t){return null}):x(null)},t.prototype.bucket=function(){if(this.nt)throw m();return this.et},t.prototype.service=function(){return this.ut},t.prototype.makeStorageReference=function(t){return this.it(this,t)},t.prototype.makeRequest=function(t,e){if(this.nt)return new Re(m());var n=this.at(t,e,this.st);return this.ht.addRequest(n),n},t.prototype.deleteApp=function(){this.nt=!0,this.rt=null,this.ht.clear()},t.prototype.maxUploadRetryTime=function(){return this.lt},t.prototype.setMaxUploadRetryTime=function(t){this.lt=t},t.prototype.maxOperationRetryTime=function(){return this.ct},t.prototype.setMaxOperationRetryTime=function(t){this.ct=t},t}(),Ue=function(){function t(t,e,n,r,o,i,a,s,u,c,l){this.pt=null,this.ft=null,this.y=null,this.R=null,this.dt=!1,this._t=!1,this.vt=t,this.bt=e,this.mt=n,this.gt=r,this.yt=o.slice(),this.Rt=i.slice(),this.Et=a,this.wt=s,this.Ut=c,this.Tt=u,this.st=l;var h=this;this.D=P(function(t,e){h.y=t,h.R=e,h.M()})}return t.prototype.M=function(){function t(t,e){function r(t){var e=t.loaded,r=t.lengthComputable?t.total:-1;null!==n.Ut&&n.Ut(e,r)}if(e)return void t(!1,new Te(!1,null,!0));var o=n.st.createXhrIo();n.pt=o,null!==n.Ut&&o.addUploadProgressListener(r),o.send(n.vt,n.bt,n.gt,n.mt).then(function(e){null!==n.Ut&&e.removeUploadProgressListener(r),n.pt=null,e=e;var o=e.getErrorCode()===zt.NO_ERROR,i=e.getStatus();if(!o||n.At(i)){var a=e.getErrorCode()===zt.ABORT;return void t(!1,new Te(!1,null,a))}var s=yt(n.yt,i);t(!0,new Te(s,e))})}function e(t,e){var r=n.y,i=n.R,a=e.xhr;if(e.wasSuccessCode)try{var s=n.Et(a,a.getResponseText());W(s)?r(s):r()}catch(t){i(t)}else if(null!==a){var u=o();u.setServerResponseProp(a.getResponseText()),i(n.wt?n.wt(a,u):u)}else if(e.canceled){var u=n._t?m():l();i(u)}else{var u=c();i(u)}}var n=this;this.dt?e(!1,new Te(!1,null,!0)):this.ft=Wt(t,e,this.Tt)},t.prototype.getPromise=function(){return this.D},t.prototype.cancel=function(t){this.dt=!0,this._t=t||!1,null!==this.ft&&Bt(this.ft),null!==this.pt&&this.pt.abort()},t.prototype.At=function(t){var e=t>=500&&t<600,n=[408,429],r=yt(n,t),o=yt(this.Rt,t);return e||r||o},t}(),Te=function(){function t(t,e,n){this.wasSuccessCode=t,this.xhr=e,this.canceled=!!n}return t}(),Ae=function(){function t(t,e,n){function r(t,e){return new ye(t,e)}if(this.et=null,this.U=new we(t,r,qt,this,e),this.rt=t,null!=n)this.et=le.makeFromBucketSpec(n);else{var o=this.U.bucket();null!=o&&(this.et=new le(o,""))}this.Nt=new Ne(this)}return t.prototype.ref=function(t){function e(t){if(/^[A-Za-z]+:\/\//.test(t))throw"Expected child path but got a URL, use refFromURL instead."}if(ct("ref",[ht(e,!0)],arguments),null==this.et)throw Error("No Storage Bucket defined in Firebase Options.");var n=new ye(this.U,this.et);return null!=t?n.child(t):n},t.prototype.refFromURL=function(t){function e(t){if(!/^[A-Za-z]+:\/\//.test(t))throw"Expected full URL but got a child path, use ref instead.";try{le.makeFromUrl(t)}catch(t){throw"Expected valid full URL but got an invalid one."}}return ct("refFromURL",[ht(e,!1)],arguments),new ye(this.U,t)},Object.defineProperty(t.prototype,"maxUploadRetryTime",{get:function(){return this.U.maxUploadRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxUploadRetryTime=function(t){ct("setMaxUploadRetryTime",[dt()],arguments),this.U.setMaxUploadRetryTime(t)},Object.defineProperty(t.prototype,"maxOperationRetryTime",{get:function(){return this.U.maxOperationRetryTime()},enumerable:!0,configurable:!0}),t.prototype.setMaxOperationRetryTime=function(t){ct("setMaxOperationRetryTime",[dt()],arguments),this.U.setMaxOperationRetryTime(t)},Object.defineProperty(t.prototype,"app",{get:function(){return this.rt},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"INTERNAL",{get:function(){return this.Nt},enumerable:!0,configurable:!0}),t}(),Ne=function(){function t(t){this.ut=t}return t.prototype.delete=function(){return this.ut.U.deleteApp(),x(void 0)},t}();e.registerStorage=Ht;var Oe="storage";Ht(Xt.default)}},[118])}catch(t){throw Error("Cannot instantiate firebase-storage.js - be sure to load firebase-app.js first.")} + +//# sourceMappingURL=firebase.js.map + +/*! + * @license Firebase v4.8.1 + * Build: rev-d8c20f0 + * Terms: https://firebase.google.com/terms/ + */ +try{webpackJsonpFirebase([1],{113:function(t,e,n){n(114)},114:function(t,e,n){"use strict";function r(){return Kt}function o(t){Kt=t}function i(t,e){for(var n=[],r=2;rr)throw new zt(Ht.INVALID_ARGUMENT,"Function "+t+"() requires between "+n+" and "+r+" arguments, but was called with "+P(e.length,"argument")+".")}function I(t,e,n,r){if(!(e instanceof Array)||e.length20&&(t=t.substring(0,20)+"..."),JSON.stringify(t);if("number"==typeof t||"boolean"==typeof t)return""+t;if("object"==typeof t){if(t instanceof Array)return"an array";var e=A(t);return e?"a custom "+e+" object":"an object"}return"function"==typeof t?"a function":u("Unknown wrong type: "+typeof t)}function A(t){if(t.constructor){var e=/function\s+([^\s(]+)\s*\(/,n=e.exec(""+t.constructor);if(n&&n.length>1)return n[1]}return null}function R(t,e,n){if(void 0===n)throw new zt(Ht.INVALID_ARGUMENT,"Function "+t+"() requires a valid "+_(e)+" argument, but it was undefined.")}function O(t,e,n){y(e,function(e,r){if(n.indexOf(e)<0)throw new zt(Ht.INVALID_ARGUMENT,"Unknown option '"+e+"' passed to function "+t+"(). Available options: "+n.join(", "))})}function M(t,e,n,r){var o=N(r);return new zt(Ht.INVALID_ARGUMENT,"Function "+t+"() requires its "+_(n)+" argument to be a "+e+", but it was: "+o)}function _(t){switch(t){case 1:return"first";case 2:return"second";case 3:return"third";default:return t+"th"}}function P(t,e){return t+" "+e+(1===t?"":"s")}function L(t,e){return te?1:0}function x(t,e){return null!==t&&void 0!==t?!(!e||!t.equals(e)):t===e}function B(t,e){if(t.length!==e.length)return!1;for(var n=0;ne?1:t===e?0:isNaN(t)?isNaN(e)?0:-1:1}function Q(t,e){return t===e?0!==t||1/t==1/e:t!==t&&e!==e}function K(t){return null===t||void 0===t}function W(t){return Pe(t)&&t<=_e&&t>=Me}function G(t,e,n){if(n.equals(ve.INSTANCE)){if(e!==xe.EQUAL)throw new zt(Ht.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on null.");return new Ue(t)}if(n.equals(Te.NAN)){if(e!==xe.EQUAL)throw new zt(Ht.INVALID_ARGUMENT,"Invalid query. You can only perform equals comparisons on NaN.");return new Fe(t)}return new Be(t,e,n)}function H(t){switch(t){case Ht.OK:return u("Treated status OK as error");case Ht.CANCELLED:case Ht.UNKNOWN:case Ht.DEADLINE_EXCEEDED:case Ht.RESOURCE_EXHAUSTED:case Ht.INTERNAL:case Ht.UNAVAILABLE:case Ht.UNAUTHENTICATED:return!1;case Ht.INVALID_ARGUMENT:case Ht.NOT_FOUND:case Ht.ALREADY_EXISTS:case Ht.PERMISSION_DENIED:case Ht.FAILED_PRECONDITION:case Ht.ABORTED:case Ht.OUT_OF_RANGE:case Ht.UNIMPLEMENTED:case Ht.DATA_LOSS:return!0;default:return u("Unknown status code: "+t)}}function z(t){var e=en[t];if(void 0!==e)return X(e)}function X(t){if(void 0===t)return a("GRPC error has no .code"),Ht.UNKNOWN;switch(t){case en.OK:return Ht.OK;case en.CANCELLED:return Ht.CANCELLED;case en.UNKNOWN:return Ht.UNKNOWN;case en.DEADLINE_EXCEEDED:return Ht.DEADLINE_EXCEEDED;case en.RESOURCE_EXHAUSTED:return Ht.RESOURCE_EXHAUSTED;case en.INTERNAL:return Ht.INTERNAL;case en.UNAVAILABLE:return Ht.UNAVAILABLE;case en.UNAUTHENTICATED:return Ht.UNAUTHENTICATED;case en.INVALID_ARGUMENT:return Ht.INVALID_ARGUMENT;case en.NOT_FOUND:return Ht.NOT_FOUND;case en.ALREADY_EXISTS:return Ht.ALREADY_EXISTS;case en.PERMISSION_DENIED:return Ht.PERMISSION_DENIED;case en.FAILED_PRECONDITION:return Ht.FAILED_PRECONDITION;case en.ABORTED:return Ht.ABORTED;case en.OUT_OF_RANGE:return Ht.OUT_OF_RANGE;case en.UNIMPLEMENTED:return Ht.UNIMPLEMENTED;case en.DATA_LOSS:return Ht.DATA_LOSS;default:return u("Unknown status code: "+t)}}function Y(t){if(void 0===t)return en.OK;switch(t){case Ht.OK:return en.OK;case Ht.CANCELLED:return en.CANCELLED;case Ht.UNKNOWN:return en.UNKNOWN;case Ht.DEADLINE_EXCEEDED:return en.DEADLINE_EXCEEDED;case Ht.RESOURCE_EXHAUSTED:return en.RESOURCE_EXHAUSTED;case Ht.INTERNAL:return en.INTERNAL;case Ht.UNAVAILABLE:return en.UNAVAILABLE;case Ht.UNAUTHENTICATED:return en.UNAUTHENTICATED;case Ht.INVALID_ARGUMENT:return en.INVALID_ARGUMENT;case Ht.NOT_FOUND:return en.NOT_FOUND;case Ht.ALREADY_EXISTS:return en.ALREADY_EXISTS;case Ht.PERMISSION_DENIED:return en.PERMISSION_DENIED;case Ht.FAILED_PRECONDITION:return en.FAILED_PRECONDITION;case Ht.ABORTED:return en.ABORTED;case Ht.OUT_OF_RANGE:return en.OUT_OF_RANGE;case Ht.UNIMPLEMENTED:return en.UNIMPLEMENTED;case Ht.DATA_LOSS:return en.DATA_LOSS;default:return u("Unknown status code: "+t)}}function J(t){switch(t){case 200:return Ht.OK;case 400:return Ht.INVALID_ARGUMENT;case 401:return Ht.UNAUTHENTICATED;case 403:return Ht.PERMISSION_DENIED;case 404:return Ht.NOT_FOUND;case 409:return Ht.ABORTED;case 416:return Ht.OUT_OF_RANGE;case 429:return Ht.RESOURCE_EXHAUSTED;case 499:return Ht.CANCELLED;case 500:return Ht.UNKNOWN;case 501:return Ht.UNIMPLEMENTED;case 503:return Ht.UNAVAILABLE;case 504:return Ht.DEADLINE_EXCEEDED;default:return t>=200&&t<300?Ht.OK:t>=400&&t<500?Ht.FAILED_PRECONDITION:t>=500&&t<600?Ht.INTERNAL:Ht.UNKNOWN}}function $(){return fn}function Z(){return dn}function tt(){return pn}function et(){return yn}function nt(t,e){e.length>0&&(t.resumeToken=e)}function rt(t,e){c(!K(t),e+" is missing")}function ot(t){return"number"==typeof t?t:"string"==typeof t?parseInt(t,10):u("can't parse "+t)}function it(t,e,n){return e===n||!e&&n in t}function at(t){if(t.search(Bn)>=0)throw new zt(Ht.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not contain '~', '*', '/', '[', or ']'");try{return new(xn.bind.apply(xn,[void 0].concat(t.split("."))))}catch(e){throw new zt(Ht.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'")}}function st(t,e){var n=function(t){switch(t){case Un.Added:return 1;case Un.Modified:case Un.Metadata:return 2;case Un.Removed:return 0;default:return u("Unknown ChangeType: "+t)}};return n(t)-n(e)}function ut(t){for(var e="",n=0;n0&&(e=ht(e)),e=ct(t.get(n),e);return ht(e)}function ct(t,e){for(var n=e,r=t.length,o=0;o=2,"Invalid path "+t),2===e)return c(t.charAt(0)===cr&&t.charAt(1)===hr,"Non-empty path "+t+" had length 2"),oe.EMPTY_PATH;for(var n=e-2,r=[],o="",i=0;in)&&u('Invalid encoded resource path: "'+t+'"'),t.charAt(a+1)){case hr:var s=t.substring(i,a),h=void 0;0===o.length?h=s:(o+=s,h=o,o=""),r.push(h);break;case lr:o+=t.substring(i,a),o+="\0";break;case fr:o+=t.substring(i,a+1);break;default:u('Invalid encoded resource path: "'+t+'"')}i=a+2}return new oe(r)}function ft(t,e){c(0===e,"Unexpected upgrade from version "+e),t.createObjectStore(yr.store,{keyPath:yr.keyPath}),t.createObjectStore(mr.store,{keyPath:mr.keyPath}),t.createObjectStore(Ir.store,{keyPath:Ir.keyPath}).createIndex(Ir.documentTargetsIndex,Ir.documentTargetsKeyPath,{unique:!0}),t.createObjectStore(wr.store,{keyPath:wr.keyPath}).createIndex(wr.queryTargetsIndexName,wr.queryTargetsKeyPath,{unique:!0}),t.createObjectStore(gr.store),t.createObjectStore(br.store),t.createObjectStore(pr.store),t.createObjectStore(Tr.store)}function dt(t){return new Hn(function(e,n){t.onsuccess=function(t){var n=t.target.result;e(n)},t.onerror=function(t){n(t.target.error)}})}function pt(t){return c("string"==typeof t,"Persisting non-string stream token not supported."),t}function yt(t){return vt(t,mr.store)}function mt(t){return vt(t,gr.store)}function gt(t){return vt(t,yr.store)}function vt(t,e){return t instanceof Dr?t.store(e):u("Invalid transaction object provided!")}function bt(t){return Tt(t,wr.store)}function wt(t){return Tt(t,Tr.store)}function It(t){return Tt(t,Ir.store)}function Tt(t,e){return t instanceof Dr?t.store(e):u("Invalid transaction object provided!")}function Et(t){return t instanceof Dr?t.store(br.store):u("Invalid transaction object provided!")}function St(t){return t.path.toArray()}function Ct(t){return void 0!==t.documents}function Dt(t){if(!t)return new so;switch(t.type){case"gapi":return new ho(t.client,t.sessionIndex||"0");case"provider":return t.client;default:throw new zt(Ht.INVALID_ARGUMENT,"makeCredentialsProvider failed due to invalid credential type")}}function kt(t){return Nt(t,["next","error","complete"])}function Nt(t,e){if("object"!=typeof t||null===t)return!1;for(var n=t,r=0,o=e;r=0,"Index for document not found"),o=o.delete(n.doc.key)),n.type!==Un.Removed&&(o=o.add(n.doc),a=o.indexOf(n.doc.key)),{type:Ut(n.type),doc:r,oldIndex:i,newIndex:a}})}function Ut(t){switch(t){case Un.Added:return"added";case Un.Modified:case Un.Metadata:return"modified";case Un.Removed:return"removed";default:return u("Unknown change type: "+t)}}function Ft(t){t.INTERNAL.registerService("firestore",function(t){return new No(t)},g(Ko))}function Vt(t){Ft(t)}Object.defineProperty(e,"__esModule",{value:!0});var qt,jt=n(6),Qt=jt.default.SDK_VERSION;!function(t){t[t.DEBUG=0]="DEBUG",t[t.ERROR=1]="ERROR",t[t.SILENT=2]="SILENT"}(qt||(qt={}));var Kt=qt.ERROR,Wt=function(){function t(){}return t.setPlatform=function(e){t.platform&&u("Platform already defined"),t.platform=e},t.getPlatform=function(){return t.platform||u("Platform not set"),t.platform},t}(),Gt=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Ht={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"},zt=function(t){function e(e,n){var r=t.call(this,n)||this;return r.code=e,r.message=n,r.name="FirebaseError",r.toString=function(){return r.name+": [code="+r.code+"]: "+r.message},r}return Gt(e,t),e}(Error),Xt=function(){function t(){}return t.newId=function(){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e="",n=0;n<20;n++)e+=t.charAt(Math.floor(Math.random()*t.length));return c(20===e.length,"Invalid auto ID: "+e),e},t}(),Yt=function(){function t(t){q(),this.e=t}return t.fromBase64String=function(e){v("Blob.fromBase64String",arguments,1),T("Blob.fromBase64String","string",1,e),q();try{return new t(Wt.getPlatform().atob(e))}catch(t){throw new zt(Ht.INVALID_ARGUMENT,"Failed to construct Blob from Base64 string: "+t)}},t.fromUint8Array=function(e){if(v("Blob.fromUint8Array",arguments,1),V(),!(e instanceof Uint8Array))throw M("Blob.fromUint8Array","Uint8Array",1,e);return new t(Array.prototype.map.call(e,function(t){return String.fromCharCode(t)}).join(""))},t.prototype.toBase64=function(){return v("Blob.toBase64",arguments,0),q(),Wt.getPlatform().btoa(this.e)},t.prototype.toUint8Array=function(){v("Blob.toUint8Array",arguments,0),V();for(var t=new Uint8Array(this.e.length),e=0;e90)throw new zt(Ht.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+t);if(!isFinite(e)||e<-180||e>180)throw new zt(Ht.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+e);this._lat=t,this.d=e}return Object.defineProperty(t.prototype,"latitude",{get:function(){return this._lat},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"longitude",{get:function(){return this.d},enumerable:!0,configurable:!0}),t.prototype.n=function(t){return this._lat===t._lat&&this.d===t.d},t.prototype.r=function(t){return L(this._lat,t._lat)||L(this.d,t.d)},t}(),Zt=function(){function t(t,e,n,r){this.databaseId=t,this.persistenceKey=e,this.host=n,this.ssl=r}return t}(),te="(default)",ee=function(){function t(t,e){this.projectId=t,this.database=e||te}return Object.defineProperty(t.prototype,"isDefaultDatabase",{get:function(){return this.database===te},enumerable:!0,configurable:!0}),t.prototype.equals=function(e){return e instanceof t&&e.projectId===this.projectId&&e.database===this.database},t.prototype.compareTo=function(t){return L(this.projectId,t.projectId)||L(this.database,t.database)},t}(),ne=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),re=function(){function t(t,e,n){this.init(t,e,n)}return t.prototype.init=function(t,e,n){void 0===e?e=0:e>t.length&&u("offset "+e+" out of range "+t.length),void 0===n?n=t.length-e:n>t.length-e&&u("length "+n+" out of range "+(t.length-e)),this.segments=t,this.offset=e,this.len=n},t.prototype.construct=function(t,e,n){var r=Object.create(Object.getPrototypeOf(this));return r.init(t,e,n),r},Object.defineProperty(t.prototype,"length",{get:function(){return this.len},enumerable:!0,configurable:!0}),t.prototype.equals=function(e){return 0===t.comparator(this,e)},t.prototype.child=function(e){var n=this.segments.slice(this.offset,this.limit());return e instanceof t?e.forEach(function(t){n.push(t)}):"string"==typeof e?n.push(e):u("Unknown parameter type for Path.child(): "+e),this.construct(n)},t.prototype.limit=function(){return this.offset+this.length},t.prototype.popFirst=function(t){return t=void 0===t?1:t,c(this.length>=t,"Can't call popFirst() with less segments"),this.construct(this.segments,this.offset+t,this.length-t)},t.prototype.popLast=function(){return c(!this.isEmpty(),"Can't call popLast() on empty path"),this.construct(this.segments,this.offset,this.length-1)},t.prototype.firstSegment=function(){return c(!this.isEmpty(),"Can't call firstSegment() on empty path"),this.segments[this.offset]},t.prototype.lastSegment=function(){return c(!this.isEmpty(),"Can't call lastSegment() on empty path"),this.segments[this.limit()-1]},t.prototype.get=function(t){return c(ti)return 1}return t.lengthe.length?1:0},t}(),oe=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ne(e,t),e.prototype.canonicalString=function(){return this.toArray().join("/")},e.prototype.toString=function(){return this.canonicalString()},e.fromString=function(t){if(t.indexOf("//")>=0)throw new zt(Ht.INVALID_ARGUMENT,"Invalid path ("+t+"). Paths must not contain // in them.");return new e(t.split("/").filter(function(t){return t.length>0}))},e.EMPTY_PATH=new e([]),e}(re),ie=/^[_a-zA-Z][_a-zA-Z0-9]*$/,ae=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ne(e,t),e.isValidIdentifier=function(t){return ie.test(t)},e.prototype.canonicalString=function(){return this.toArray().map(function(t){return t=t.replace("\\","\\\\").replace("`","\\`"),e.isValidIdentifier(t)||(t="`"+t+"`"),t}).join(".")},e.prototype.toString=function(){return this.canonicalString()},e.prototype.isKeyField=function(){return 1===this.length&&"__name__"===this.get(0)},e.keyField=function(){return new e(["__name__"])},e.fromServerFormat=function(t){for(var n=[],r="",o=0,i=function(){if(0===r.length)throw new zt(Ht.INVALID_ARGUMENT,"Invalid field path ("+t+"). Paths must not be empty, begin with '.', end with '.', or contain '..'");n.push(r),r=""},a=!1;o0&&(e=e.right)}return null},t.prototype.getPredecessorKey=function(t){for(var e=this.root,n=null;!e.isEmpty();){var r=this.comparator(t,e.key);if(0===r){if(e.left.isEmpty())return n?n.key:null;for(e=e.left;!e.right.isEmpty();)e=e.right;return e.key}r<0?e=e.left:r>0&&(n=e,e=e.right)}throw u("Attempted to find predecessor key for a nonexistent key. What gives?")},t.prototype.indexOf=function(t){for(var e=0,n=this.root;!n.isEmpty();){var r=this.comparator(t,n.key);if(0===r)return e+n.left.size;r<0?n=n.left:(e+=n.left.size+1,n=n.right)}return-1},t.prototype.isEmpty=function(){return this.root.isEmpty()},Object.defineProperty(t.prototype,"size",{get:function(){return this.root.size},enumerable:!0,configurable:!0}),t.prototype.minKey=function(){return this.root.minKey()},t.prototype.maxKey=function(){return this.root.maxKey()},t.prototype.inorderTraversal=function(t){return this.root.inorderTraversal(t)},t.prototype.forEach=function(t){this.inorderTraversal(function(e,n){return t(e,n),!1})},t.prototype.reverseTraversal=function(t){return this.root.reverseTraversal(t)},t.prototype.getIterator=function(t){return new le(this.root,null,this.comparator,!1,t)},t.prototype.getIteratorFrom=function(t,e){return new le(this.root,t,this.comparator,!1,e)},t.prototype.getReverseIterator=function(t){return new le(this.root,null,this.comparator,!0,t)},t.prototype.getReverseIteratorFrom=function(t,e){return new le(this.root,t,this.comparator,!0,e)},t}(),le=function(){function t(t,e,n,r,o){this.resultGenerator=o||null,this.isReverse=r,this.nodeStack=[];for(var i=1;!t.isEmpty();)if(i=e?n(t.key,e):1,r&&(i*=-1),i<0)t=this.isReverse?t.left:t.right;else{if(0===i){this.nodeStack.push(t);break}this.nodeStack.push(t),t=this.isReverse?t.right:t.left}}return t.prototype.getNext=function(){c(this.nodeStack.length>0,"getNext() called on iterator when hasNext() is false.");var t,e=this.nodeStack.pop();if(t=this.resultGenerator?this.resultGenerator(e.key,e.value):{key:e.key,value:e.value},this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t},t.prototype.hasNext=function(){return this.nodeStack.length>0},t.prototype.peek=function(){if(0===this.nodeStack.length)return null;var t=this.nodeStack[this.nodeStack.length-1];return this.resultGenerator?this.resultGenerator(t.key,t.value):{key:t.key,value:t.value}},t}(),fe=function(){function t(e,n,r,o,i){this.key=e,this.value=n,this.color=null!=r?r:t.RED,this.left=null!=o?o:t.EMPTY,this.right=null!=i?i:t.EMPTY,this.size=this.left.size+1+this.right.size}return t.prototype.copy=function(e,n,r,o,i){return new t(null!=e?e:this.key,null!=n?n:this.value,null!=r?r:this.color,null!=o?o:this.left,null!=i?i:this.right)},t.prototype.isEmpty=function(){return!1},t.prototype.inorderTraversal=function(t){return this.left.inorderTraversal(t)||t(this.key,this.value)||this.right.inorderTraversal(t)},t.prototype.reverseTraversal=function(t){return this.right.reverseTraversal(t)||t(this.key,this.value)||this.left.reverseTraversal(t)},t.prototype.min=function(){return this.left.isEmpty()?this:this.left.min()},t.prototype.minKey=function(){return this.min().key},t.prototype.maxKey=function(){return this.right.isEmpty()?this.key:this.right.maxKey()},t.prototype.insert=function(t,e,n){var r=this,o=n(t,r.key);return r=o<0?r.copy(null,null,null,r.left.insert(t,e,n),null):0===o?r.copy(null,e,null,null,null):r.copy(null,null,null,null,r.right.insert(t,e,n)),r.fixUp()},t.prototype.removeMin=function(){if(this.left.isEmpty())return t.EMPTY;var e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()},t.prototype.remove=function(e,n){var r,o=this;if(n(e,o.key)<0)o.left.isEmpty()||o.left.isRed()||o.left.left.isRed()||(o=o.moveRedLeft()),o=o.copy(null,null,null,o.left.remove(e,n),null);else{if(o.left.isRed()&&(o=o.rotateRight()),o.right.isEmpty()||o.right.isRed()||o.right.left.isRed()||(o=o.moveRedRight()),0===n(e,o.key)){if(o.right.isEmpty())return t.EMPTY;r=o.right.min(),o=o.copy(r.key,r.value,null,null,o.right.removeMin())}o=o.copy(null,null,null,null,o.right.remove(e,n))}return o.fixUp()},t.prototype.isRed=function(){return this.color},t.prototype.fixUp=function(){var t=this;return t.right.isRed()&&!t.left.isRed()&&(t=t.rotateLeft()),t.left.isRed()&&t.left.left.isRed()&&(t=t.rotateRight()),t.left.isRed()&&t.right.isRed()&&(t=t.colorFlip()),t},t.prototype.moveRedLeft=function(){var t=this.colorFlip();return t.right.left.isRed()&&(t=t.copy(null,null,null,null,t.right.rotateRight()),t=t.rotateLeft(),t=t.colorFlip()),t},t.prototype.moveRedRight=function(){var t=this.colorFlip();return t.left.left.isRed()&&(t=t.rotateRight(),t=t.colorFlip()),t},t.prototype.rotateLeft=function(){var e=this.copy(null,null,t.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)},t.prototype.rotateRight=function(){var e=this.copy(null,null,t.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)},t.prototype.colorFlip=function(){var t=this.left.copy(null,null,!this.left.color,null,null),e=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,t,e)},t.prototype.checkMaxDepth=function(){var t=this.check();return Math.pow(2,t)<=this.size+1},t.prototype.check=function(){if(this.isRed()&&this.left.isRed())throw u("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed())throw u("Right child of ("+this.key+","+this.value+") is red");var t=this.left.check();if(t!==this.right.check())throw u("Black depths differ");return t+(this.isRed()?0:1)},t.EMPTY=null,t.RED=!0,t.BLACK=!1,t}(),de=function(){function t(){this.size=0}return t.prototype.copy=function(t,e,n,r,o){return this},t.prototype.insert=function(t,e,n){return new fe(t,e)},t.prototype.remove=function(t,e){return this},t.prototype.isEmpty=function(){return!0},t.prototype.inorderTraversal=function(t){return!1},t.prototype.reverseTraversal=function(t){return!1},t.prototype.minKey=function(){return null},t.prototype.maxKey=function(){return null},t.prototype.isRed=function(){return!1},t.prototype.checkMaxDepth=function(){return!0},t.prototype.check=function(){return 0},t}();fe.EMPTY=new de;var pe,ye=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.NullValue=0]="NullValue",t[t.BooleanValue=1]="BooleanValue",t[t.NumberValue=2]="NumberValue",t[t.TimestampValue=3]="TimestampValue",t[t.StringValue=4]="StringValue",t[t.BlobValue=5]="BlobValue",t[t.RefValue=6]="RefValue",t[t.GeoPointValue=7]="GeoPointValue",t[t.ArrayValue=8]="ArrayValue",t[t.ObjectValue=9]="ObjectValue"}(pe||(pe={}));var me,ge=function(){function t(){}return t.prototype.toString=function(){var t=this.value();return null===t?"null":""+t},t.prototype.defaultCompareTo=function(t){return c(this.typeOrder!==t.typeOrder,"Default compareTo should not be used for values of same type."),L(this.typeOrder,t.typeOrder)},t}(),ve=function(t){function e(){var e=t.call(this)||this;return e.typeOrder=pe.NullValue,e.internalValue=null,e}return ye(e,t),e.prototype.value=function(){return null},e.prototype.equals=function(t){return t instanceof e},e.prototype.compareTo=function(t){return t instanceof e?0:this.defaultCompareTo(t)},e.INSTANCE=new e,e}(ge),be=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.BooleanValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?L(this,t):this.defaultCompareTo(t)},e.of=function(t){return t?e.TRUE:e.FALSE},e.TRUE=new e(!0),e.FALSE=new e(!1),e}(ge),we=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.NumberValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.compareTo=function(t){return t instanceof e?j(this.internalValue,t.internalValue):this.defaultCompareTo(t)},e}(ge),Ie=function(t){function e(e){return t.call(this,e)||this}return ye(e,t),e.prototype.equals=function(t){return t instanceof e&&Q(this.internalValue,t.internalValue)},e}(we),Te=function(t){function e(e){var n=t.call(this,e)||this;return n.internalValue=e,n}return ye(e,t),e.prototype.equals=function(t){return t instanceof e&&Q(this.internalValue,t.internalValue)},e.NAN=new e(NaN),e.POSITIVE_INFINITY=new e(1/0),e.NEGATIVE_INFINITY=new e(-1/0),e}(we),Ee=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.StringValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue===t.internalValue},e.prototype.compareTo=function(t){return t instanceof e?L(this.internalValue,t.internalValue):this.defaultCompareTo(t)},e}(ge),Se=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.TimestampValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue.toDate()},e.prototype.equals=function(t){return t instanceof e&&this.internalValue.equals(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue.compareTo(t.internalValue):t instanceof Ce?-1:this.defaultCompareTo(t)},e}(ge),Ce=function(t){function e(e){var n=t.call(this)||this;return n.localWriteTime=e,n.typeOrder=pe.TimestampValue,n}return ye(e,t),e.prototype.value=function(){return null},e.prototype.equals=function(t){return t instanceof e&&this.localWriteTime.equals(t.localWriteTime)},e.prototype.compareTo=function(t){return t instanceof e?this.localWriteTime.compareTo(t.localWriteTime):t instanceof Se?1:this.defaultCompareTo(t)},e.prototype.toString=function(){return""},e}(ge),De=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.BlobValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue.n(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue.r(t.internalValue):this.defaultCompareTo(t)},e}(ge),ke=function(t){function e(e,n){var r=t.call(this)||this;return r.databaseId=e,r.key=n,r.typeOrder=pe.RefValue,r}return ye(e,t),e.prototype.value=function(){return this.key},e.prototype.equals=function(t){return t instanceof e&&this.key.equals(t.key)&&this.databaseId.equals(t.databaseId)},e.prototype.compareTo=function(t){if(t instanceof e){var n=this.databaseId.compareTo(t.databaseId);return 0!==n?n:se.comparator(this.key,t.key)}return this.defaultCompareTo(t)},e}(ge),Ne=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.GeoPointValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue},e.prototype.equals=function(t){return t instanceof e&&this.internalValue.n(t.internalValue)},e.prototype.compareTo=function(t){return t instanceof e?this.internalValue.r(t.internalValue):this.defaultCompareTo(t)},e}(ge),Ae=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.ObjectValue,n}return ye(e,t),e.prototype.value=function(){var t={};return this.internalValue.inorderTraversal(function(e,n){t[e]=n.value()}),t},e.prototype.forEach=function(t){this.internalValue.inorderTraversal(t)},e.prototype.equals=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var o=n.getNext(),i=r.getNext();if(o.key!==i.key||!o.value.equals(i.value))return!1}return!n.hasNext()&&!r.hasNext()}return!1},e.prototype.compareTo=function(t){if(t instanceof e){for(var n=this.internalValue.getIterator(),r=t.internalValue.getIterator();n.hasNext()&&r.hasNext();){var o=n.getNext(),i=r.getNext(),a=L(o.key,i.key)||o.value.compareTo(i.value);if(a)return a}return L(n.hasNext(),r.hasNext())}return this.defaultCompareTo(t)},e.prototype.set=function(t,n){if(c(!t.isEmpty(),"Cannot set field for empty path on ObjectValue"),1===t.length)return this.setChild(t.firstSegment(),n);var r=this.child(t.firstSegment());r instanceof e||(r=e.EMPTY);var o=r.set(t.popFirst(),n);return this.setChild(t.firstSegment(),o)},e.prototype.delete=function(t){if(c(!t.isEmpty(),"Cannot delete field for empty path on ObjectValue"),1===t.length)return new e(this.internalValue.remove(t.firstSegment()));var n=this.child(t.firstSegment());if(n instanceof e){var r=n.delete(t.popFirst());return new e(this.internalValue.insert(t.firstSegment(),r))}return this},e.prototype.contains=function(t){return void 0!==this.field(t)},e.prototype.field=function(t){c(!t.isEmpty(),"Can't get field of empty path");var n=this;return t.forEach(function(t){n=n instanceof e?n.internalValue.get(t)||void 0:void 0}),n},e.prototype.toString=function(){return JSON.stringify(this.value())},e.prototype.child=function(t){return this.internalValue.get(t)||void 0},e.prototype.setChild=function(t,n){return new e(this.internalValue.insert(t,n))},e.EMPTY=new e(new he(L)),e}(ge),Re=function(t){function e(e){var n=t.call(this)||this;return n.internalValue=e,n.typeOrder=pe.ArrayValue,n}return ye(e,t),e.prototype.value=function(){return this.internalValue.map(function(t){return t.value()})},e.prototype.forEach=function(t){this.internalValue.forEach(t)},e.prototype.equals=function(t){if(t instanceof e){if(this.internalValue.length!==t.internalValue.length)return!1;for(var n=0;n0?this.explicitOrderBy[this.explicitOrderBy.length-1].dir:Ve.ASCENDING;this.memoizedOrderBy.push(a===Ve.ASCENDING?Qe:Ke)}}}return this.memoizedOrderBy},enumerable:!0,configurable:!0}),t.prototype.addFilter=function(e){c(null==this.getInequalityFilterField()||!(e instanceof Be)||!e.isInequality()||e.field.equals(this.getInequalityFilterField()),"Query must only have one inequality field."),c(!se.isDocumentKey(this.path),"No filtering allowed for document query");var n=this.filters.concat([e]);return new t(this.path,this.explicitOrderBy.slice(),n,this.limit,this.startAt,this.endAt)},t.prototype.addOrderBy=function(e){c(!se.isDocumentKey(this.path),"No ordering allowed for document query"),c(!this.startAt&&!this.endAt,"Bounds must be set after orderBy");var n=this.explicitOrderBy.concat([e]);return new t(this.path,n,this.filters.slice(),this.limit,this.startAt,this.endAt)},t.prototype.withLimit=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),e,this.startAt,this.endAt)},t.prototype.withStartAt=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,e,this.endAt)},t.prototype.withEndAt=function(e){return new t(this.path,this.explicitOrderBy.slice(),this.filters.slice(),this.limit,this.startAt,e)},t.prototype.canonicalId=function(){if(null===this.memoizedCanonicalId){var t=this.path.canonicalString();t+="|f:";for(var e=0,n=this.filters;e0&&(t+=", filters: ["+this.filters.join(", ")+"]"),K(this.limit)||(t+=", limit: "+this.limit),this.explicitOrderBy.length>0&&(t+=", orderBy: ["+this.explicitOrderBy.join(", ")+"]"),this.startAt&&(t+=", startAt: "+this.startAt.canonicalId()),this.endAt&&(t+=", endAt: "+this.endAt.canonicalId()),t+")"},t.prototype.equals=function(t){if(this.limit!==t.limit)return!1;if(this.orderBy.length!==t.orderBy.length)return!1;for(var e=0;e0?this.explicitOrderBy[0].field:null},t.prototype.getInequalityFilterField=function(){for(var t=0,e=this.filters;t=":return t.GREATER_THAN_OR_EQUAL;case">":return t.GREATER_THAN;default:return u("Unknown relation: "+e)}},t.prototype.toString=function(){return this.name},t.prototype.equals=function(t){return this.name===t.name},t.LESS_THAN=new t("<"),t.LESS_THAN_OR_EQUAL=new t("<="),t.EQUAL=new t("=="),t.GREATER_THAN=new t(">"),t.GREATER_THAN_OR_EQUAL=new t(">="),t}(),Be=function(){function t(t,e,n){this.field=t,this.op=e,this.value=n}return t.prototype.matches=function(t){if(this.field.isKeyField()){c(this.value instanceof ke,"Comparing on key, but filter value not a RefValue");var e=this.value,n=se.comparator(t.key,e.key);return this.matchesComparison(n)}var r=t.field(this.field);return void 0!==r&&this.matchesValue(r)},t.prototype.matchesValue=function(t){return this.value.typeOrder===t.typeOrder&&this.matchesComparison(t.compareTo(this.value))},t.prototype.matchesComparison=function(t){switch(this.op){case xe.LESS_THAN:return t<0;case xe.LESS_THAN_OR_EQUAL:return t<=0;case xe.EQUAL:return 0===t;case xe.GREATER_THAN:return t>0;case xe.GREATER_THAN_OR_EQUAL:return t>=0;default:return u("Unknown relation op"+this.op)}},t.prototype.isInequality=function(){return this.op!==xe.EQUAL},t.prototype.canonicalId=function(){return this.field.canonicalString()+""+this.op+this.value},t.prototype.equals=function(e){return e instanceof t&&this.op.equals(e.op)&&this.field.equals(e.field)&&this.value.equals(e.value)},t.prototype.toString=function(){return this.field.canonicalString()+" "+this.op+" "+this.value.value()},t}(),Ue=function(){function t(t){this.field=t}return t.prototype.matches=function(t){var e=t.field(this.field);return void 0!==e&&null===e.value()},t.prototype.canonicalId=function(){return this.field.canonicalString()+" IS null"},t.prototype.toString=function(){return this.field.canonicalString()+" IS null"},t.prototype.equals=function(e){return e instanceof t&&this.field.equals(e.field)},t}(),Fe=function(){function t(t){this.field=t}return t.prototype.matches=function(t){var e=t.field(this.field).value();return"number"==typeof e&&isNaN(e)},t.prototype.canonicalId=function(){return this.field.canonicalString()+" IS NaN"},t.prototype.toString=function(){return this.field.canonicalString()+" IS NaN"},t.prototype.equals=function(e){return e instanceof t&&this.field.equals(e.field)},t}(),Ve=function(){function t(t){this.name=t}return t.prototype.toString=function(){return this.name},t.ASCENDING=new t("asc"),t.DESCENDING=new t("desc"),t}(),qe=function(){function t(t,e){this.position=t,this.before=e}return t.prototype.canonicalId=function(){for(var t=this.before?"b:":"a:",e=0,n=this.position;e=0,"timestamp nanoseconds out of range: "+e),c(e<1e9,"timestamp nanoseconds out of range"+e),c(t>=-62135596800,"timestamp seconds out of range: "+t),c(t<253402300800,"timestamp seconds out of range"+t)}return t.now=function(){return t.fromEpochMilliseconds(Date.now())},t.fromDate=function(e){return t.fromEpochMilliseconds(e.getTime())},t.fromEpochMilliseconds=function(e){var n=Math.floor(e/1e3);return new t(n,1e6*(e-1e3*n))},t.fromISOString=function(e){var n=0,r=We.exec(e);if(c(!!r,"invalid timestamp: "+e),r[1]){var o=r[1];o=(o+"000000000").substr(0,9),n=parseInt(o,10)}var i=new Date(e);return new t(Math.floor(i.getTime()/1e3),n)},t.prototype.toDate=function(){return new Date(this.toEpochMilliseconds())},t.prototype.toEpochMilliseconds=function(){return 1e3*this.seconds+this.nanos/1e6},t.prototype.compareTo=function(t){return this.seconds===t.seconds?L(this.nanos,t.nanos):L(this.seconds,t.seconds)},t.prototype.equals=function(t){return t.seconds===this.seconds&&t.nanos===this.nanos},t.prototype.toString=function(){return"Timestamp(seconds="+this.seconds+", nanos="+this.nanos+")"},t}(),He=function(){function t(t){this.timestamp=t}return t.fromMicroseconds=function(e){var n=Math.floor(e/1e6);return new t(new Ge(n,e%1e6*1e3))},t.fromTimestamp=function(e){return new t(e)},t.forDeletedDoc=function(){return t.MIN},t.prototype.compareTo=function(t){return this.timestamp.compareTo(t.timestamp)},t.prototype.equals=function(t){return this.timestamp.equals(t.timestamp)},t.prototype.toMicroseconds=function(){return 1e6*this.timestamp.seconds+this.timestamp.nanos/1e3},t.prototype.toString=function(){return"SnapshotVersion("+this.timestamp+")"},t.prototype.toTimestamp=function(){return this.timestamp},t.MIN=new t(new Ge(0,0)),t}();!function(t){t[t.Listen=0]="Listen",t[t.ExistenceFilterMismatch=1]="ExistenceFilterMismatch",t[t.LimboResolution=2]="LimboResolution"}(me||(me={}));var ze,Xe=function(){function t(t,e,n,r,o){void 0===r&&(r=He.MIN),void 0===o&&(o=h()),this.query=t,this.targetId=e,this.purpose=n,this.snapshotVersion=r,this.resumeToken=o}return t.prototype.update=function(e){return new t(this.query,this.targetId,this.purpose,e.snapshotVersion,e.resumeToken)},t.prototype.equals=function(t){return this.targetId===t.targetId&&this.purpose===t.purpose&&this.snapshotVersion.equals(t.snapshotVersion)&&this.resumeToken===t.resumeToken&&this.query.equals(t.query)},t}(),Ye=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Je=function(){function t(t){this.fields=t}return t.prototype.equals=function(t){return B(this.fields,t.fields)},t}(),$e=function(){function t(){}return t.prototype.equals=function(e){return e instanceof t},t.instance=new t,t}(),Ze=function(){function t(t,e){this.field=t,this.transform=e}return t.prototype.equals=function(t){return this.field.equals(t.field)&&this.transform.equals(t.transform)},t}(),tn=function(){function t(t,e){this.version=t,this.transformResults=e}return t}();!function(t){t[t.Set=0]="Set",t[t.Patch=1]="Patch",t[t.Transform=2]="Transform",t[t.Delete=3]="Delete"}(ze||(ze={}));var en,nn=function(){function t(t,e){this.updateTime=t,this.exists=e,c(void 0===t||void 0===e,'Precondition can specify "exists" or "updateTime" but not both')}return t.exists=function(e){return new t(void 0,e)},t.updateTime=function(e){return new t(e)},Object.defineProperty(t.prototype,"isNone",{get:function(){return void 0===this.updateTime&&void 0===this.exists},enumerable:!0,configurable:!0}),t.prototype.isValidFor=function(t){return void 0!==this.updateTime?t instanceof ue&&t.version.equals(this.updateTime):void 0!==this.exists?this.exists?t instanceof ue:null===t||t instanceof ce:(c(this.isNone,"Precondition should be empty"),!0)},t.prototype.equals=function(t){return x(this.updateTime,t.updateTime)&&this.exists===t.exists},t.NONE=new t,t}(),rn=function(){function t(){}return t.prototype.verifyKeyMatches=function(t){null!=t&&c(t.key.equals(this.key),"Can only apply a mutation to a document with the same key")},t.getPostMutationVersion=function(t){return t instanceof ue?t.version:He.MIN},t}(),on=function(t){function e(e,n,r){var o=t.call(this)||this;return o.key=e,o.value=n,o.precondition=r,o.type=ze.Set,o}return Ye(e,t),e.prototype.applyToRemoteDocument=function(t,e){this.verifyKeyMatches(t),c(null==e.transformResults,"Transform results received by SetMutation.");var n=rn.getPostMutationVersion(t);return new ue(this.key,n,this.value,{hasLocalMutations:!1})},e.prototype.applyToLocalView=function(t,e){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var n=rn.getPostMutationVersion(t);return new ue(this.key,n,this.value,{hasLocalMutations:!0})},e.prototype.equals=function(t){return t instanceof e&&this.key.equals(t.key)&&this.value.equals(t.value)&&this.precondition.equals(t.precondition)},e}(rn),an=function(t){function e(e,n,r,o){var i=t.call(this)||this;return i.key=e,i.data=n,i.fieldMask=r,i.precondition=o,i.type=ze.Patch,i}return Ye(e,t),e.prototype.applyToRemoteDocument=function(t,e){if(this.verifyKeyMatches(t),c(null==e.transformResults,"Transform results received by PatchMutation."),!this.precondition.isValidFor(t))return t;var n=rn.getPostMutationVersion(t),r=this.patchDocument(t);return new ue(this.key,n,r,{hasLocalMutations:!1})},e.prototype.applyToLocalView=function(t,e){if(this.verifyKeyMatches(t),!this.precondition.isValidFor(t))return t;var n=rn.getPostMutationVersion(t),r=this.patchDocument(t);return new ue(this.key,n,r,{hasLocalMutations:!0})},e.prototype.equals=function(t){return t instanceof e&&this.key.equals(t.key)&&this.fieldMask.equals(t.fieldMask)&&this.precondition.equals(t.precondition)},e.prototype.patchDocument=function(t){var e;return e=t instanceof ue?t.data:Ae.EMPTY,this.patchObject(e)},e.prototype.patchObject=function(t){for(var e=0,n=this.fieldMask.fields;e=0)return;e(r.key)}},t.prototype.forEachWhile=function(t,e){var n;for(n=void 0!==e?this.data.getIteratorFrom(e):this.data.getIterator();n.hasNext();)if(!t(n.getNext().key))return},t.prototype.firstAfterOrEqual=function(t){var e=this.data.getIteratorFrom(t);return e.hasNext()?e.getNext().key:null},t.prototype.add=function(t){return this.copy(this.data.remove(t).insert(t,!0))},t.prototype.delete=function(t){return this.has(t)?this.copy(this.data.remove(t)):this},t.prototype.isEmpty=function(){return this.data.isEmpty()},t.prototype.unionWith=function(t){var e=this;return t.forEach(function(t){e=e.add(t)}),e},t.prototype.equals=function(e){if(!(e instanceof t))return!1;if(this.size!==e.size)return!1;for(var n=this.data.getIterator(),r=e.data.getIterator();n.hasNext();){var o=n.getNext().key,i=r.getNext().key;if(0!==this.comparator(o,i))return!1}return!0},t.prototype.toString=function(){var t=[];return this.forEach(function(e){return t.push(e)}),"SortedSet("+t+")"},t.prototype.copy=function(e){var n=new t(this.comparator);return n.data=e,n},t}(),fn=new he(se.comparator),dn=new he(se.comparator),pn=new he(se.comparator),yn=new ln(se.comparator),mn=function(){function t(t,e,n){this.snapshotVersion=t,this.targetChanges=e,this.documentUpdates=n}return t.prototype.addDocumentUpdate=function(t){this.documentUpdates=this.documentUpdates.insert(t.key,t)},t.prototype.handleExistenceFilterMismatch=function(t){this.targetChanges[t]={mapping:new bn,snapshotVersion:He.MIN,currentStatusUpdate:hn.MarkNotCurrent,resumeToken:h()}},t}();!function(t){t[t.None=0]="None",t[t.MarkNotCurrent=1]="MarkNotCurrent",t[t.MarkCurrent=2]="MarkCurrent"}(hn||(hn={}));var gn,vn=et(),bn=function(){function t(){this.docs=vn}return Object.defineProperty(t.prototype,"documents",{get:function(){return this.docs},enumerable:!0,configurable:!0}),t.prototype.add=function(t){this.docs=this.docs.add(t)},t.prototype.delete=function(t){this.docs=this.docs.delete(t)},t.prototype.equals=function(t){return null!==t&&this.docs.equals(t.docs)},t}(),wn=function(){function t(){this.addedDocuments=vn,this.removedDocuments=vn}return t.prototype.applyToKeySet=function(t){var e=t;return this.addedDocuments.forEach(function(t){return e=e.add(t)}),this.removedDocuments.forEach(function(t){return e=e.delete(t)}),e},t.prototype.add=function(t){this.addedDocuments=this.addedDocuments.add(t),this.removedDocuments=this.removedDocuments.delete(t)},t.prototype.delete=function(t){this.addedDocuments=this.addedDocuments.delete(t),this.removedDocuments=this.removedDocuments.add(t)},t.prototype.equals=function(t){return null!==t&&this.addedDocuments.equals(t.addedDocuments)&&this.removedDocuments.equals(t.removedDocuments)},t}(),In=function(){function t(t,e,n,r){this.updatedTargetIds=t,this.removedTargetIds=e,this.key=n,this.newDoc=r}return t}(),Tn=function(){function t(t,e){this.targetId=t,this.existenceFilter=e}return t}();!function(t){t[t.NoChange=0]="NoChange",t[t.Added=1]="Added",t[t.Removed=2]="Removed",t[t.Current=3]="Current",t[t.Reset=4]="Reset"}(gn||(gn={}));var En=function(){function t(t,e,n,r){void 0===n&&(n=h()),void 0===r&&(r=null),this.state=t,this.targetIds=e,this.resumeToken=n,this.cause=r}return t}(),Sn=function(){function t(t,e,n){this.snapshotVersion=t,this.listenTargets=e,this.existenceFilters={},this.targetChanges={},this.documentUpdates=$(),this.frozen=!1,this.pendingTargetResponses=g(n)}return t.prototype.add=function(t){c(!this.frozen,"Trying to modify frozen WatchChangeAggregator."),t instanceof In?this.addDocumentChange(t):t instanceof En?this.addTargetChange(t):t instanceof Tn?this.addExistenceFilterChange(t):u("Unknown watch change: "+t)},t.prototype.addChanges=function(t){var e=this;c(!this.frozen,"Trying to modify frozen WatchChangeAggregator."),t.forEach(function(t){return e.add(t)})},t.prototype.createRemoteEvent=function(){var t=this,e=this.targetChanges;return p(this.targetChanges,function(n){t.isActiveTarget(n)||delete e[n]}),this.frozen=!0,new mn(this.snapshotVersion,e,this.documentUpdates)},t.prototype.ensureTargetChange=function(t){var e=this.targetChanges[t];return e||(e={currentStatusUpdate:hn.None,snapshotVersion:this.snapshotVersion,mapping:new wn,resumeToken:h()},this.targetChanges[t]=e),e},t.prototype.isActiveTarget=function(t){return!f(this.pendingTargetResponses,t)&&f(this.listenTargets,t)},t.prototype.addDocumentChange=function(t){for(var e=!1,n=0,r=t.updatedTargetIds;n4&&"documents"===t.get(4),"tried to deserialize invalid key "+t),t.popFirst(5)},t.prototype.isValidResourceName=function(t){return t.length>=4&&"projects"===t.get(0)&&"databases"===t.get(2)},t.prototype.toValue=function(t){if(t instanceof ve)return{nullValue:"NULL_VALUE"};if(t instanceof be)return{booleanValue:t.value()};if(t instanceof Ie)return{integerValue:""+t.value()};if(t instanceof Te){var e=t.value();if(this.options.useProto3Json){if(isNaN(e))return{doubleValue:"NaN"};if(e===1/0)return{doubleValue:"Infinity"};if(e===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:t.value()}}return t instanceof Ee?{stringValue:t.value()}:t instanceof Ae?{mapValue:this.toMapValue(t)}:t instanceof Re?{arrayValue:this.toArrayValue(t)}:t instanceof Se?{timestampValue:this.toTimestamp(t.internalValue)}:t instanceof Ne?{geoPointValue:{latitude:t.value().latitude,longitude:t.value().longitude}}:t instanceof De?{bytesValue:this.toBytes(t.value())}:t instanceof ke?{referenceValue:this.toResourceName(t.databaseId,t.key.path)}:u("Unknown FieldValue "+JSON.stringify(t))},t.prototype.fromValue=function(t){var e=this,n=t.value_type;if(it(t,n,"nullValue"))return ve.INSTANCE;if(it(t,n,"booleanValue"))return be.of(t.booleanValue);if(it(t,n,"integerValue"))return new Ie(ot(t.integerValue));if(it(t,n,"doubleValue")){if(this.options.useProto3Json){if("NaN"===t.doubleValue)return Te.NAN;if("Infinity"===t.doubleValue)return Te.POSITIVE_INFINITY;if("-Infinity"===t.doubleValue)return Te.NEGATIVE_INFINITY}return new Te(t.doubleValue)}if(it(t,n,"stringValue"))return new Ee(t.stringValue);if(it(t,n,"mapValue"))return this.fromFields(t.mapValue.fields||{});if(it(t,n,"arrayValue")){rt(t.arrayValue,"arrayValue");var r=t.arrayValue.values||[];return new Re(r.map(function(t){return e.fromValue(t)}))}if(it(t,n,"timestampValue"))return rt(t.timestampValue,"timestampValue"),new Se(this.fromTimestamp(t.timestampValue));if(it(t,n,"geoPointValue")){rt(t.geoPointValue,"geoPointValue");var o=t.geoPointValue.latitude||0,i=t.geoPointValue.longitude||0;return new Ne(new $t(o,i))}if(it(t,n,"bytesValue")){rt(t.bytesValue,"bytesValue");var a=this.fromBlob(t.bytesValue);return new De(a)}if(it(t,n,"referenceValue")){rt(t.referenceValue,"referenceValue");var s=this.fromResourceName(t.referenceValue),c=new ee(s.get(1),s.get(3)),h=new se(this.extractLocalPathFromResourceName(s));return new ke(c,h)}return u("Unknown Value proto "+JSON.stringify(t))},t.prototype.toMutationDocument=function(t,e){return{name:this.toName(t),fields:this.toFields(e)}},t.prototype.toDocument=function(t){return c(!t.hasLocalMutations,"Can't serialize documents with mutations."),{name:this.toName(t.key),fields:this.toFields(t.data),updateTime:this.toTimestamp(t.version.toTimestamp())}},t.prototype.fromDocument=function(t){return new ue(this.fromName(t.name),this.fromVersion(t.updateTime),this.fromFields(t.fields||{}),{hasLocalMutations:!1})},t.prototype.toFields=function(t){var e=this,n={};return t.forEach(function(t,r){n[t]=e.toValue(r)}),n},t.prototype.fromFields=function(t){var e=this,n=t,r=Ae.EMPTY;return y(n,function(t,n){r=r.set(new ae([t]),e.fromValue(n))}),r},t.prototype.toMapValue=function(t){return{fields:this.toFields(t)}},t.prototype.toArrayValue=function(t){var e=this,n=[];return t.forEach(function(t){n.push(e.toValue(t))}),{values:n}},t.prototype.fromFound=function(t){c(!!t.found,"Tried to deserialize a found document from a missing document."),rt(t.found.name,"doc.found.name"),rt(t.found.updateTime,"doc.found.updateTime");var e=this.fromName(t.found.name),n=this.fromVersion(t.found.updateTime),r=this.fromFields(t.found.fields||{});return new ue(e,n,r,{hasLocalMutations:!1})},t.prototype.fromMissing=function(t){c(!!t.missing,"Tried to deserialize a missing document from a found document."),c(!!t.readTime,"Tried to deserialize a missing document without a read time.");var e=this.fromName(t.missing),n=this.fromVersion(t.readTime);return new ce(e,n)},t.prototype.fromMaybeDocument=function(t){var e=t.result;return it(t,e,"found")?this.fromFound(t):it(t,e,"missing")?this.fromMissing(t):u("invalid batch get response: "+JSON.stringify(t))},t.prototype.toWatchTargetChangeState=function(t){switch(t){case gn.Added:return"ADD";case gn.Current:return"CURRENT";case gn.NoChange:return"NO_CHANGE";case gn.Removed:return"REMOVE";case gn.Reset:return"RESET";default:return u("Unknown WatchTargetChangeState: "+t)}},t.prototype.toTestWatchChange=function(t){if(t instanceof Tn)return{filter:{count:t.existenceFilter.count,targetId:t.targetId}};if(t instanceof In){if(t.newDoc instanceof ue){var e=t.newDoc;return{documentChange:{document:{name:this.toName(e.key),fields:this.toFields(e.data),updateTime:this.toVersion(e.version)},targetIds:t.updatedTargetIds,removedTargetIds:t.removedTargetIds}}}if(t.newDoc instanceof ce){var e=t.newDoc;return{documentDelete:{document:this.toName(e.key),readTime:this.toVersion(e.version),removedTargetIds:t.removedTargetIds}}}if(null===t.newDoc)return{documentRemove:{document:this.toName(t.key),removedTargetIds:t.removedTargetIds}}}if(t instanceof En){var n=void 0;return t.cause&&(n={code:Y(t.cause.code),message:t.cause.message}),{targetChange:{targetChangeType:this.toWatchTargetChangeState(t.state),targetIds:t.targetIds,resumeToken:this.unsafeCastProtoByteString(t.resumeToken),cause:n}}}return u("Unrecognized watch change: "+JSON.stringify(t))},t.prototype.fromWatchChange=function(t){var e,n=t.response_type;if(it(t,n,"targetChange")){rt(t.targetChange,"targetChange");var r=this.fromWatchTargetChangeState(t.targetChange.targetChangeType||"NO_CHANGE"),o=t.targetChange.targetIds||[],i=t.targetChange.resumeToken||this.emptyByteString(),a=t.targetChange.cause,s=a&&this.fromRpcStatus(a);e=new En(r,o,i,s||null)}else if(it(t,n,"documentChange")){rt(t.documentChange,"documentChange"),rt(t.documentChange.document,"documentChange.name"),rt(t.documentChange.document.name,"documentChange.document.name"),rt(t.documentChange.document.updateTime,"documentChange.document.updateTime");var c=t.documentChange,h=this.fromName(c.document.name),l=this.fromVersion(c.document.updateTime),f=this.fromFields(c.document.fields||{}),d=new ue(h,l,f,{hasLocalMutations:!1}),p=c.targetIds||[],y=c.removedTargetIds||[];e=new In(p,y,d.key,d)}else if(it(t,n,"documentDelete")){rt(t.documentDelete,"documentDelete"),rt(t.documentDelete.document,"documentDelete.document");var m=t.documentDelete,h=this.fromName(m.document),l=m.readTime?this.fromVersion(m.readTime):He.forDeletedDoc(),d=new ce(h,l),y=m.removedTargetIds||[];e=new In([],y,d.key,d)}else if(it(t,n,"documentRemove")){rt(t.documentRemove,"documentRemove"),rt(t.documentRemove.document,"documentRemove");var g=t.documentRemove,h=this.fromName(g.document),y=g.removedTargetIds||[];e=new In([],y,h,null)}else{if(!it(t,n,"filter"))return u("Unknown change type "+JSON.stringify(t));rt(t.filter,"filter"),rt(t.filter.targetId,"filter.targetId");var v=t.filter,b=v.count||0,w=new cn(b),I=v.targetId;e=new Tn(I,w)}return e},t.prototype.fromWatchTargetChangeState=function(t){return"NO_CHANGE"===t?gn.NoChange:"ADD"===t?gn.Added:"REMOVE"===t?gn.Removed:"CURRENT"===t?gn.Current:"RESET"===t?gn.Reset:u("Got unexpected TargetChange.state: "+t)},t.prototype.versionFromListenResponse=function(t){if(!it(t,t.response_type,"targetChange"))return He.MIN;var e=t.targetChange;return e.targetIds&&e.targetIds.length?He.MIN:e.readTime?this.fromVersion(e.readTime):He.MIN},t.prototype.toMutation=function(t){var e,n=this;if(t instanceof on)e={update:this.toMutationDocument(t.key,t.value)};else if(t instanceof un)e={delete:this.toName(t.key)};else if(t instanceof an)e={update:this.toMutationDocument(t.key,t.data),updateMask:this.toDocumentMask(t.fieldMask)};else{if(!(t instanceof sn))return u("Unknown mutation type "+t.type);e={transform:{document:this.toName(t.key),fieldTransforms:t.fieldTransforms.map(function(t){return n.toFieldTransform(t)})}}}return t.precondition.isNone||(e.currentDocument=this.toPrecondition(t.precondition)),e},t.prototype.fromMutation=function(t){var e=this,n=t.currentDocument?this.fromPrecondition(t.currentDocument):nn.NONE;if(t.update){rt(t.update.name,"name");var r=this.fromName(t.update.name),o=this.fromFields(t.update.fields||{});if(t.updateMask){var i=this.fromDocumentMask(t.updateMask);return new an(r,o,i,n)}return new on(r,o,n)}if(t.delete){var r=this.fromName(t.delete);return new un(r,n)}if(t.transform){var r=this.fromName(t.transform.document),a=t.transform.fieldTransforms.map(function(t){return e.fromFieldTransform(t)});return c(!0===n.exists,'Transforms only support precondition "exists == true"'),new sn(r,a)}return u("unknown mutation proto: "+JSON.stringify(t))},t.prototype.toPrecondition=function(t){return c(!t.isNone,"Can't serialize an empty precondition"),void 0!==t.updateTime?{updateTime:this.toVersion(t.updateTime)}:void 0!==t.exists?{exists:t.exists}:u("Unknown precondition")},t.prototype.fromPrecondition=function(t){return void 0!==t.updateTime?nn.updateTime(this.fromVersion(t.updateTime)):void 0!==t.exists?nn.exists(t.exists):nn.NONE},t.prototype.fromWriteResult=function(t){var e=this,n=t.updateTime?this.fromVersion(t.updateTime):null,r=null;return t.transformResults&&t.transformResults.length>0&&(r=t.transformResults.map(function(t){return e.fromValue(t)})),new tn(n,r)},t.prototype.fromWriteResults=function(t){var e=this;return(t||[]).map(function(t){return e.fromWriteResult(t)})},t.prototype.toFieldTransform=function(t){return c(t.transform instanceof $e,"Unknown transform: "+t.transform),{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"}},t.prototype.fromFieldTransform=function(t){c("REQUEST_TIME"===t.setToServerValue,"Unknown transform proto: "+JSON.stringify(t));var e=ae.fromServerFormat(t.fieldPath);return new Ze(e,$e.instance)},t.prototype.toDocumentsTarget=function(t){return{documents:[this.toQueryPath(t.path)]}},t.prototype.fromDocumentsTarget=function(t){var e=t.documents.length;c(1===e,"DocumentsTarget contained other than 1 document: "+e);var n=t.documents[0];return Le.atPath(this.fromQueryPath(n))},t.prototype.toQueryTarget=function(t){var e={structuredQuery:{}};if(t.path.isEmpty())e.parent=this.toQueryPath(oe.EMPTY_PATH);else{var n=t.path;c(n.length%2!=0,"Document queries with filters are not supported."),e.parent=this.toQueryPath(n.popLast()),e.structuredQuery.from=[{collectionId:n.lastSegment()}]}var r=this.toFilter(t.filters);r&&(e.structuredQuery.where=r);var o=this.toOrder(t.orderBy);o&&(e.structuredQuery.orderBy=o);var i=this.toInt32Value(t.limit);return void 0!==i&&(e.structuredQuery.limit=i),t.startAt&&(e.structuredQuery.startAt=this.toCursor(t.startAt)),t.endAt&&(e.structuredQuery.endAt=this.toCursor(t.endAt)),e},t.prototype.fromQueryTarget=function(t){var e=this.fromQueryPath(t.parent),n=t.structuredQuery,r=n.from?n.from.length:0;if(r>0){c(1===r,"StructuredQuery.from with more than one collection is not supported.");var o=n.from[0];e=e.child(o.collectionId)}var i=[];n.where&&(i=this.fromFilter(n.where));var a=[];n.orderBy&&(a=this.fromOrder(n.orderBy));var s=null;n.limit&&(s=this.fromInt32Value(n.limit));var u=null;n.startAt&&(u=this.fromCursor(n.startAt));var h=null;return n.endAt&&(h=this.fromCursor(n.endAt)),new Le(e,a,i,s,u,h)},t.prototype.toListenRequestLabels=function(t){var e=this.toLabel(t.purpose);return null==e?null:{"goog-listen-tags":e}},t.prototype.toLabel=function(t){switch(t){case me.Listen:return null;case me.ExistenceFilterMismatch:return"existence-filter-mismatch";case me.LimboResolution:return"limbo-document";default:return u("Unrecognized query purpose: "+t)}},t.prototype.toTarget=function(t){var e,n=t.query;return e=n.isDocumentQuery()?{documents:this.toDocumentsTarget(n)}:{query:this.toQueryTarget(n)},e.targetId=t.targetId,t.resumeToken.length>0&&(e.resumeToken=this.unsafeCastProtoByteString(t.resumeToken)),e},t.prototype.toFilter=function(t){var e=this;if(0!==t.length){var n=t.map(function(t){return t instanceof Be?e.toRelationFilter(t):e.toUnaryFilter(t)});return 1===n.length?n[0]:{compositeFilter:{op:"AND",filters:n}}}},t.prototype.fromFilter=function(t){var e=this;return t?void 0!==t.unaryFilter?[this.fromUnaryFilter(t)]:void 0!==t.fieldFilter?[this.fromRelationFilter(t)]:void 0!==t.compositeFilter?t.compositeFilter.filters.map(function(t){return e.fromFilter(t)}).reduce(function(t,e){return t.concat(e)}):u("Unknown filter: "+JSON.stringify(t)):[]},t.prototype.toOrder=function(t){var e=this;if(0!==t.length)return t.map(function(t){return e.toPropertyOrder(t)})},t.prototype.fromOrder=function(t){var e=this;return t.map(function(t){return e.fromPropertyOrder(t)})},t.prototype.toCursor=function(t){var e=this;return{before:t.before,values:t.position.map(function(t){return e.toValue(t)})}},t.prototype.fromCursor=function(t){var e=this,n=!!t.before,r=t.values.map(function(t){return e.fromValue(t)});return new qe(r,n)},t.prototype.toDirection=function(t){return Cn[t.name]},t.prototype.fromDirection=function(t){switch(t){case"ASCENDING":return Ve.ASCENDING;case"DESCENDING":return Ve.DESCENDING;default:return}},t.prototype.toOperatorName=function(t){return Dn[t.name]},t.prototype.fromOperatorName=function(t){switch(t){case"EQUAL":return xe.EQUAL;case"GREATER_THAN":return xe.GREATER_THAN;case"GREATER_THAN_OR_EQUAL":return xe.GREATER_THAN_OR_EQUAL;case"LESS_THAN":return xe.LESS_THAN;case"LESS_THAN_OR_EQUAL":return xe.LESS_THAN_OR_EQUAL;case"OPERATOR_UNSPECIFIED":return u("Unspecified relation");default:return u("Unknown relation")}},t.prototype.toFieldPathReference=function(t){return{fieldPath:t.canonicalString()}},t.prototype.fromFieldPathReference=function(t){return ae.fromServerFormat(t.fieldPath)},t.prototype.toPropertyOrder=function(t){return{field:this.toFieldPathReference(t.field),direction:this.toDirection(t.dir)}},t.prototype.fromPropertyOrder=function(t){return new je(this.fromFieldPathReference(t.field),this.fromDirection(t.direction))},t.prototype.toRelationFilter=function(t){return t instanceof Be?{fieldFilter:{field:this.toFieldPathReference(t.field),op:this.toOperatorName(t.op),value:this.toValue(t.value)}}:u("Unrecognized filter: "+JSON.stringify(t))},t.prototype.fromRelationFilter=function(t){return new Be(this.fromFieldPathReference(t.fieldFilter.field),this.fromOperatorName(t.fieldFilter.op),this.fromValue(t.fieldFilter.value))},t.prototype.toUnaryFilter=function(t){return t instanceof Fe?{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NAN"}}:t instanceof Ue?{unaryFilter:{field:this.toFieldPathReference(t.field),op:"IS_NULL"}}:u("Unrecognized filter: "+JSON.stringify(t))},t.prototype.fromUnaryFilter=function(t){switch(t.unaryFilter.op){case"IS_NAN":var e=this.fromFieldPathReference(t.unaryFilter.field);return new Fe(e);case"IS_NULL":var n=this.fromFieldPathReference(t.unaryFilter.field);return new Ue(n);case"OPERATOR_UNSPECIFIED":return u("Unspecified filter");default:return u("Unknown filter")}},t.prototype.toDocumentMask=function(t){return{fieldPaths:t.fields.map(function(t){return t.canonicalString()})}},t.prototype.fromDocumentMask=function(t){var e=t.fieldPaths||[],n=e.map(function(t){return ae.fromServerFormat(t)});return new Je(n)},t}(),Nn=n(115),An=function(){function t(t){this.wrappedOnOpen=null,this.wrappedOnClose=null,this.wrappedOnMessage=null,this.sendFn=t.sendFn,this.closeFn=t.closeFn}return t.prototype.onOpen=function(t){c(!this.wrappedOnOpen,"Called onOpen on stream twice!"),this.wrappedOnOpen=t},t.prototype.onClose=function(t){c(!this.wrappedOnClose,"Called onClose on stream twice!"),this.wrappedOnClose=t},t.prototype.onMessage=function(t){c(!this.wrappedOnMessage,"Called onMessage on stream twice!"),this.wrappedOnMessage=t},t.prototype.close=function(){this.closeFn()},t.prototype.send=function(t){this.sendFn(t)},t.prototype.callOnOpen=function(){c(null!==this.wrappedOnOpen,"Cannot call onOpen because no callback was set"),this.wrappedOnOpen()},t.prototype.callOnClose=function(t){c(null!==this.wrappedOnClose,"Cannot call onClose because no callback was set"),this.wrappedOnClose(t)},t.prototype.callOnMessage=function(t){c(null!==this.wrappedOnMessage,"Cannot call onMessage because no callback was set"),this.wrappedOnMessage(t)},t}(),Rn="Connection",On={BatchGetDocuments:"batchGet",Commit:"commit"},Mn="gl-js/ fire/"+Qt,_n=function(){function t(t){this.databaseId=t.databaseId,this.pool=new Nn.XhrIoPool;var e=t.ssl?"https":"http";this.baseUrl=e+"://"+t.host}return t.prototype.modifyHeadersForRequest=function(t,e){if(e)for(var n in e.authHeaders)e.authHeaders.hasOwnProperty(n)&&(t[n]=e.authHeaders[n]);t["X-Goog-Api-Client"]=Mn,t["google-cloud-resource-prefix"]="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database},t.prototype.invokeRPC=function(t,e,n){var r=this,o=this.makeUrl(t);return new Promise(function(a,s){r.pool.getObject(function(c){c.listenOnce(Nn.EventType.COMPLETE,function(){try{switch(c.getLastErrorCode()){case Nn.ErrorCode.NO_ERROR:var e=c.getResponseJson();i(Rn,"XHR received:",JSON.stringify(e)),a(e);break;case Nn.ErrorCode.TIMEOUT:i(Rn,'RPC "'+t+'" timed out'),s(new zt(Ht.DEADLINE_EXCEEDED,"Request time out"));break;case Nn.ErrorCode.HTTP_ERROR:var n=c.getStatus();i(Rn,'RPC "'+t+'" failed with status:',n,"response text:",c.getResponseText()),n>0?s(new zt(J(n),"Server responded with status "+c.getStatusText())):(i(Rn,'RPC "'+t+'" failed'),s(new zt(Ht.UNAVAILABLE,"Connection failed.")));break;default:u('RPC "'+t+'" failed with unanticipated webchannel error '+c.getLastErrorCode()+": "+c.getLastError()+", giving up.")}}finally{i(Rn,'RPC "'+t+'" completed.'),r.pool.releaseObject(c)}});var h=JSON.stringify(e);i(Rn,"XHR sending: ",o+" "+h);var l={"Content-Type":"text/plain"};r.modifyHeadersForRequest(l,n),c.send(o,"POST",h,l,15)})})},t.prototype.invokeStreamingRPC=function(t,e,n){return this.invokeRPC(t,e,n)},t.prototype.openStream=function(t,e){var n=[this.baseUrl,"/","google.firestore.v1beta1.Firestore","/",t,"/channel"],r=Object(Nn.createWebChannelTransport)(),o={backgroundChannelTest:!0,httpSessionIdParam:"gsessionid",initMessageHeaders:{},httpHeadersOverwriteParam:"$httpHeaders",sendRawJson:!0,supportsCrossDomainXhr:!0};this.modifyHeadersForRequest(o.initMessageHeaders,e);var a=n.join("");i(Rn,"Creating WebChannel: "+a+" "+o);var s=r.createWebChannel(a,o),u=!1,h=!1,l=new An({sendFn:function(t){h?i(Rn,"Not sending because WebChannel is closed:",t):(u||(i(Rn,"Opening WebChannel transport."),s.open(),u=!0),i(Rn,"WebChannel sending:",t),s.send(t))},closeFn:function(){return s.close()}}),f=function(t,e){s.listen(t,function(t){try{e(t)}catch(t){setTimeout(function(){throw t},0)}})};return f(Nn.WebChannel.EventType.OPEN,function(){h||i(Rn,"WebChannel transport opened.")}),f(Nn.WebChannel.EventType.CLOSE,function(){h||(h=!0,i(Rn,"WebChannel transport closed"),l.callOnClose())}),f(Nn.WebChannel.EventType.ERROR,function(t){h||(h=!0,i(Rn,"WebChannel transport errored:",t),l.callOnClose(new zt(Ht.UNAVAILABLE,"The operation could not be completed")))}),f(Nn.WebChannel.EventType.MESSAGE,function(t){if(!h){var e=t.data[0];c(!!e,"Got a webchannel message without data.");var n=e.error||e[0]&&e[0].error;if(n){i(Rn,"WebChannel received error:",n);var r=n.status,o=z(r),a=n.message;void 0===o&&(o=Ht.INTERNAL,a="Unknown error status: "+r+" with message "+n.message),h=!0,l.callOnClose(new zt(o,a)),s.close()}else i(Rn,"WebChannel received:",e),l.callOnMessage(e)}}),setTimeout(function(){l.callOnOpen()},0),l},t.prototype.makeUrl=function(t){var e=On[t];c(void 0!==e,"Unknown REST mapping for: "+t);var n=[this.baseUrl,"/","v1beta1"];return n.push("/projects/"),n.push(this.databaseId.projectId),n.push("/databases/"),n.push(this.databaseId.database),n.push("/documents"),n.push(":"),n.push(e),n.join("")},t}(),Pn=function(){function t(){this.emptyByteString="",this.base64Available="undefined"!=typeof atob}return t.prototype.loadConnection=function(t){return Promise.resolve(new _n(t))},t.prototype.newSerializer=function(t){return new kn(t,{useProto3Json:!0})},t.prototype.formatJSON=function(t){return JSON.stringify(t)},t.prototype.atob=function(t){return atob(t)},t.prototype.btoa=function(t){return btoa(t)},t}();Wt.setPlatform(new Pn);var Ln,xn=function(){function t(){for(var t=[],e=0;e=0&&(r.listeners.splice(o,1),n=0===r.listeners.length)}return n?(this.queries.delete(e),this.syncEngine.unlisten(e)):Promise.resolve()},t.prototype.onChange=function(t){for(var e=0,n=t;e0||t.syncStateChanged,"We got a new snapshot with no changes?"),!this.options.includeDocumentMetadataChanges){for(var e=[],n=0,r=t.docChanges;n0)return!0;var e=this.snap&&this.snap.hasPendingWrites!==t.hasPendingWrites;return!(!t.syncStateChanged&&!e)&&!0===this.options.includeQueryMetadataChanges},t.prototype.raiseInitialEvent=function(e){c(!this.raisedInitialEvent,"Trying to raise initial events for second time"),e={query:e.query,docs:e.docs,oldDocs:jn.emptySet(e.docs),docChanges:t.getInitialViewChanges(e),fromCache:e.fromCache,hasPendingWrites:e.hasPendingWrites,syncStateChanged:!0},this.raisedInitialEvent=!0,this.queryObserver.next(e)},t.getInitialViewChanges=function(t){var e=[];return t.docs.forEach(function(t){e.push({type:Un.Added,doc:t})}),e},t}(),Hn=function(){function t(t){var e=this;this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=null,this.isDone=!1,this.callbackAttached=!1,t(function(t){e.isDone=!0,e.result=t,e.nextCallback&&e.nextCallback(t)},function(t){e.isDone=!0,e.error=t,e.catchCallback&&e.catchCallback(t)})}return t.prototype.catch=function(t){return this.next(void 0,t)},t.prototype.next=function(e,n){var r=this;return this.callbackAttached&&u("Called next() or catch() twice for PersistencePromise"),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(n,this.error):this.wrapSuccess(e,this.result):new t(function(t,o){r.nextCallback=function(n){r.wrapSuccess(e,n).next(t,o)},r.catchCallback=function(e){r.wrapFailure(n,e).next(t,o)}})},t.prototype.toPromise=function(){var t=this;return new Promise(function(e,n){t.next(e,n)})},t.prototype.wrapUserFunction=function(e){try{var n=e();return n instanceof t?n:t.resolve(n)}catch(e){return t.reject(e)}},t.prototype.wrapSuccess=function(e,n){return e?this.wrapUserFunction(function(){return e(n)}):t.resolve(n)},t.prototype.wrapFailure=function(e,n){return e?this.wrapUserFunction(function(){return e(n)}):t.reject(n)},t.resolve=function(e){return new t(function(t,n){t(e)})},t.reject=function(e){return new t(function(t,n){n(e)})},t.waitFor=function(e){return e.reduce(function(t,e,n){return t.next(function(){return e})},t.resolve())},t.map=function(e){var n=[],r=!0,o=t.resolve(null);return e.reduce(function(t,e){return t.next(function(t){return r||n.push(t),r=!1,e})},o).next(function(t){return n.push(t),n})},t}(),zn=function(){function t(){this.isEager=!0,this.sources=[],this.potentialGarbage=et()}return t.prototype.addGarbageSource=function(t){this.sources.push(t),t.setGarbageCollector(this)},t.prototype.removeGarbageSource=function(t){this.sources.splice(this.sources.indexOf(t),1),t.setGarbageCollector(null)},t.prototype.addPotentialGarbageKey=function(t){this.potentialGarbage=this.potentialGarbage.add(t)},t.prototype.collectGarbage=function(t){var e=this,n=[],r=et();return this.potentialGarbage.forEach(function(o){var i=e.documentHasAnyReferences(t,o);n.push(i.next(function(t){return t||(r=r.add(o)),Hn.resolve()}))}),this.potentialGarbage=et(),Hn.waitFor(n).next(function(){return r})},t.prototype.documentHasAnyReferences=function(t,e){var n=Hn.resolve(!1);return this.sources.map(function(n){return function(){return n.containsKey(t,e)}}).reduce(function(t,e){return t.next(function(t){return t?Hn.resolve(!0):e()})},n)},t}(),Xn=function(){function t(t,e,n){this.query=t,this.addedKeys=e,this.removedKeys=n}return t.fromSnapshot=function(e){for(var n=et(),r=et(),o=0,i=e.docChanges;o>$n<<$n,r=e-n;this.previousId=r>=t?n|this.generatorId:(n|this.generatorId)-(1<<$n)}return t.prototype.next=function(){return this.previousId+=1<<$n,this.previousId},t.forLocalStore=function(e){return void 0===e&&(e=0),new t(Vn.LocalStore,e)},t.forSyncEngine=function(){return new t(Vn.SyncEngine)},t}(),er=function(){function t(t){this.key=t}return t}(),nr=function(){function t(t){this.key=t}return t}(),rr=function(){function t(t,e){this.query=t,this.syncedDocuments=e,this.syncState=null,this.current=!1,this.limboDocuments=et(),this.mutatedKeys=et(),this.documentSet=new jn(t.docComparator.bind(t))}return t.prototype.computeDocChanges=function(t,e){var n=this,r=e?e.changeSet:new qn,o=e?e.documentSet:this.documentSet,i=e?e.mutatedKeys:this.mutatedKeys,a=o,s=!1,u=this.query.hasLimit()&&o.size===this.query.limit?o.last():null;if(t.inorderTraversal(function(t,e){var h=o.get(t),l=e instanceof ue?e:null;if(l&&(c(t.equals(l.key),"Mismatching keys found in document changes: "+t+" != "+l.key),l=n.query.matches(l)?l:null),l?(a=a.add(l),i=l.hasLocalMutations?i.add(t):i.delete(t)):(a=a.delete(t),i=i.delete(t)),h&&l){var f=h.data.equals(l.data);f&&h.hasLocalMutations===l.hasLocalMutations||(f?r.track({type:Un.Metadata,doc:l}):r.track({type:Un.Modified,doc:l}),u&&n.query.docComparator(l,u)>0&&(s=!0))}else!h&&l?r.track({type:Un.Added,doc:l}):h&&!l&&(r.track({type:Un.Removed,doc:h}),u&&(s=!0))}),this.query.hasLimit())for(;a.size>this.query.limit;){var h=a.last();a=a.delete(h.key),r.track({type:Un.Removed,doc:h})}return c(!s||!e,"View was refilled using docs that themselves needed refilling."),{documentSet:a,changeSet:r,needsRefill:s,mutatedKeys:i}},t.prototype.applyChanges=function(t,e){var n=this;c(!t.needsRefill,"Cannot apply changes that need a refill");var r=this.documentSet;this.documentSet=t.documentSet,this.mutatedKeys=t.mutatedKeys;var o=t.changeSet.getChanges();o.sort(function(t,e){return st(t.type,e.type)||n.query.docComparator(t.doc,e.doc)});var i=this.applyTargetChange(e),a=0===this.limboDocuments.size&&this.current,s=a?Fn.Synced:Fn.Local,u=s!==this.syncState;return this.syncState=s,0!==o.length||u?{snapshot:{query:this.query,docs:t.documentSet,oldDocs:r,docChanges:o,fromCache:s===Fn.Local,syncStateChanged:u,hasPendingWrites:!t.mutatedKeys.isEmpty()},limboChanges:i}:{limboChanges:i}},t.prototype.shouldBeInLimbo=function(t){return!this.syncedDocuments.has(t)&&!!this.documentSet.has(t)&&!this.documentSet.get(t).hasLocalMutations},t.prototype.applyTargetChange=function(t){var e=this;if(t){var n=t.mapping;switch(n instanceof bn?this.syncedDocuments=n.documents:n instanceof wn&&(this.syncedDocuments=n.applyToKeySet(this.syncedDocuments)),t.currentStatusUpdate){case hn.MarkCurrent:this.current=!0;break;case hn.MarkNotCurrent:this.current=!1;break;case hn.None:break;default:u("Unknown current status update: "+t.currentStatusUpdate)}}var r=this.limboDocuments;this.limboDocuments=et(),this.current&&this.documentSet.forEach(function(t){e.shouldBeInLimbo(t.key)&&(e.limboDocuments=e.limboDocuments.add(t.key))});var o=[];return r.forEach(function(t){e.limboDocuments.has(t)||o.push(new nr(t))}),this.limboDocuments.forEach(function(t){r.has(t)||o.push(new er(t))}),o},t}(),or=function(){function t(t,e,n,r){this.query=t,this.targetId=e,this.resumeToken=n,this.view=r}return t}(),ir=function(){function t(t,e,n){this.localStore=t,this.remoteStore=e,this.currentUser=n,this.viewHandler=null,this.errorHandler=null,this.queryViewsByQuery=new Qn(function(t){return t.canonicalId()}),this.queryViewsByTarget={},this.limboTargetsByKey=new he(se.comparator),this.limboKeysByTarget={},this.limboDocumentRefs=new Yn,this.limboCollector=new zn,this.mutationUserCallbacks={},this.targetIdGenerator=tr.forSyncEngine()}return t.prototype.subscribe=function(t,e){c(null!==t&&null!==e,"View and error handlers cannot be null"),c(null===this.viewHandler&&null===this.errorHandler,"SyncEngine already has a subscriber."),this.viewHandler=t,this.errorHandler=e,this.limboCollector.addGarbageSource(this.limboDocumentRefs)},t.prototype.listen=function(t){var e=this;return this.assertSubscribed("listen()"),c(!this.queryViewsByQuery.has(t),"We already listen to the query: "+t),this.localStore.allocateQuery(t).then(function(n){return e.localStore.executeQuery(t).then(function(r){return e.localStore.remoteDocumentKeys(n.targetId).then(function(o){var i=new rr(t,o),a=i.computeDocChanges(r),s=i.applyChanges(a);c(0===s.limboChanges.length,"View returned limbo docs before target ack from the server."),c(!!s.snapshot,"applyChanges for new view should always return a snapshot");var u=new or(t,n.targetId,n.resumeToken,i);e.queryViewsByQuery.set(t,u),e.queryViewsByTarget[n.targetId]=u,e.viewHandler([s.snapshot]),e.remoteStore.listen(n)})}).then(function(){return n.targetId})})},t.prototype.unlisten=function(t){var e=this;this.assertSubscribed("unlisten()");var n=this.queryViewsByQuery.get(t);return c(!!n,"Trying to unlisten on query not found:"+t),this.localStore.releaseQuery(t).then(function(){return e.remoteStore.unlisten(n.targetId),e.removeAndCleanupQuery(n).then(function(){return e.localStore.collectGarbage()})})},t.prototype.write=function(t,e){var n=this;return this.assertSubscribed("write()"),this.localStore.localWrite(t).then(function(t){return n.addMutationCallback(t.batchId,e),n.emitNewSnapsAndNotifyLocalStore(t.changes)}).then(function(){return n.remoteStore.fillWritePipeline()})},t.prototype.wrapUpdateFunctionError=function(t){return t},t.prototype.runTransaction=function(t,e){var n=this;void 0===e&&(e=5),c(e>=0,"Got negative number of retries for transaction.");var r=this.remoteStore.createTransaction();return function(){try{var e=t(r);return!K(e)&&e.catch&&e.then?e.catch(function(t){return Promise.reject(n.wrapUpdateFunctionError(t))}):Promise.reject(Error("Transaction callback must return a Promise"))}catch(t){return Promise.reject(n.wrapUpdateFunctionError(t))}}().then(function(o){return r.commit().then(function(){return o}).catch(function(r){return 0===e?Promise.reject(r):n.runTransaction(t,e-1)})})},t.prototype.applyRemoteEvent=function(t){var e=this;return this.assertSubscribed("applyRemoteEvent()"),p(t.targetChanges,function(n,r){var o=e.limboKeysByTarget[n];o&&r.currentStatusUpdate===hn.MarkCurrent&&!t.documentUpdates.get(o)&&t.addDocumentUpdate(new ce(o,t.snapshotVersion))}),this.localStore.applyRemoteEvent(t).then(function(n){return e.emitNewSnapsAndNotifyLocalStore(n,t)})},t.prototype.rejectListen=function(t,e){var n=this;this.assertSubscribed("rejectListens()");var r=this.limboKeysByTarget[t];if(r){this.limboTargetsByKey=this.limboTargetsByKey.remove(r),delete this.limboKeysByTarget[t];var o=new he(se.comparator);o=o.insert(r,new ce(r,He.forDeletedDoc()));var i=new mn(He.MIN,{},o);return this.applyRemoteEvent(i)}var a=this.queryViewsByTarget[t];return c(!!a,"Unknown targetId: "+t),this.localStore.releaseQuery(a.query).then(function(){return n.removeAndCleanupQuery(a).then(function(){n.errorHandler(a.query,e)})})},t.prototype.applySuccessfulWrite=function(t){var e=this;return this.assertSubscribed("applySuccessfulWrite()"),this.processUserCallback(t.batch.batchId,null),this.localStore.acknowledgeBatch(t).then(function(t){return e.emitNewSnapsAndNotifyLocalStore(t)})},t.prototype.rejectFailedWrite=function(t,e){var n=this;return this.assertSubscribed("rejectFailedWrite()"),this.processUserCallback(t,e),this.localStore.rejectBatch(t).then(function(t){return n.emitNewSnapsAndNotifyLocalStore(t)})},t.prototype.addMutationCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];n||(n=new he(L)),n=n.insert(t,e),this.mutationUserCallbacks[this.currentUser.toKey()]=n},t.prototype.processUserCallback=function(t,e){var n=this.mutationUserCallbacks[this.currentUser.toKey()];if(n){var r=n.get(t);r&&(c(t===n.minKey(),"Mutation callbacks processed out-of-order?"),e?r.reject(e):r.resolve(),n=n.remove(t)),this.mutationUserCallbacks[this.currentUser.toKey()]=n}},t.prototype.removeAndCleanupQuery=function(t){return this.queryViewsByQuery.delete(t.query),delete this.queryViewsByTarget[t.targetId],this.limboDocumentRefs.removeReferencesForId(t.targetId),this.gcLimboDocuments()},t.prototype.updateTrackedLimbos=function(t,e){for(var n=0,r=e;n0||t.indexOf("Trident/")>0||t.indexOf("Edge/")>0)},t.prototype.runTransaction=function(t,e,n){var r=new Dr(this.db,t,e),o=n(r).catch(function(t){return r.abort(),Hn.reject(t)}).toPromise();return r.completionPromise.then(function(){return o})},t.prototype.close=function(){this.db.close()},t}(),Cr=function(){function t(t){this.dbCursor=t,this.shouldStop=!1,this.nextKey=null}return Object.defineProperty(t.prototype,"isDone",{get:function(){return this.shouldStop},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skipToKey",{get:function(){return this.nextKey},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cursor",{set:function(t){this.dbCursor=t},enumerable:!0,configurable:!0}),t.prototype.done=function(){this.shouldStop=!0},t.prototype.skip=function(t){this.nextKey=t},t.prototype.delete=function(){return dt(this.dbCursor.delete())},t}(),Dr=function(){function t(t,e,n){var r=this;this.aborted=!1,this.transaction=t.transaction(n,e),this.completionPromise=new Promise(function(t,e){r.transaction.onabort=r.transaction.oncomplete=function(e){t()},r.transaction.onerror=function(t){e(t.target.error)}})}return t.prototype.abort=function(){this.aborted||(i("SimpleDb","Aborting transaction."),this.aborted=!0,this.transaction.abort())},t.prototype.store=function(t){var e=this.transaction.objectStore(t);return c(!!e,"Object store not part of transaction: "+t),new kr(e)},t}(),kr=function(){function t(t){this.store=t}return t.prototype.put=function(t,e){var n;return void 0!==e?(i("SimpleDb","PUT",this.store.name,t,e),n=this.store.put(e,t)):(i("SimpleDb","PUT",this.store.name,"",t),n=this.store.put(t)),dt(n)},t.prototype.get=function(t){var e=this;return dt(this.store.get(t)).next(function(n){return void 0===n&&(n=null),i("SimpleDb","GET",e.store.name,t,n),n})},t.prototype.delete=function(t){return i("SimpleDb","DELETE",this.store.name,t),dt(this.store.delete(t))},t.prototype.loadAll=function(t,e){var n=this.cursor(this.options(t,e)),r=[];return this.iterateCursor(n,function(t,e){r.push(e)}).next(function(){return r})},t.prototype.deleteAll=function(t,e){i("SimpleDb","DELETE ALL",this.store.name);var n=this.options(t,e);n.keysOnly=!1;var r=this.cursor(n);return this.iterateCursor(r,function(t,e,n){return n.delete()})},t.prototype.iterate=function(t,e){var n;e?n=t:(n={},e=t);var r=this.cursor(n);return this.iterateCursor(r,e)},t.prototype.iterateCursor=function(t,e){var n=[];return new Hn(function(r,o){t.onerror=function(t){o(t.target.error)},t.onsuccess=function(t){var o=t.target.result;if(!o)return void r();var i=new Cr(o),a=e(o.primaryKey,o.value,i);a instanceof Hn&&n.push(a),i.isDone?r():null===i.skipToKey?o.continue():o.continue(i.skipToKey)}}).next(function(){return Hn.waitFor(n)})},t.prototype.options=function(t,e){var n=void 0;return void 0!==t&&("string"==typeof t?n=t:(c(void 0===e,"3rd argument must not be defined if 2nd is a range."),e=t)),{index:n,range:e}},t.prototype.cursor=function(t){var e="next";if(t.reverse&&(e="prev"),t.index){var n=this.store.index(t.index);return t.keysOnly?n.openKeyCursor(t.range,e):n.openCursor(t.range,e)}return this.store.openCursor(t.range,e)},t}(),Nr=function(){function t(t,e){this.userId=t,this.serializer=e,this.garbageCollector=null}return t.forUser=function(e,n){return c(""!==e.uid,"UserID must not be an empty string."),new t(e.isUnauthenticated()?"":e.uid,n)},t.prototype.start=function(e){var n=this;return t.loadNextBatchIdFromDb(e).next(function(t){return n.nextBatchId=t,gt(e).get(n.userId)}).next(function(t){return t||(t=new yr(n.userId,ar,"")),n.metadata=t,n.metadata.lastAcknowledgedBatchId>=n.nextBatchId?n.checkEmpty(e).next(function(t){return c(t,"Reset nextBatchID is only possible when the queue is empty"),n.metadata.lastAcknowledgedBatchId=ar,gt(e).put(n.metadata)}):Hn.resolve()})},t.loadNextBatchIdFromDb=function(t){var e=ar;return yt(t).iterate({reverse:!0},function(t,n,r){var o=t[0];if(t[1]>e&&(e=n.batchId),""===o)r.done();else{var i=U(o);r.skip([i])}}).next(function(){return e+1})},t.prototype.checkEmpty=function(t){var e=!0,n=IDBKeyRange.bound(this.keyForBatchId(Number.NEGATIVE_INFINITY),this.keyForBatchId(Number.POSITIVE_INFINITY));return yt(t).iterate({range:n},function(t,n,r){e=!1,r.done()}).next(function(){return e})},t.prototype.getNextBatchId=function(t){return Hn.resolve(this.nextBatchId)},t.prototype.getHighestAcknowledgedBatchId=function(t){return Hn.resolve(this.metadata.lastAcknowledgedBatchId)},t.prototype.acknowledgeBatch=function(t,e,n){var r=e.batchId;return c(r>this.metadata.lastAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order"),this.metadata.lastAcknowledgedBatchId=r,this.metadata.lastStreamToken=pt(n),gt(t).put(this.metadata)},t.prototype.getLastStreamToken=function(t){return Hn.resolve(this.metadata.lastStreamToken)},t.prototype.setLastStreamToken=function(t,e){return this.metadata.lastStreamToken=pt(e),gt(t).put(this.metadata)},t.prototype.addMutationBatch=function(t,e,n){var r=this,o=this.nextBatchId;this.nextBatchId++;var i=new sr(o,e,n),a=this.serializer.toDbMutationBatch(this.userId,i);return yt(t).put(a).next(function(){for(var e=[],i=0,a=n;ie,"Should have found mutation after "+e),o=n.serializer.fromDbMutationBatch(r)),i.done()}).next(function(){return o})},t.prototype.getAllMutationBatches=function(t){var e=this,n=IDBKeyRange.bound(this.keyForBatchId(ar),this.keyForBatchId(Number.POSITIVE_INFINITY));return yt(t).loadAll(n).next(function(t){return t.map(function(t){return e.serializer.fromDbMutationBatch(t)})})},t.prototype.getAllMutationBatchesThroughBatchId=function(t,e){var n=this,r=IDBKeyRange.bound(this.keyForBatchId(ar),this.keyForBatchId(e));return yt(t).loadAll(r).next(function(t){return t.map(function(t){return n.serializer.fromDbMutationBatch(t)})})},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=gr.prefixForPath(this.userId,e.path),o=IDBKeyRange.lowerBound(r),i=[];return mt(t).iterate({range:o},function(r,o,a){var s=r[0],c=r[1],h=r[2],l=lt(c);if(s!==n.userId||!e.path.equals(l))return void a.done();var f=n.keyForBatchId(h);return yt(t).get(f).next(function(t){null===t&&u("Dangling document-mutation reference found: "+r+" which points to "+f),i.push(n.serializer.fromDbMutationBatch(t))})}).next(function(){return i})},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=this;c(!e.isDocumentQuery(),"Document queries shouldn't go down this path");var r=e.path,o=r.length+1,i=gr.prefixForPath(this.userId,r),a=(i[1],IDBKeyRange.lowerBound(i)),s=new ln(L);return mt(t).iterate({range:a},function(t,e,i){var a=t[0],u=t[1],c=t[2],h=lt(u);if(a!==n.userId||!r.isPrefixOf(h))return void i.done();h.length===o&&(s=s.add(c))}).next(function(){var e=[],r=[];return s.forEach(function(o){var i=n.keyForBatchId(o);r.push(yt(t).get(i).next(function(t){null===t&&u("Dangling document-mutation reference found, which points to "+i),e.push(n.serializer.fromDbMutationBatch(t))}))}),Hn.waitFor(r).next(function(){return e})})},t.prototype.removeMutationBatches=function(t,e){for(var n=yt(t),r=mt(t),o=[],i=this,a=0,s=e;athis.metadata.highestTargetId?(this.metadata.highestTargetId=r,o.next(function(){return wt(t).put(Tr.key,n.metadata)})):o},t.prototype.removeQueryData=function(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(function(){bt(t).delete(e.targetId)})},t.prototype.getQueryData=function(t,e){var n=this,r=e.canonicalId(),o=IDBKeyRange.bound([r,Number.NEGATIVE_INFINITY],[r,Number.POSITIVE_INFINITY]),i=null;return bt(t).iterate({range:o,index:wr.queryTargetsIndexName},function(t,r,o){var a=n.serializer.fromDbTarget(r);e.equals(a.query)&&(i=a,o.done())}).next(function(){return i})},t.prototype.addMatchingKeys=function(t,e,n){var r=[],o=It(t);return e.forEach(function(t){var e=ut(t.path);r.push(o.put(new Ir(n,e)))}),Hn.waitFor(r)},t.prototype.removeMatchingKeys=function(t,e,n){var r=this,o=[],i=It(t);return e.forEach(function(t){var e=ut(t.path);o.push(i.delete([n,e])),null!==r.garbageCollector&&r.garbageCollector.addPotentialGarbageKey(t)}),Hn.waitFor(o)},t.prototype.removeMatchingKeysForTargetId=function(t,e){var n=It(t),r=IDBKeyRange.bound([e],[e+1],!1,!0);return this.notifyGCForRemovedKeys(t,r).next(function(){return n.delete(r)})},t.prototype.notifyGCForRemovedKeys=function(t,e){var n=this,r=It(t);return null!==this.garbageCollector&&this.garbageCollector.isEager?r.iterate({range:e,keysOnly:!0},function(t,e,r){var o=lt(t[1]),i=new se(o);c(null!==n.garbageCollector,"GarbageCollector for query cache set to null during key removal."),n.garbageCollector.addPotentialGarbageKey(i)}):Hn.resolve()},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=IDBKeyRange.bound([e],[e+1],!1,!0),r=It(t),o=et();return r.iterate({range:n,keysOnly:!0},function(t,e,n){var r=lt(t[1]),i=new se(r);o=o.add(i)}).next(function(){return o})},t.prototype.setGarbageCollector=function(t){this.garbageCollector=t},t.prototype.containsKey=function(t,e){c(null!==t,"Persistence Transaction cannot be null for query cache containsKey");var n=ut(e.path),r=IDBKeyRange.bound([n],[F(n)],!1,!0),o=0;return It(t).iterate({index:Ir.documentTargetsIndex,keysOnly:!0,range:r},function(t,e,n){o++,n.done()}).next(function(){return o>0})},t}(),Rr=function(){function t(t){this.serializer=t}return t.prototype.addEntry=function(t,e){return Et(t).put(St(e.key),this.serializer.toDbRemoteDocument(e))},t.prototype.removeEntry=function(t,e){return Et(t).delete(St(e))},t.prototype.getEntry=function(t,e){var n=this;return Et(t).get(St(e)).next(function(t){return t?n.serializer.fromDbRemoteDocument(t):null})},t.prototype.getDocumentsMatchingQuery=function(t,e){var n=this,r=Z(),o=e.path.toArray(),i=IDBKeyRange.lowerBound(o);return Et(t).iterate({range:i},function(t,o,i){var a=n.serializer.fromDbRemoteDocument(o);e.path.isPrefixOf(a.key.path)?a instanceof ue&&e.matches(a)&&(r=r.insert(a.key,a)):i.done()}).next(function(){return r})},t}(),Or=function(){function t(t){this.remoteSerializer=t}return t.prototype.fromDbRemoteDocument=function(t){if(t.document)return this.remoteSerializer.fromDocument(t.document);if(t.noDocument){var e=se.fromSegments(t.noDocument.path),n=t.noDocument.readTime,r=new Ge(n.seconds,n.nanos);return new ce(e,He.fromTimestamp(r))}return u("Unexpected DbRemoteDocument")},t.prototype.toDbRemoteDocument=function(t){if(t instanceof ue){var e=this.remoteSerializer.toDocument(t);return new br(null,e)}var n=t.key.path.toArray(),r=t.version.toTimestamp(),o=new dr(r.seconds,r.nanos);return new br(new vr(n,o),null)},t.prototype.toDbMutationBatch=function(t,e){var n=this,r=e.mutations.map(function(t){return n.remoteSerializer.toMutation(t)});return new mr(t,e.batchId,e.localWriteTime.toEpochMilliseconds(),r)},t.prototype.fromDbMutationBatch=function(t){var e=this,n=t.mutations.map(function(t){return e.remoteSerializer.fromMutation(t)}),r=Ge.fromEpochMilliseconds(t.localWriteTimeMs);return new sr(t.batchId,r,n)},t.prototype.fromDbTarget=function(t){var e,n=new Ge(t.readTime.seconds,t.readTime.nanos),r=He.fromTimestamp(n);return e=Ct(t.query)?this.remoteSerializer.fromDocumentsTarget(t.query):this.remoteSerializer.fromQueryTarget(t.query),new Xe(e,t.targetId,me.Listen,r,t.resumeToken)},t.prototype.toDbTarget=function(t){c(me.Listen===t.purpose,"Only queries with purpose "+me.Listen+" may be stored, got "+t.purpose);var e,n=t.snapshotVersion.toTimestamp(),r=new dr(n.seconds,n.nanos);e=t.query.isDocumentQuery()?this.remoteSerializer.toDocumentsTarget(t.query):this.remoteSerializer.toQueryTarget(t.query),c("string"==typeof t.resumeToken,"Persisting non-string resume token not supported.");var o=t.resumeToken;return new wr(t.targetId,t.query.canonicalId(),r,o,0,e)},t}(),Mr="There is another tab open with offline persistence enabled. Only one such tab is allowed at a time. The other tab must be closed or persistence must be disabled.",_r=function(){function t(e,n){this.ownerId=this.generateOwnerId(),this.dbName=e+t.MAIN_DATABASE,this.serializer=new Or(n),this.localStoragePrefix=e}return t.prototype.start=function(){var e=this;return t.isAvailable()?(c(!this.started,"IndexedDbPersistence double-started!"),this.started=!0,Sr.openOrCreate(this.dbName,1,ft).then(function(t){e.simpleDb=t}).then(function(){return e.tryAcquireOwnerLease()}).then(function(){e.scheduleOwnerLeaseRefreshes(),e.attachWindowUnloadHook()})):(this.persistenceError=new zt(Ht.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled."),Promise.reject(this.persistenceError))},t.prototype.shutdown=function(){var t=this;return c(this.started,"IndexedDbPersistence shutdown without start!"),this.started=!1,this.detachWindowUnloadHook(),this.stopOwnerLeaseRefreshes(),this.releaseOwnerLease().then(function(){t.simpleDb.close()})},t.prototype.getMutationQueue=function(t){return Nr.forUser(t,this.serializer)},t.prototype.getQueryCache=function(){return new Ar(this.serializer)},t.prototype.getRemoteDocumentCache=function(){return new Rr(this.serializer)},t.prototype.runTransaction=function(t,e){var n=this;return this.persistenceError?Promise.reject(this.persistenceError):(i("IndexedDbPersistence","Starting transaction:",t),this.simpleDb.runTransaction("readwrite",Er,function(t){return n.ensureOwnerLease(t).next(function(){return e(t)})}))},t.isAvailable=function(){return Sr.isAvailable()},t.buildStoragePrefix=function(t){var e=t.databaseId.projectId;return t.databaseId.isDefaultDatabase||(e+="."+t.databaseId.database),"firestore/"+t.persistenceKey+"/"+e+"/"},t.prototype.tryAcquireOwnerLease=function(){var t=this;return this.simpleDb.runTransaction("readwrite",[pr.store],function(e){var n=e.store(pr.store);return n.get("owner").next(function(e){if(t.validOwner(e))return i("IndexedDbPersistence","Valid owner already. Failing. Current owner:",e),t.persistenceError=new zt(Ht.FAILED_PRECONDITION,Mr),Hn.reject(t.persistenceError);var r=new pr(t.ownerId,Date.now());return i("IndexedDbPersistence","No valid owner. Acquiring owner lease. Current owner:",e,"New owner:",r),n.put("owner",r)})})},t.prototype.releaseOwnerLease=function(){var t=this;return this.simpleDb.runTransaction("readwrite",[pr.store],function(e){var n=e.store(pr.store);return n.get("owner").next(function(e){return null!==e&&e.ownerId===t.ownerId?(i("IndexedDbPersistence","Releasing owner lease."),n.delete("owner")):Hn.resolve()})})},t.prototype.ensureOwnerLease=function(t){var e=this;return t.store(pr.store).get("owner").next(function(t){return null===t||t.ownerId!==e.ownerId?(e.persistenceError=new zt(Ht.FAILED_PRECONDITION,Mr),Hn.reject(e.persistenceError)):Hn.resolve()})},t.prototype.validOwner=function(t){var e=Date.now(),n=e-5e3,r=e;return!(null===t||t.leaseTimestampMsr?(a("Persistence owner-lease is in the future. Discarding.",t),1):t.ownerId===this.getZombiedOwnerId()))},t.prototype.scheduleOwnerLeaseRefreshes=function(){var t=this;this.ownerLeaseRefreshHandle=setInterval(function(){t.runTransaction("Refresh owner timestamp",function(e){return e.store(pr.store).put("owner",new pr(t.ownerId,Date.now()))}).catch(function(e){a(e),t.stopOwnerLeaseRefreshes()})},4e3)},t.prototype.stopOwnerLeaseRefreshes=function(){this.ownerLeaseRefreshHandle&&(clearInterval(this.ownerLeaseRefreshHandle),this.ownerLeaseRefreshHandle=null)},t.prototype.attachWindowUnloadHook=function(){var t=this;this.windowUnloadHandler=function(){t.setZombiedOwnerId(t.ownerId),t.shutdown()},window.addEventListener("unload",this.windowUnloadHandler)},t.prototype.detachWindowUnloadHook=function(){this.windowUnloadHandler&&(window.removeEventListener("unload",this.windowUnloadHandler),this.windowUnloadHandler=null)},t.prototype.getZombiedOwnerId=function(){try{var t=window.localStorage.getItem(this.zombiedOwnerLocalStorageKey());return i("IndexedDbPersistence","Zombied ownerID from LocalStorage:",t),t}catch(t){return a("Failed to get zombie owner id.",t),null}},t.prototype.setZombiedOwnerId=function(t){try{null===t?window.localStorage.removeItem(this.zombiedOwnerLocalStorageKey()):window.localStorage.setItem(this.zombiedOwnerLocalStorageKey(),t)}catch(t){a("Failed to set zombie owner id.",t)}},t.prototype.zombiedOwnerLocalStorageKey=function(){return this.localStoragePrefix+"zombiedOwnerId"},t.prototype.generateOwnerId=function(){return Xt.newId()},t.MAIN_DATABASE="main",t}(),Pr=function(){function t(t,e){this.remoteDocumentCache=t,this.mutationQueue=e}return t.prototype.getDocument=function(t,e){var n=this;return this.remoteDocumentCache.getEntry(t,e).next(function(r){return n.computeLocalDocument(t,e,r)})},t.prototype.getDocuments=function(t,e){var n=this,r=[],o=$();return e.forEach(function(e){r.push(n.getDocument(t,e).next(function(t){t||(t=new ce(e,He.forDeletedDoc())),o=o.insert(e,t)}))}),Hn.waitFor(r).next(function(){return o})},t.prototype.getDocumentsMatchingQuery=function(t,e){return se.isDocumentKey(e.path)?this.getDocumentsMatchingDocumentQuery(t,e.path):this.getDocumentsMatchingCollectionQuery(t,e)},t.prototype.getDocumentsMatchingDocumentQuery=function(t,e){return this.getDocument(t,new se(e)).next(function(t){var e=Z();return t instanceof ue&&(e=e.insert(t.key,t)),e})},t.prototype.getDocumentsMatchingCollectionQuery=function(t,e){var n,r=this;return this.remoteDocumentCache.getDocumentsMatchingQuery(t,e).next(function(e){return r.computeLocalDocuments(t,e)}).next(function(o){return n=o,r.mutationQueue.getAllMutationBatchesAffectingQuery(t,e)}).next(function(e){for(var o=et(),i=0,a=e;i0?e.mutationQueue.removeMutationBatches(t,n):Hn.resolve()})},t.prototype.localWrite=function(t){var e=this;return this.persistence.runTransaction("Locally write mutations",function(n){var r,o=Ge.now();return e.mutationQueue.addMutationBatch(n,o,t).next(function(t){r=t;var o=r.keys();return e.localDocuments.getDocuments(n,o)}).next(function(t){return{batchId:r.batchId,changes:t}})})},t.prototype.acknowledgeBatch=function(t){var e=this;return this.persistence.runTransaction("Acknowledge batch",function(n){var r;return e.mutationQueue.acknowledgeBatch(n,t.batch,t.streamToken).next(function(){if(e.shouldHoldBatchResult(t.commitVersion))return e.heldBatchResults.push(t),r=et(),Hn.resolve();var o=new Lr(e.remoteDocuments);return e.releaseBatchResults(n,[t],o).next(function(t){return r=t,o.apply(n)})}).next(function(){return e.mutationQueue.performConsistencyCheck(n)}).next(function(){return e.localDocuments.getDocuments(n,r)})})},t.prototype.rejectBatch=function(t){var e=this;return this.persistence.runTransaction("Reject batch",function(n){var r,o;return e.mutationQueue.lookupMutationBatch(n,t).next(function(o){return c(null!=o,"Attempt to reject nonexistent batch!"),r=o,e.mutationQueue.getHighestAcknowledgedBatchId(n).next(function(e){return c(t>e,"Acknowledged batches can't be rejected."),r})}).next(function(){return e.removeMutationBatch(n,r)}).next(function(t){return o=t,e.mutationQueue.performConsistencyCheck(n)}).next(function(){return e.localDocuments.getDocuments(n,o)})})},t.prototype.getLastStreamToken=function(){var t=this;return this.persistence.runTransaction("Get last stream token",function(e){return t.mutationQueue.getLastStreamToken(e)})},t.prototype.setLastStreamToken=function(t){var e=this;return this.persistence.runTransaction("Set last stream token",function(n){return e.mutationQueue.setLastStreamToken(n,t)})},t.prototype.getLastRemoteSnapshotVersion=function(){return this.queryCache.getLastRemoteSnapshotVersion()},t.prototype.applyRemoteEvent=function(t){var e=this,n=new Lr(this.remoteDocuments);return this.persistence.runTransaction("Apply remote event",function(r){var o=[];p(t.targetChanges,function(t,n){var i=e.targetIds[t];if(i){var a=n.mapping;if(a)if(a instanceof bn)o.push(e.queryCache.removeMatchingKeysForTargetId(r,t).next(function(){return e.queryCache.addMatchingKeys(r,a.documents,t)}));else{if(!(a instanceof wn))return u("Unknown mapping type: "+JSON.stringify(a));o.push(e.queryCache.removeMatchingKeys(r,a.removedDocuments,t).next(function(){return e.queryCache.addMatchingKeys(r,a.addedDocuments,t)}))}var s=n.resumeToken;s.length>0&&(i=i.update({resumeToken:s,snapshotVersion:n.snapshotVersion}),e.targetIds[t]=i,o.push(e.queryCache.addQueryData(r,i)))}});var a=et();t.documentUpdates.forEach(function(t,s){a=a.add(t),o.push(n.getEntry(r,t).next(function(r){null==r||s.version.equals(He.MIN)||s.version.compareTo(r.version)>=0?n.addEntry(s):i("LocalStore","Ignoring outdated watch update for ",t,". Current version:",r.version," Watch version:",s.version),e.garbageCollector.addPotentialGarbageKey(t)}))});var s=e.queryCache.getLastRemoteSnapshotVersion(),h=t.snapshotVersion;h.equals(He.MIN)||(c(h.compareTo(s)>=0,"Watch stream reverted to previous snapshot?? "+h+" < "+s),o.push(e.queryCache.setLastRemoteSnapshotVersion(r,h)));var l;return Hn.waitFor(o).next(function(){return e.releaseHeldBatchResults(r,n)}).next(function(t){return l=t,n.apply(r)}).next(function(){return e.localDocuments.getDocuments(r,a.unionWith(l))})})},t.prototype.notifyLocalViewChanges=function(t){var e=this;return this.persistence.runTransaction("Notify local view changes",function(n){for(var r=[],o=0,i=t;o0},t.prototype.releaseBatchResults=function(t,e,n){for(var r=this,o=Hn.resolve(),i=0,a=e;ithis.highestAcknowledgedBatchId,"Mutation batchIDs must be acknowledged in order");var o=this.indexOfExistingBatchId(r,"acknowledged"),i=this.mutationQueue[o];return c(r===i.batchId,"Queue ordering failure: expected batch "+r+", got batch "+i.batchId),c(!i.isTombstone(),"Can't acknowledge a previously removed batch"),this.highestAcknowledgedBatchId=r,this.lastStreamToken=n,Hn.resolve()},t.prototype.getLastStreamToken=function(t){return Hn.resolve(this.lastStreamToken)},t.prototype.setLastStreamToken=function(t,e){return this.lastStreamToken=e,Hn.resolve()},t.prototype.addMutationBatch=function(t,e,n){c(0!==n.length,"Mutation batches should not be empty");var r=this.nextBatchId;this.nextBatchId++,this.mutationQueue.length>0&&c(this.mutationQueue[this.mutationQueue.length-1].batchId=n?r=n:r++,Hn.resolve(this.getAllLiveMutationBatchesBeforeIndex(r))},t.prototype.getAllMutationBatchesAffectingDocumentKey=function(t,e){var n=this,r=new Jn(e,0),o=new Jn(e,Number.POSITIVE_INFINITY),i=[];return this.batchesByDocumentKey.forEachInRange([r,o],function(t){c(e.equals(t.key),"Should only iterate over a single key's batches");var r=n.findMutationBatch(t.targetOrBatchId);c(null!==r,"Batches in the index must exist in the main table"),i.push(r)}),Hn.resolve(i)},t.prototype.getAllMutationBatchesAffectingQuery=function(t,e){var n=this,r=e.path,o=r.length+1,i=r;se.isDocumentKey(i)||(i=i.child(""));var a=new Jn(new se(i),0),s=new ln(L);this.batchesByDocumentKey.forEachWhile(function(t){var e=t.key.path;return!!r.isPrefixOf(e)&&(e.length===o&&(s=s.add(t.targetOrBatchId)),!0)},a);var u=[];return s.forEach(function(t){var e=n.findMutationBatch(t);null!==e&&u.push(e)}),Hn.resolve(u)},t.prototype.removeMutationBatches=function(t,e){var n=e.length;c(n>0,"Should not remove mutations when none exist.");var r=e[0].batchId,o=this.mutationQueue.length,i=this.indexOfExistingBatchId(r,"removed");c(this.mutationQueue[i].batchId===r,"Removed batches must exist in the queue");for(var a=1,s=i+1;a=0&&n=this.mutationQueue.length)return null;var n=this.mutationQueue[e];return c(n.batchId===t,"If found batch must match"),n.isTombstone()?null:n},t}(),Ur=function(){function t(){this.queries=new Qn(function(t){return t.canonicalId()}),this.lastRemoteSnapshotVersion=He.MIN,this.highestTargetId=0,this.references=new Yn}return t.prototype.start=function(t){return Hn.resolve()},t.prototype.getLastRemoteSnapshotVersion=function(){return this.lastRemoteSnapshotVersion},t.prototype.getHighestTargetId=function(){return this.highestTargetId},t.prototype.setLastRemoteSnapshotVersion=function(t,e){return this.lastRemoteSnapshotVersion=e,Hn.resolve()},t.prototype.addQueryData=function(t,e){this.queries.set(e.query,e);var n=e.targetId;return n>this.highestTargetId&&(this.highestTargetId=n),Hn.resolve()},t.prototype.removeQueryData=function(t,e){return this.queries.delete(e.query),this.references.removeReferencesForId(e.targetId),Hn.resolve()},t.prototype.getQueryData=function(t,e){var n=this.queries.get(e)||null;return Hn.resolve(n)},t.prototype.addMatchingKeys=function(t,e,n){return this.references.addReferences(e,n),Hn.resolve()},t.prototype.removeMatchingKeys=function(t,e,n){return this.references.removeReferences(e,n),Hn.resolve()},t.prototype.removeMatchingKeysForTargetId=function(t,e){return this.references.removeReferencesForId(e),Hn.resolve()},t.prototype.getMatchingKeysForTargetId=function(t,e){var n=this.references.referencesForId(e);return Hn.resolve(n)},t.prototype.setGarbageCollector=function(t){this.references.setGarbageCollector(t)},t.prototype.containsKey=function(t,e){return this.references.containsKey(t,e)},t}(),Fr=function(){function t(){this.docs=$()}return t.prototype.addEntry=function(t,e){return this.docs=this.docs.insert(e.key,e),Hn.resolve()},t.prototype.removeEntry=function(t,e){return this.docs=this.docs.remove(e),Hn.resolve()},t.prototype.getEntry=function(t,e){return Hn.resolve(this.docs.get(e))},t.prototype.getDocumentsMatchingQuery=function(t,e){for(var n=Z(),r=new se(e.path.child("")),o=this.docs.getIteratorFrom(r);o.hasNext();){var i=o.getNext(),a=i.key,s=i.value;if(!e.path.isPrefixOf(a.path))break;s instanceof ue&&e.matches(s)&&(n=n.insert(s.key,s))}return Hn.resolve(n)},t}(),Vr=function(){function t(){this.mutationQueues={},this.remoteDocumentCache=new Fr,this.queryCache=new Ur,this.started=!1}return t.prototype.start=function(){return c(!this.started,"MemoryPersistence double-started!"),this.started=!0,Promise.resolve()},t.prototype.shutdown=function(){return c(this.started,"MemoryPersistence shutdown without start!"),this.started=!1,Promise.resolve()},t.prototype.getMutationQueue=function(t){var e=this.mutationQueues[t.toKey()];return e||(e=new Br,this.mutationQueues[t.toKey()]=e),e},t.prototype.getQueryCache=function(){return this.queryCache},t.prototype.getRemoteDocumentCache=function(){return this.remoteDocumentCache},t.prototype.runTransaction=function(t,e){return i("MemoryPersistence","Starting transaction:",t),e(new qr).toPromise()},t}(),qr=function(){function t(){}return t}(),jr=function(){function t(){this.isEager=!1}return t.prototype.addGarbageSource=function(t){},t.prototype.removeGarbageSource=function(t){},t.prototype.addPotentialGarbageKey=function(t){},t.prototype.collectGarbage=function(t){return Hn.resolve(et())},t}(),Qr=function(){function t(){var t=this;this.promise=new Promise(function(e,n){t.resolve=e,t.reject=n})}return t}(),Kr=function(){function t(t,e,n){this.initialDelayMs=t,this.backoffFactor=e,this.maxDelayMs=n,this.reset()}return t.prototype.reset=function(){this.currentBaseMs=0},t.prototype.resetToMax=function(){this.currentBaseMs=this.maxDelayMs},t.prototype.backoffAndWait=function(){var t=new Qr,e=this.currentBaseMs+this.jitterDelayMs();return this.currentBaseMs>0&&i("ExponentialBackoff","Backing off for "+e+" ms (base delay: "+this.currentBaseMs+" ms)"),setTimeout(function(){t.resolve()},e),this.currentBaseMs*=this.backoffFactor,this.currentBaseMsthis.maxDelayMs&&(this.currentBaseMs=this.maxDelayMs),t.promise},t.prototype.jitterDelayMs=function(){return(Math.random()-.5)*this.currentBaseMs},t}(),Wr=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.Initial=0]="Initial",t[t.Auth=1]="Auth",t[t.Open=2]="Open",t[t.Error=3]="Error",t[t.Backoff=4]="Backoff",t[t.Stopped=5]="Stopped"}(Zn||(Zn={}));var Gr,Hr=1e3,zr=6e4,Xr=1.5,Yr=function(){function t(t,e,n,r){this.queue=t,this.connection=e,this.credentialsProvider=n,this.idle=!1,this.stream=null,this.listener=null,this.backoff=new Kr(r||Hr,Xr,zr),this.state=Zn.Initial}return t.prototype.isStarted=function(){return this.state===Zn.Backoff||this.state===Zn.Auth||this.state===Zn.Open},t.prototype.isOpen=function(){return this.state===Zn.Open},t.prototype.start=function(t){if(this.state===Zn.Error)return void this.performBackoff(t);c(this.state===Zn.Initial,"Already started"),this.listener=t,this.auth()},t.prototype.stop=function(){this.isStarted()&&this.close(Zn.Stopped)},t.prototype.inhibitBackoff=function(){c(!this.isStarted(),"Can only inhibit backoff in a stopped state"),this.state=Zn.Initial,this.backoff.reset()},t.prototype.markIdle=function(){var t=this;this.idle=!0,this.queue.schedule(function(){return t.handleIdleCloseTimer()},6e4).catch(function(t){c(t.code===Ht.CANCELLED,"Received unexpected error in idle timeout closure. Expected CANCELLED, but was: "+t)})},t.prototype.sendRequest=function(t){this.cancelIdleCheck(),this.stream.send(t)},t.prototype.handleIdleCloseTimer=function(){return this.isOpen()&&this.idle?this.close(Zn.Initial):Promise.resolve()},t.prototype.cancelIdleCheck=function(){this.idle=!1},t.prototype.close=function(t,e){c(t==Zn.Error||K(e),"Can't provide an error when not in an error state."),this.cancelIdleCheck(),t!=Zn.Error?this.backoff.reset():e&&e.code===Ht.RESOURCE_EXHAUSTED&&(a(""+e),a("Using maximum backoff delay to prevent overloading the backend."),this.backoff.resetToMax()),null!==this.stream&&(this.tearDown(),this.stream.close(),this.stream=null),this.state=t;var n=this.listener;return this.listener=null,t!=Zn.Stopped?n.onClose(e):Promise.resolve()},t.prototype.tearDown=function(){},t.prototype.auth=function(){var t=this;c(this.state===Zn.Initial,"Must be in initial state to auth"),this.state=Zn.Auth,this.credentialsProvider.getToken(!1).then(function(e){t.startStream(e)},function(e){t.queue.schedule(function(){if(t.state!==Zn.Stopped){var n=new zt(Ht.UNKNOWN,"Fetching auth token failed: "+e.message);return t.handleStreamClose(n)}return Promise.resolve()})})},t.prototype.startStream=function(t){var e=this;if(this.state!==Zn.Stopped){c(this.state===Zn.Auth,"Trying to start stream in a non-auth state");var n=function(t,n){e.queue.schedule(function(){return e.stream===t?n():Promise.resolve()})};if(null!==this.listener){var r=this.startRpc(t);this.stream=r,this.stream.onOpen(function(){n(r,function(){return c(e.state===Zn.Auth,"Expected stream to be in state auth, but was "+e.state),e.state=Zn.Open,e.listener.onOpen()})}),this.stream.onClose(function(t){n(r,function(){return e.handleStreamClose(t)})}),this.stream.onMessage(function(t){n(r,function(){return e.onMessage(t)})})}}},t.prototype.performBackoff=function(t){var e=this;c(this.state===Zn.Error,"Should only perform backoff in an error case"),this.state=Zn.Backoff,this.backoff.backoffAndWait().then(function(){e.queue.schedule(function(){return e.state===Zn.Stopped?Promise.resolve():(e.state=Zn.Initial,e.start(t),c(e.isStarted(),"PersistentStream should have started"),Promise.resolve())})})},t.prototype.handleStreamClose=function(t){return c(this.isStarted(),"Can't handle server close on non-started stream"),i("PersistentStream","close with error: "+t),this.stream=null,this.close(Zn.Error,t)},t}(),Jr=function(t){function e(e,n,r,o,i,a){var s=t.call(this,n,r,o,a)||this;return s.databaseInfo=e,s.serializer=i,s}return Wr(e,t),e.prototype.startRpc=function(t){return this.connection.openStream("Listen",t)},e.prototype.onMessage=function(t){this.backoff.reset();var e=this.serializer.fromWatchChange(t),n=this.serializer.versionFromListenResponse(t);return this.listener.onWatchChange(e,n)},e.prototype.watch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.addTarget=this.serializer.toTarget(t);var n=this.serializer.toListenRequestLabels(t);n&&(e.labels=n),this.sendRequest(e)},e.prototype.unwatch=function(t){var e={};e.database=this.serializer.encodedDatabaseId,e.removeTarget=t,this.sendRequest(e)},e}(Yr),$r=function(t){function e(e,n,r,o,i,a){var s=t.call(this,n,r,o,a)||this;return s.databaseInfo=e,s.serializer=i,s.y=!1,s}return Wr(e,t),Object.defineProperty(e.prototype,"handshakeComplete",{get:function(){return this.y},enumerable:!0,configurable:!0}),e.prototype.start=function(e){this.y=!1,t.prototype.start.call(this,e)},e.prototype.tearDown=function(){this.y&&this.writeMutations([])},e.prototype.startRpc=function(t){return this.connection.openStream("Write",t)},e.prototype.onMessage=function(t){if(c(!!t.streamToken,"Got a write response without a stream token"),this.lastStreamToken=t.streamToken,this.y){this.backoff.reset();var e=this.serializer.fromWriteResults(t.writeResults),n=this.serializer.fromVersion(t.commitTime);return this.listener.onMutationResult(n,e)}return c(!t.writeResults||0===t.writeResults.length,"Got mutation results for handshake"),this.y=!0,this.listener.onHandshakeComplete()},e.prototype.writeHandshake=function(){c(this.isOpen(),"Writing handshake requires an opened stream"),c(!this.y,"Handshake already completed");var t={};t.database=this.serializer.encodedDatabaseId,this.sendRequest(t)},e.prototype.writeMutations=function(t){var e=this;c(this.isOpen(),"Writing mutations requires an opened stream"),c(this.y,"Handshake must be complete before writing mutations"),c(this.lastStreamToken.length>0,"Trying to write mutation without a token");var n={streamToken:this.lastStreamToken,writes:t.map(function(t){return e.serializer.toMutation(t)})};this.sendRequest(n)},e}(Yr),Zr=function(){function t(t,e,n,r,o,i){this.databaseInfo=t,this.queue=e,this.connection=n,this.credentials=r,this.serializer=o,this.initialBackoffDelay=i}return t.prototype.newPersistentWriteStream=function(){return new $r(this.databaseInfo,this.queue,this.connection,this.credentials,this.serializer,this.initialBackoffDelay)},t.prototype.newPersistentWatchStream=function(){return new Jr(this.databaseInfo,this.queue,this.connection,this.credentials,this.serializer,this.initialBackoffDelay)},t.prototype.commit=function(t){var e=this,n={database:this.serializer.encodedDatabaseId,writes:t.map(function(t){return e.serializer.toMutation(t)})};return this.invokeRPC("Commit",n).then(function(t){return e.serializer.fromWriteResults(t.writeResults)})},t.prototype.lookup=function(t){var e=this,n={database:this.serializer.encodedDatabaseId,documents:t.map(function(t){return e.serializer.toName(t)})};return this.invokeStreamingRPC("BatchGetDocuments",n).then(function(n){var r=$();n.forEach(function(t){var n=e.serializer.fromMaybeDocument(t);r=r.insert(n.key,n)});var o=[];return t.forEach(function(t){var e=r.get(t);c(!!e,"Missing entity in write response for "+t),o.push(e)}),o})},t.prototype.invokeRPC=function(t,e){var n=this;return this.credentials.getToken(!1).then(function(r){return n.connection.invokeRPC(t,e,r)})},t.prototype.invokeStreamingRPC=function(t,e){var n=this;return this.credentials.getToken(!1).then(function(r){return n.connection.invokeStreamingRPC(t,e,r)})},t}(),to=function(){function t(t){this.datastore=t,this.readVersions=tt(),this.mutations=[],this.committed=!1}return t.prototype.recordVersion=function(t){var e=t.version;t instanceof ce&&(e=He.forDeletedDoc());var n=this.readVersions.get(t.key);if(null!==n){if(!e.equals(n))throw new zt(Ht.ABORTED,"Document version changed between two reads.")}else this.readVersions=this.readVersions.insert(t.key,e)},t.prototype.lookup=function(t){var e=this;return this.committed?Promise.reject("Transaction has already completed."):this.mutations.length>0?Promise.reject("Transactions lookups are invalid after writes."):this.datastore.lookup(t).then(function(t){return t.forEach(function(t){return e.recordVersion(t)}),t})},t.prototype.write=function(t){if(this.committed)throw new zt(Ht.FAILED_PRECONDITION,"Transaction has already completed.");this.mutations=this.mutations.concat(t)},t.prototype.precondition=function(t){var e=this.readVersions.get(t);return e?nn.updateTime(e):nn.NONE},t.prototype.preconditionForUpdate=function(t){var e=this.readVersions.get(t);if(e&&e.equals(He.forDeletedDoc()))throw new zt(Ht.FAILED_PRECONDITION,"Can't update a document that doesn't exist.");return e?nn.updateTime(e):nn.exists(!0)},t.prototype.set=function(t,e){this.write(e.toMutations(t,this.precondition(t)))},t.prototype.update=function(t,e){this.write(e.toMutations(t,this.preconditionForUpdate(t)))},t.prototype.delete=function(t){this.write([new un(t,this.precondition(t))]),this.readVersions=this.readVersions.insert(t,He.forDeletedDoc())},t.prototype.commit=function(){var t=this,e=this.readVersions;return this.mutations.forEach(function(t){e=e.remove(t.key)}),e.isEmpty()?this.datastore.commit(this.mutations).then(function(){t.committed=!0}):Promise.reject(Error("Every document read in a transaction must also be written."))},t}(),eo=function(){function t(t,e,n){this.localStore=t,this.datastore=e,this.onlineStateHandler=n,this.pendingWrites=[],this.lastBatchSeen=ar,this.listenTargets={},this.pendingTargetResponses={},this.accumulatedWatchChanges=[],this.watchStream=null,this.writeStream=null,this.watchStreamOnlineState=Ln.Unknown,this.watchStreamFailures=0,this.shouldWarnOffline=!0}return t.prototype.start=function(){return this.enableNetwork()},t.prototype.setOnlineStateToHealthy=function(){this.shouldWarnOffline=!1,this.updateAndBroadcastOnlineState(Ln.Healthy)},t.prototype.setOnlineStateToUnknown=function(){this.watchStreamFailures=0,this.updateAndBroadcastOnlineState(Ln.Unknown)},t.prototype.updateOnlineStateAfterFailure=function(){this.watchStreamOnlineState===Ln.Healthy?this.setOnlineStateToUnknown():++this.watchStreamFailures>=2&&(this.shouldWarnOffline&&(a("Could not reach Firestore backend."),this.shouldWarnOffline=!1),this.updateAndBroadcastOnlineState(Ln.Failed))},t.prototype.updateAndBroadcastOnlineState=function(t){var e=this.watchStreamOnlineState!==t;this.watchStreamOnlineState=t,e&&this.onlineStateHandler(t)},t.prototype.isNetworkEnabled=function(){return c(null==this.watchStream==(null==this.writeStream),"WatchStream and WriteStream should both be null or non-null"),null!=this.watchStream},t.prototype.enableNetwork=function(){var t=this;return c(null==this.watchStream,"enableNetwork() called with non-null watchStream."),c(null==this.writeStream,"enableNetwork() called with non-null writeStream."),this.watchStream=this.datastore.newPersistentWatchStream(),this.writeStream=this.datastore.newPersistentWriteStream(),this.localStore.getLastStreamToken().then(function(e){return t.writeStream.lastStreamToken=e,t.shouldStartWatchStream()&&t.startWatchStream(),t.updateAndBroadcastOnlineState(Ln.Unknown),t.fillWritePipeline()})},t.prototype.disableNetwork=function(){return this.updateAndBroadcastOnlineState(Ln.Failed),this.watchStream.stop(),this.writeStream.stop(),this.cleanUpWatchStreamState(),this.cleanUpWriteStreamState(),this.writeStream=null,this.watchStream=null,Promise.resolve()},t.prototype.shutdown=function(){return i("RemoteStore","RemoteStore shutting down."),this.disableNetwork(),Promise.resolve(void 0)},t.prototype.listen=function(t){c(!f(this.listenTargets,t.targetId),"listen called with duplicate targetId!"),this.listenTargets[t.targetId]=t,this.shouldStartWatchStream()?this.startWatchStream():this.isNetworkEnabled()&&this.watchStream.isOpen()&&this.sendWatchRequest(t)},t.prototype.unlisten=function(t){c(f(this.listenTargets,t),"unlisten called without assigned target ID!"),this.listenTargets[t],delete this.listenTargets[t],this.isNetworkEnabled()&&this.watchStream.isOpen()&&(this.sendUnwatchRequest(t),m(this.listenTargets)&&this.watchStream.markIdle())},t.prototype.sendWatchRequest=function(t){this.recordPendingTargetRequest(t.targetId),this.watchStream.watch(t)},t.prototype.sendUnwatchRequest=function(t){this.recordPendingTargetRequest(t),this.watchStream.unwatch(t)},t.prototype.recordPendingTargetRequest=function(t){this.pendingTargetResponses[t]=(this.pendingTargetResponses[t]||0)+1},t.prototype.startWatchStream=function(){c(this.shouldStartWatchStream(),"startWriteStream() called when shouldStartWatchStream() is false."),this.watchStream.start({onOpen:this.onWatchStreamOpen.bind(this),onClose:this.onWatchStreamClose.bind(this),onWatchChange:this.onWatchStreamChange.bind(this)})},t.prototype.shouldStartWatchStream=function(){return this.isNetworkEnabled()&&!this.watchStream.isStarted()&&!m(this.listenTargets)},t.prototype.cleanUpWatchStreamState=function(){this.accumulatedWatchChanges=[],this.pendingTargetResponses={}},t.prototype.onWatchStreamOpen=function(){var t=this;return p(this.listenTargets,function(e,n){t.sendWatchRequest(n)}),Promise.resolve()},t.prototype.onWatchStreamClose=function(t){return c(this.isNetworkEnabled(),"onWatchStreamClose() should only be called when the network is enabled"),this.cleanUpWatchStreamState(),this.shouldStartWatchStream()?(this.updateOnlineStateAfterFailure(),this.startWatchStream()):this.setOnlineStateToUnknown(),Promise.resolve()},t.prototype.onWatchStreamChange=function(t,e){if(this.setOnlineStateToHealthy(),t instanceof En&&t.state===gn.Removed&&t.cause)return this.handleTargetError(t);if(this.accumulatedWatchChanges.push(t),!e.equals(He.MIN)&&e.compareTo(this.localStore.getLastRemoteSnapshotVersion())>=0){var n=this.accumulatedWatchChanges;return this.accumulatedWatchChanges=[],this.handleWatchChangeBatch(e,n)}return Promise.resolve()},t.prototype.handleWatchChangeBatch=function(t,e){var n=this,r=new Sn(t,this.listenTargets,this.pendingTargetResponses);r.addChanges(e);var o=r.createRemoteEvent();this.pendingTargetResponses=r.pendingTargetResponses;var i=[];return p(r.existenceFilters,function(e,r){var a=n.listenTargets[e];if(a){var s=a.query;if(s.isDocumentQuery())if(0===r.count){var u=new se(s.path),h=new ce(u,t);o.addDocumentUpdate(h)}else c(1===r.count,"Single document existence filter with count: "+r.count);else{var l=n.localStore.remoteDocumentKeys(e).then(function(t){if(o.targetChanges[e]){var i=o.targetChanges[e].mapping;null!==i&&(i instanceof wn?t=i.applyToKeySet(t):(c(i instanceof bn,"Expected either reset or update mapping but got something else: "+i),t=i.documents))}if(t.size!==r.count){o.handleExistenceFilterMismatch(e);var u=new Xe(s,e,a.purpose);n.listenTargets[e]=u,n.sendUnwatchRequest(e);var h=new Xe(s,e,me.ExistenceFilterMismatch);n.sendWatchRequest(h)}});i.push(l)}}}),Promise.all(i).then(function(){return p(o.targetChanges,function(t,e){if(e.resumeToken.length>0){var r=n.listenTargets[t];r&&(n.listenTargets[t]=r.update({resumeToken:e.resumeToken,snapshotVersion:e.snapshotVersion}))}}),n.syncEngine.applyRemoteEvent(o)})},t.prototype.handleTargetError=function(t){var e=this;c(!!t.cause,"Handling target error without a cause");var n=t.cause,r=Promise.resolve();return t.targetIds.forEach(function(t){r=r.then(function(){return f(e.listenTargets,t)?(delete e.listenTargets[t],e.syncEngine.rejectListen(t,n)):Promise.resolve()})}),r},t.prototype.cleanUpWriteStreamState=function(){this.lastBatchSeen=ar,this.pendingWrites=[]},t.prototype.fillWritePipeline=function(){var t=this;return this.canWriteMutations()?this.localStore.nextMutationBatch(this.lastBatchSeen).then(function(e){return null===e?(0==t.pendingWrites.length&&t.writeStream.markIdle(),Promise.resolve()):(t.commit(e),t.fillWritePipeline())}):Promise.resolve()},t.prototype.canWriteMutations=function(){return this.isNetworkEnabled()&&this.pendingWrites.length<10},t.prototype.outstandingWrites=function(){return this.pendingWrites.length},t.prototype.commit=function(t){c(this.canWriteMutations(),"commit called when batches can't be written"),this.lastBatchSeen=t.batchId,this.pendingWrites.push(t),this.shouldStartWriteStream()?this.startWriteStream():this.isNetworkEnabled()&&this.writeStream.handshakeComplete&&this.writeStream.writeMutations(t.mutations)},t.prototype.shouldStartWriteStream=function(){return this.isNetworkEnabled()&&!this.writeStream.isStarted()&&this.pendingWrites.length>0},t.prototype.startWriteStream=function(){c(this.shouldStartWriteStream(),"startWriteStream() called when shouldStartWriteStream() is false."),this.writeStream.start({onOpen:this.onWriteStreamOpen.bind(this),onClose:this.onWriteStreamClose.bind(this),onHandshakeComplete:this.onWriteHandshakeComplete.bind(this),onMutationResult:this.onMutationResult.bind(this)})},t.prototype.onWriteStreamOpen=function(){return this.writeStream.writeHandshake(),Promise.resolve()},t.prototype.onWriteHandshakeComplete=function(){var t=this;return this.localStore.setLastStreamToken(this.writeStream.lastStreamToken).then(function(){for(var e=0,n=t.pendingWrites;e0,"Got result for empty pending writes");var r=this.pendingWrites.shift(),o=ur.from(r,t,e,this.writeStream.lastStreamToken);return this.syncEngine.applySuccessfulWrite(o).then(function(){return n.fillWritePipeline()})},t.prototype.onWriteStreamClose=function(t){var e=this;if(c(this.isNetworkEnabled(),"onWriteStreamClose() should only be called when the network is enabled"),t&&this.pendingWrites.length>0){c(!!t,"We have pending writes, but the write stream closed without an error");var n=void 0;return n=this.writeStream.handshakeComplete?this.handleWriteError(t):this.handleHandshakeError(t),n.then(function(){e.shouldStartWriteStream()&&e.startWriteStream()})}return Promise.resolve()},t.prototype.handleHandshakeError=function(t){return H(t.code)||t.code===Ht.ABORTED?(i("RemoteStore","RemoteStore error before completed handshake; resetting stream token: ",this.writeStream.lastStreamToken),this.writeStream.lastStreamToken=h(),this.localStore.setLastStreamToken(h())):Promise.resolve()},t.prototype.handleWriteError=function(t){var e=this;if(H(t.code)){var n=this.pendingWrites.shift();return this.writeStream.inhibitBackoff(),this.syncEngine.rejectFailedWrite(n.batchId,t).then(function(){return e.fillWritePipeline()})}return Promise.resolve()},t.prototype.createTransaction=function(){return new to(this.datastore)},t.prototype.handleUserChange=function(t){return i("RemoteStore","RemoteStore changing users: uid=",t.uid),this.disableNetwork(),this.enableNetwork()},t}(),no=function(){function t(t,e,n,r){this.platform=t,this.databaseInfo=e,this.credentials=n,this.asyncQueue=r}return t.prototype.start=function(t){var e=this,n=new Qr,r=new Qr,o=!1;return this.credentials.setUserChangeListener(function(i){o?e.asyncQueue.schedule(function(){return e.handleUserChange(i)}):(o=!0,e.initializePersistence(t,r).then(function(){return e.initializeRest(i)}).then(n.resolve,n.reject))}),this.asyncQueue.schedule(function(){return n.promise}),r.promise},t.prototype.enableNetwork=function(){var t=this;return this.asyncQueue.schedule(function(){return t.remoteStore.enableNetwork()})},t.prototype.initializePersistence=function(t,e){var n=this;return t?this.startIndexedDbPersistence().then(e.resolve).catch(function(t){return e.reject(t),n.canFallback(t)?(console.warn("Error enabling offline storage. Falling back to storage disabled: "+t),n.startMemoryPersistence()):Promise.reject(t)}):(e.resolve(),this.startMemoryPersistence())},t.prototype.canFallback=function(t){return t.code===Ht.FAILED_PRECONDITION||t.code===Ht.UNIMPLEMENTED},t.prototype.startIndexedDbPersistence=function(){this.garbageCollector=new jr;var t=_r.buildStoragePrefix(this.databaseInfo),e=new kn(this.databaseInfo.databaseId,{useProto3Json:!0});return this.persistence=new _r(t,e),this.persistence.start()},t.prototype.startMemoryPersistence=function(){return this.garbageCollector=new zn,this.persistence=new Vr,this.persistence.start()},t.prototype.initializeRest=function(t){var e=this;return this.platform.loadConnection(this.databaseInfo).then(function(n){e.localStore=new xr(e.persistence,t,e.garbageCollector);var r=e.platform.newSerializer(e.databaseInfo.databaseId),o=new Zr(e.databaseInfo,e.asyncQueue,n,e.credentials,r),i=function(t){e.eventMgr.onOnlineStateChanged(t)};return e.remoteStore=new eo(e.localStore,o,i),e.syncEngine=new ir(e.localStore,e.remoteStore,t),e.remoteStore.syncEngine=e.syncEngine,e.eventMgr=new Wn(e.syncEngine),e.localStore.start()}).then(function(){return e.remoteStore.start()})},t.prototype.handleUserChange=function(t){return this.asyncQueue.verifyOperationInProgress(),i("FirestoreClient","User Changed: "+t.uid),this.syncEngine.handleUserChange(t)},t.prototype.disableNetwork=function(){var t=this;return this.asyncQueue.schedule(function(){return t.remoteStore.disableNetwork()})},t.prototype.shutdown=function(){var t=this;return this.asyncQueue.schedule(function(){return t.credentials.removeUserChangeListener(),t.remoteStore.shutdown()}).then(function(){return t.persistence.shutdown()})},t.prototype.listen=function(t,e,n){var r=this,o=new Gn(t,e,n);return this.asyncQueue.schedule(function(){return r.eventMgr.listen(o)}),o},t.prototype.unlisten=function(t){var e=this;this.asyncQueue.schedule(function(){return e.eventMgr.unlisten(t)})},t.prototype.write=function(t){var e=this,n=new Qr;return this.asyncQueue.schedule(function(){return e.syncEngine.write(t,n)}),n.promise},t.prototype.databaseId=function(){return this.databaseInfo.databaseId},t.prototype.transaction=function(t){var e=this;return this.asyncQueue.schedule(function(){return Promise.resolve()}).then(function(){return e.syncEngine.runTransaction(t)})},t}(),ro=function(){function t(t){this.observer=t,this.muted=!1}return t.prototype.next=function(t){this.scheduleEvent(this.observer.next,t)},t.prototype.error=function(t){this.scheduleEvent(this.observer.error,t)},t.prototype.mute=function(){this.muted=!0},t.prototype.scheduleEvent=function(t,e){var n=this;this.muted||setTimeout(function(){n.muted||t(e)},0)},t}(),oo=function(){function t(){this.tail=Promise.resolve(),this.delayedOperations=[],this.delayedOperationsCount=0,this.operationInProgress=!1}return t.prototype.schedule=function(t,e){var n=this;if(this.failure&&u("AsyncQueue is already failed: "+(this.failure.stack||this.failure.message)),(e||0)>0){this.delayedOperationsCount++;var r={handle:null,op:t,deferred:new Qr};return r.handle=setTimeout(function(){n.scheduleInternal(function(){return r.op().then(function(t){r.deferred.resolve(t)})}),r.handle=null,0==--n.delayedOperationsCount&&(n.delayedOperations=[])},e),this.delayedOperations.push(r),r.deferred.promise}return this.scheduleInternal(t)},t.prototype.scheduleInternal=function(t){var e=this;return this.tail=this.tail.then(function(){return e.operationInProgress=!0,t().catch(function(t){e.failure=t,e.operationInProgress=!1;var n=t.stack||t.message||"";throw a("INTERNAL UNHANDLED ERROR: ",n),n.indexOf("Firestore Test Simulated Error")<0&&setTimeout(function(){throw t},0),t}).then(function(){e.operationInProgress=!1})}),this.tail},t.prototype.verifyOperationInProgress=function(){c(this.operationInProgress,"verifyOpInProgress() called when no op in progress on this queue.")},t.prototype.drain=function(t){var e=this;return this.delayedOperations.forEach(function(n){n.handle&&(clearTimeout(n.handle),t?e.scheduleInternal(n.op).then(n.deferred.resolve,n.deferred.reject):n.deferred.reject(new zt(Ht.CANCELLED,"Operation cancelled by shutdown")))}),this.delayedOperations=[],this.delayedOperationsCount=0,this.schedule(function(){return Promise.resolve()})},t}(),io=function(){function t(t){this.uid=t}return t.prototype.isUnauthenticated=function(){return null==this.uid},t.prototype.toKey=function(){return this.isUnauthenticated()?"anonymous-user":"uid:"+this.uid},t.prototype.equals=function(t){return t.uid===this.uid},t.UNAUTHENTICATED=new t(null),t.GOOGLE_CREDENTIALS=new t("google-credentials-uid"),t.FIRST_PARTY=new t("first-party-uid"),t}(),ao=function(){function t(t,e){this.user=e,this.type="OAuth",this.authHeaders={Authorization:"Bearer "+t}}return t}(),so=function(){function t(){this.userListener=null}return t.prototype.getToken=function(t){return Promise.resolve(null)},t.prototype.setUserChangeListener=function(t){c(!this.userListener,"Can only call setUserChangeListener() once."),this.userListener=t,t(io.UNAUTHENTICATED)},t.prototype.removeUserChangeListener=function(){c(null!==this.userListener,"removeUserChangeListener() when no listener registered"),this.userListener=null},t}(),uo=function(){function t(t){var e=this;this.app=t,this.tokenListener=null,this.userCounter=0,this.userListener=null,this.tokenListener=function(){var t=e.getUser();e.currentUser&&t.equals(e.currentUser)||(e.currentUser=t,e.userCounter++,e.userListener&&e.userListener(e.currentUser))},this.userCounter=0,this.app.INTERNAL.addAuthTokenListener(this.tokenListener)}return t.prototype.getToken=function(t){var e=this;c(null!=this.tokenListener,"getToken cannot be called after listener removed.");var n=this.userCounter;return this.app.INTERNAL.getToken(t).then(function(t){if(e.userCounter!==n)throw new zt(Ht.ABORTED,"getToken aborted due to uid change.");return t?(c("string"==typeof t.accessToken,"Invalid tokenData returned from getToken():"+t),new ao(t.accessToken,e.currentUser)):null})},t.prototype.setUserChangeListener=function(t){c(!this.userListener,"Can only call setUserChangeListener() once."),this.userListener=t,this.currentUser&&t(this.currentUser)},t.prototype.removeUserChangeListener=function(){c(null!=this.tokenListener,"removeUserChangeListener() called twice"),c(null!==this.userListener,"removeUserChangeListener() called when no listener registered"),this.app.INTERNAL.removeAuthTokenListener(this.tokenListener),this.tokenListener=null,this.userListener=null},t.prototype.getUser=function(){"function"!=typeof this.app.INTERNAL.getUid&&u("This version of the Firestore SDK requires at least version 3.7.0 of firebase.js.");var t=this.app.INTERNAL.getUid();return c(null===t||"string"==typeof t,"Received invalid UID: "+t),new io(t)},t}(),co=function(){function t(t,e){this.gapi=t,this.sessionIndex=e,this.type="FirstParty",this.user=io.FIRST_PARTY,c(this.gapi&&this.gapi.auth&&this.gapi.auth.getAuthHeaderValueForFirstParty,"unexpected gapi interface")}return Object.defineProperty(t.prototype,"authHeaders",{get:function(){return{Authorization:this.gapi.auth.getAuthHeaderValueForFirstParty([]),"X-Goog-AuthUser":this.sessionIndex}},enumerable:!0,configurable:!0}),t}(),ho=function(){function t(t,e){this.gapi=t,this.sessionIndex=e,c(this.gapi&&this.gapi.auth&&this.gapi.auth.getAuthHeaderValueForFirstParty,"unexpected gapi interface")}return t.prototype.getToken=function(t){return Promise.resolve(new co(this.gapi,this.sessionIndex))},t.prototype.setUserChangeListener=function(t){t(io.FIRST_PARTY)},t.prototype.removeUserChangeListener=function(){},t}(),lo=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),fo=function(){function t(){}return t.delete=function(){return po.instance},t.serverTimestamp=function(){return yo.instance},t}(),po=function(t){function e(){return t.call(this)||this}return lo(e,t),e.instance=new e,e}(fo),yo=function(t){function e(){return t.call(this)||this}return lo(e,t),e.instance=new e,e}(fo),mo=l(fo,"Use FieldValue.() instead."),go=/^__.*__$/,vo=function(){function t(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}return t.prototype.toMutations=function(t,e){var n=[];return null!==this.fieldMask?n.push(new an(t,this.data,this.fieldMask,e)):n.push(new on(t,this.data,e)),this.fieldTransforms.length>0&&n.push(new sn(t,this.fieldTransforms)),n},t}(),bo=function(){function t(t,e,n){this.data=t,this.fieldMask=e,this.fieldTransforms=n}return t.prototype.toMutations=function(t,e){var n=[new an(t,this.data,this.fieldMask,e)];return this.fieldTransforms.length>0&&n.push(new sn(t,this.fieldTransforms)),n},t}();!function(t){t[t.Set=0]="Set",t[t.Update=1]="Update",t[t.MergeSet=2]="MergeSet",t[t.QueryValue=3]="QueryValue"}(Gr||(Gr={}));var wo=function(){function t(t,e,n,r,o,i){this.dataSource=t,this.methodName=e,this.path=n,this.arrayElement=r,void 0===o&&this.validatePath(),this.arrayElement=void 0!==r&&r,this.fieldTransforms=o||[],this.fieldMask=i||[]}return t.prototype.childContextForField=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePathSegment(e),r},t.prototype.childContextForFieldPath=function(e){var n=null==this.path?null:this.path.child(e),r=new t(this.dataSource,this.methodName,n,!1,this.fieldTransforms,this.fieldMask);return r.validatePath(),r},t.prototype.childContextForArray=function(e){return new t(this.dataSource,this.methodName,null,!0,this.fieldTransforms,this.fieldMask)},t.prototype.createError=function(t){var e=null===this.path||this.path.isEmpty()?"":" (found in field "+this.path+")";return new zt(Ht.INVALID_ARGUMENT,"Function "+this.methodName+"() called with invalid data. "+t+e)},t.prototype.validatePath=function(){if(null!==this.path)for(var t=0;t0,"FieldValue.delete() at the top level should have already been handled."),e.createError("FieldValue.delete() can only appear at the top level of your update data")):e.createError("FieldValue.delete() can only be used with update() and set() with {merge:true}")}if(t instanceof yo){if(!At(e.dataSource))throw e.createError("FieldValue.serverTimestamp() can only be used with set() and update()");if(null===e.path)throw e.createError("FieldValue.serverTimestamp() is not currently supported inside arrays");return e.fieldTransforms.push(new Ze(e.path,$e.instance)),null}return u("Unknown FieldValue type: "+t)}throw e.createError("Unsupported field value: "+N(t))},t}(),Eo=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),So="firestore.googleapis.com",Co=!0,Do=function(){function t(t){if(void 0===t.host){if(void 0!==t.ssl)throw new zt(Ht.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=So,this.ssl=Co}else S("settings","string","host",t.host),this.host=t.host,C("settings","boolean","ssl",t.ssl),this.ssl=d(t.ssl,Co);O("settings",t,["host","ssl","credentials"]),C("settings","object","credentials",t.credentials),this.credentials=t.credentials}return t.prototype.equals=function(t){return this.host===t.host&&this.ssl===t.ssl&&this.credentials===t.credentials},t}(),ko=function(){function t(){}return t}(),No=function(){function t(e){var n=this;this.k=new oo,this.INTERNAL={delete:function(){return n._?n._.shutdown():Promise.resolve()},disableNetwork:function(){return n._.disableNetwork()},enableNetwork:function(){return n._.enableNetwork()},drainAsyncQueue:function(t){return n.k.drain(t)}};var r=new ko;if("object"==typeof e.options){var o=e;r.firebaseApp=o,r.databaseId=t.databaseIdFromApp(o),r.persistenceKey=r.firebaseApp.name,r.credentials=new uo(o)}else{var i=e;if(!i.projectId)throw new zt(Ht.INVALID_ARGUMENT,"Must provide projectId");r.databaseId=new ee(i.projectId,i.database),r.persistenceKey="[DEFAULT]",r.credentials=new so}r.settings=new Do({}),this.x=r,this._databaseId=r.databaseId}return t.prototype.settings=function(t){if(v("Firestore.settings",arguments,1),T("Firestore.settings","object",1,t),f(t,"persistence"))throw new zt(Ht.INVALID_ARGUMENT,'"persistence" is now specified with a separate call to firestore.enablePersistence().');var e=new Do(t);if(this._&&!this.x.settings.equals(e))throw new zt(Ht.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only call settings() before calling any other methods on a Firestore object.");this.x.settings=e,void 0!==e.credentials&&(this.x.credentials=Dt(e.credentials))},t.prototype.enablePersistence=function(){if(this._)throw new zt(Ht.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only call enablePersistence() before calling any other methods on a Firestore object.");return this.configureClient(!0)},t.prototype.ensureClientConfigured=function(){return this._||this.configureClient(!1),this._},t.prototype.configureClient=function(t){var e=this;c(!!this.x.settings.host,"FirestoreSettings.host cannot be falsey"),c(!this._,"configureClient() called multiple times");var n=new Zt(this.x.databaseId,this.x.persistenceKey,this.x.settings.host,this.x.settings.ssl),r=function(t){if(t instanceof Oo){var n=e.x.databaseId,r=t.firestore.x.databaseId;if(!r.equals(n))throw new zt(Ht.INVALID_ARGUMENT,"Document reference is for database "+r.projectId+"/"+r.database+" but should be for database "+n.projectId+"/"+n.database);return new Io(e.x.databaseId,t.q)}return t};return this._dataConverter=new To(r),this._=new no(Wt.getPlatform(),n,this.x.credentials,this.k),this._.start(t)},t.databaseIdFromApp=function(t){var e=t.options;if(!f(e,"projectId")){if(f(e,"firestoreId"))throw new zt(Ht.INVALID_ARGUMENT,'"firestoreId" is now specified as "projectId" in firebase.initializeApp.');throw new zt(Ht.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.')}if(f(e,"firestoreOptions"))throw new zt(Ht.INVALID_ARGUMENT,'"firestoreOptions" values are now specified with Firestore.settings()');var n=e.projectId;if(!n||"string"!=typeof n)throw new zt(Ht.INVALID_ARGUMENT,"projectId must be a string in FirebaseApp.options");return new ee(n)},Object.defineProperty(t.prototype,"app",{get:function(){if(!this.x.firebaseApp)throw new zt(Ht.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this.x.firebaseApp},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(v("Firestore.collection",arguments,1),T("Firestore.collection","string",1,t),!t)throw new zt(Ht.INVALID_ARGUMENT,"Must provide a non-empty collection path to collection()");return this.ensureClientConfigured(),new Lo(oe.fromString(t),this)},t.prototype.doc=function(t){if(v("Firestore.doc",arguments,1),T("Firestore.doc","string",1,t),!t)throw new zt(Ht.INVALID_ARGUMENT,"Must provide a non-empty document path to doc()");return this.ensureClientConfigured(),Oo.forPath(oe.fromString(t),this)},t.prototype.runTransaction=function(t){var e=this;return v("Firestore.runTransaction",arguments,1),T("Firestore.runTransaction","function",1,t),this.ensureClientConfigured().transaction(function(n){return t(new Ao(e,n))})},t.prototype.batch=function(){return this.ensureClientConfigured(),new Ro(this)},Object.defineProperty(t,"logLevel",{get:function(){switch(r()){case qt.DEBUG:return"debug";case qt.ERROR:return"error";case qt.SILENT:return"silent";default:return u("Unknown log level: "+r())}},enumerable:!0,configurable:!0}),t.setLogLevel=function(t){switch(v("Firestore.setLogLevel",arguments,1),T("Firestore.setLogLevel","string",1,t),t){case"debug":o(qt.DEBUG);break;case"error":o(qt.ERROR);break;case"silent":o(qt.SILENT);break;default:throw new zt(Ht.INVALID_ARGUMENT,"Invalid log level: "+t)}},t}(),Ao=function(){function t(t,e){this.Q=t,this.z=e}return t.prototype.get=function(t){var e=this;v("Transaction.get",arguments,1);var n=xt("Transaction.get",t,this.Q);return this.z.lookup([n.q]).then(function(t){if(!t||1!==t.length)return u("Mismatch in docs returned from document lookup.");var r=t[0];return r instanceof ce?new Mo(e.Q,n.q,null,!1):new Mo(e.Q,n.q,r,!1)})},t.prototype.set=function(t,e,n){w("Transaction.set",arguments,2,3);var r=xt("Transaction.set",t,this.Q);n=Lt("Transaction.set",n);var o=n.merge?this.Q._dataConverter.parseMergeData("Transaction.set",e):this.Q._dataConverter.parseSetData("Transaction.set",e);return this.z.set(r.q,o),this},t.prototype.update=function(t,e,n){for(var r=[],o=3;o0?this.Q.ensureClientConfigured().write(this.tt):Promise.resolve()},t.prototype.verifyNotCommitted=function(){if(this.et)throw new zt(Ht.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")},t}(),Oo=function(){function t(t,e){this.q=t,this.firestore=e,this._=this.firestore.ensureClientConfigured()}return t.forPath=function(e,n){if(e.length%2!=0)throw new zt(Ht.INVALID_ARGUMENT,"Invalid document reference. Document references must have an even number of segments, but "+e.canonicalString()+" has "+e.length);return new t(new se(e),n)},Object.defineProperty(t.prototype,"id",{get:function(){return this.q.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return new Lo(this.q.path.popLast(),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"path",{get:function(){return this.q.path.canonicalString()},enumerable:!0,configurable:!0}),t.prototype.collection=function(t){if(v("DocumentReference.collection",arguments,1),T("DocumentReference.collection","string",1,t),!t)throw new zt(Ht.INVALID_ARGUMENT,"Must provide a non-empty collection name to collection()");var e=oe.fromString(t);return new Lo(this.q.path.child(e),this.firestore)},t.prototype.isEqual=function(e){if(!(e instanceof t))throw M("isEqual","DocumentReference",1,e);return this.firestore===e.firestore&&this.q.equals(e.q)},t.prototype.set=function(t,e){w("DocumentReference.set",arguments,1,2),e=Lt("DocumentReference.set",e);var n=e.merge?this.firestore._dataConverter.parseMergeData("DocumentReference.set",t):this.firestore._dataConverter.parseSetData("DocumentReference.set",t);return this._.write(n.toMutations(this.q,nn.NONE))},t.prototype.update=function(t,e){for(var n=[],r=2;r0)throw new zt(Ht.INVALID_ARGUMENT,"Too many arguments provided to "+t+"().");var o=e;if(!o.exists)throw new zt(Ht.NOT_FOUND,"Can't use a DocumentSnapshot that doesn't exist for "+t+"().");return this.boundFromDocument(t,o.nt,r)}var i=[e].concat(n);return this.boundFromFields(t,i,r)},t.prototype.boundFromDocument=function(t,e,n){for(var r=[],o=0,i=this.ot.orderBy;or.length)throw new zt(Ht.INVALID_ARGUMENT,"Too many arguments provided to "+t+"(). The number of arguments must be less than or equal to the number of Query.orderBy() clauses");for(var o=[],i=0;i, or >=) must be on the same field. But you have inequality filters on '"+e+"' and '"+t.field+"'");var n=this.ot.getFirstOrderByField();null!==n&&this.validateOrderByAndInequalityMatch(t.field,n)}},t.prototype.validateNewOrderBy=function(t){if(null===this.ot.getFirstOrderByField()){var e=this.ot.getInequalityFilterField();null!==e&&this.validateOrderByAndInequalityMatch(e,t.field)}},t.prototype.validateOrderByAndInequalityMatch=function(t,e){if(!e.equals(t))throw new zt(Ht.INVALID_ARGUMENT,"Invalid query. You have a where filter with an inequality (<, <=, >, or >=) on field '"+t+"' and so you must also use '"+t+"' as your first Query.orderBy(), but your first Query.orderBy() is on field '"+e+"' instead.")},t}(),Po=function(){function t(t,e,n){this.Q=t,this.it=e,this.at=n,this._cachedChanges=null,this.metadata={fromCache:n.fromCache,hasPendingWrites:n.hasPendingWrites}}return Object.defineProperty(t.prototype,"docs",{get:function(){var t=[];return this.forEach(function(e){return t.push(e)}),t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"empty",{get:function(){return this.at.docs.isEmpty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"size",{get:function(){return this.at.docs.size},enumerable:!0,configurable:!0}),t.prototype.forEach=function(t,e){var n=this;w("QuerySnapshot.forEach",arguments,1,2),T("QuerySnapshot.forEach","function",1,t),this.at.docs.forEach(function(r){t.call(e,n.convertToDocumentImpl(r))})},Object.defineProperty(t.prototype,"query",{get:function(){return new _o(this.it,this.Q)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"docChanges",{get:function(){return this._cachedChanges||(this._cachedChanges=Bt(this.Q,this.at)),this._cachedChanges},enumerable:!0,configurable:!0}),t.prototype.convertToDocumentImpl=function(t){return new Mo(this.Q,t.key,t,this.metadata.fromCache)},t}(),Lo=function(t){function e(e,n){var r=t.call(this,Le.atPath(e),n)||this;if(e.length%2!=1)throw new zt(Ht.INVALID_ARGUMENT,"Invalid collection reference. Collection references must have an odd number of segments, but "+e.canonicalString()+" has "+e.length);return r}return Eo(e,t),Object.defineProperty(e.prototype,"id",{get:function(){return this.ot.path.lastSegment()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){var t=this.ot.path.popLast();return t.isEmpty()?null:new Oo(new se(t),this.firestore)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return this.ot.path.canonicalString()},enumerable:!0,configurable:!0}),e.prototype.doc=function(t){if(w("CollectionReference.doc",arguments,0,1),0===arguments.length&&(t=Xt.newId()),T("CollectionReference.doc","string",1,t),""===t)throw new zt(Ht.INVALID_ARGUMENT,"Document path must be a non-empty string");var e=oe.fromString(t);return Oo.forPath(this.ot.path.child(e),this.firestore)},e.prototype.add=function(t){v("CollectionReference.add",arguments,1),T("CollectionReference.add","object",1,t);var e=this.doc();return e.set(t).then(function(){return e})},e}(_o),xo=l(No,"Use firebase.firestore() instead."),Bo=l(Ao,"Use firebase.firestore().runTransaction() instead."),Uo=l(Ro,"Use firebase.firestore().batch() instead."),Fo=l(Oo,"Use firebase.firestore().doc() instead."),Vo=l(Mo),qo=l(_o),jo=l(Po),Qo=l(Lo,"Use firebase.firestore().collection() instead."),Ko={Firestore:xo,GeoPoint:$t,Blob:Jt,Transaction:Bo,WriteBatch:Uo,DocumentReference:Fo,DocumentSnapshot:Vo,Query:qo,QuerySnapshot:jo,CollectionReference:Qo,FieldPath:xn,FieldValue:mo,setLogLevel:No.setLogLevel};e.registerFirestore=Vt,Vt(jt.default)},115:function(module,exports,__webpack_require__){(function(global){(function(){function l(t){return"string"==typeof t}function aa(){}function ba(t){var e=typeof t;if("object"==e){if(!t)return"null";if(t instanceof Array)return"array";if(t instanceof Object)return e;var n=Object.prototype.toString.call(t);if("[object Window]"==n)return"object";if("[object Array]"==n||"number"==typeof t.length&&void 0!==t.splice&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("splice"))return"array";if("[object Function]"==n||void 0!==t.call&&void 0!==t.propertyIsEnumerable&&!t.propertyIsEnumerable("call"))return"function"}else if("function"==e&&void 0===t.call)return"object";return e}function n(t){return"array"==ba(t)}function ca(t){var e=ba(t);return"array"==e||"object"==e&&"number"==typeof t.length}function da(t){return"function"==ba(t)}function p(t){var e=typeof t;return"object"==e&&null!=t||"function"==e}function fa(t,e,n){return t.call.apply(t.bind,arguments)}function ha(t,e,n){if(!t)throw Error();if(2e?1:0}function na(t,e){e.unshift(t),ja.call(this,ka.apply(null,e)),e.shift()}function oa(t,e){throw new na("Failure"+(t?": "+t:""),Array.prototype.slice.call(arguments,1))}function w(){0!=qa&&(ra[this[q]||(this[q]=++ea)]=this),this.i=this.i,this.w=this.w}function ua(t){t:{for(var e=va,n=t.length,r=l(t)?t.split(""):t,o=0;oe?null:l(t)?t.charAt(e):t[e]}function wa(t){if(!n(t))for(var e=t.length-1;0<=e;e--)delete t[e];t.length=0}function xa(t){return Array.prototype.concat.apply([],arguments)}function ya(t){var e=t.length;if(0r.keyCode||void 0!=r.returnValue)){t:{var o=!1;if(0==r.keyCode)try{r.keyCode=-1;break t}catch(t){o=!0}(o||void 0==r.returnValue)&&(r.returnValue=!0)}for(r=[],o=e.a;o;o=o.parentNode)r.push(o);for(t=t.type,o=r.length-1;0<=o;o--){e.a=r[o];var i=xb(r[o],t,!0,e);n=n&&i}for(o=0;oe.b&&(e.b++,t.next=e.a,e.a=t)}Wb=!1}function Xb(e,n){B.call(this),this.b=e||1,this.a=n||k,this.f=r(this.ib,this),this.g=t()}function Yb(t){t.$=!1,t.K&&(t.a.clearTimeout(t.K),t.K=null)}function Zb(t,e,n){if(da(t))n&&(t=r(t,n));else{if(!t||"function"!=typeof t.handleEvent)throw Error("Invalid listener argument");t=r(t.handleEvent,t)}return 2147483647<+e?-1:k.setTimeout(t,e||0)}function $b(t,e,n){w.call(this),this.f=null!=n?r(t,n):t,this.c=e,this.b=r(this.bb,this),this.a=[]}function ac(t){t.X=Zb(t.b,t.c),t.f.apply(null,t.a)}function C(t){w.call(this),this.b=t,this.a={}}function cc(t){Ba(t.a,function(t,e){this.a.hasOwnProperty(e)&&wb(t)},t),t.a={}}function dc(t,e,n){this.reset(t,e,n,void 0,void 0)}function fc(t){this.f=t,this.b=this.c=this.a=null}function D(t,e){this.name=t,this.value=e}function lc(t){return t.c?t.c:t.a?lc(t.a):(oa("Root logger has no level set."),null)}function oc(t){nc||(nc=new fc(""),mc[""]=nc,nc.c=jc);var e;if(!(e=mc[t])){e=new fc(t);var n=t.lastIndexOf("."),r=t.substr(n+1);n=oc(t.substr(0,n)),n.b||(n.b={}),n.b[r]=e,e.a=n,mc[t]=e}return e}function E(t,e){t&&t.log(hc,e,void 0)}function pc(t,e){t&&t.log(ic,e,void 0)}function F(t,e){t&&t.log(kc,e,void 0)}function qc(){this.a=oc("goog.labs.net.webChannel.WebChannelDebug"),this.b=!0}function rc(t,e,n,r,o,i){H(t,function(){if(t.b)if(i)for(var a="",s=i.split("&"),u=0;ui.length)){var a=i[1];if(n(a)&&!(1>a.length)){var s=a[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var u=1;ue||3==e&&!Ka&&!t.a.V())){t.B||4!=e||7==n||Ac(8==n||0>=r?3:2),Zc(t);var o=t.a.W();t.C=o,(n=t.a.V())||I(t.b,function(){return"No response text for uri "+t.g+" status "+o}),t.c=200==o,sc(t.b,t.o,t.g,t.f,t.T,e,o),t.c?(t.M?($c(t,e,n),Ka&&t.c&&3==e&&ad(t)):(tc(t.b,t.f,n,null),bd(t,n)),4==e&&cd(t),t.c&&!t.B&&(4==e?t.i.ua(t):(t.c=!1,Wc(t)))):(400==o&&0e.length?Rc:(e=e.substr(r,n),t.F=r+n,e))}function Wc(e){e.U=t()+e.S,fd(e,e.S)}function fd(t,e){if(null!=t.w)throw Error("WatchDog timer not null");t.w=Ec(r(t.cb,t),e)}function Zc(t){t.w&&(k.clearTimeout(t.w),t.w=null)}function dd(t){t.i.Ja()||t.B||t.i.ua(t)}function cd(t){Zc(t);var e=t.I;e&&"function"==typeof e.Z&&e.Z(),t.I=null,Yb(t.H),cc(t.N),t.a&&(e=t.a,t.a=null,e.abort(),e.Z())}function bd(t,e){try{t.i.Ma(t,e),Ac(4)}catch(e){wc(t.b,e,"Error in httprequest callback")}}function gd(t){if(t.v&&"function"==typeof t.v)return t.v();if(l(t))return t.split("");if(ca(t)){for(var e=[],n=t.length,r=0;r2*t.c&&id(t),!0)}function id(t){if(t.c!=t.a.length){for(var e=0,n=0;ee)throw Error("Bad port number "+e);t.i=e}else t.i=null}function qd(t,e,n){e instanceof td?(t.c=e,zd(t.c,t.h)):(n||(e=ud(e,Ad)),t.c=new td(e,t.h))}function Q(t,e,n){t.c.set(e,n)}function Xc(t,e,r){n(r)||(r=[r+""]),Bd(t.c,e,r)}function Tc(e){return Q(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^t()).toString(36)),e}function Cd(t){return t instanceof P?L(t):new P(t,void 0)}function Dd(t,e,n,r){var o=new P(null,void 0);return t&&nd(o,t),e&&od(o,e),n&&pd(o,n),r&&(o.a=r),o}function sd(t,e){return t?e?decodeURI(t.replace(/%25/g,"%2525")):decodeURIComponent(t):""}function ud(t,e,n){return l(t)?(t=encodeURI(t).replace(e,Ed),n&&(t=t.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),t):null}function Ed(t){return t=t.charCodeAt(0),"%"+(t>>4&15).toString(16)+(15&t).toString(16)}function td(t,e){this.b=this.a=null,this.c=t||null,this.f=!!e}function R(t){t.a||(t.a=new N,t.b=0,t.c&&md(t.c,function(e,n){t.add(decodeURIComponent(e.replace(/\+/g," ")),n)}))}function Gd(t,e){R(t),e=Fd(t,e),O(t.a.b,e)&&(t.c=null,t.b-=t.a.get(e).length,kd(t.a,e))}function Hd(t,e){return R(t),e=Fd(t,e),O(t.a.b,e)}function Bd(t,e,n){Gd(t,e),0=t.f}function ce(t,e){return t.b?t.b==e:!!t.a&&t.a.contains(e)}function ae(t,e){t.a?t.a.add(e):t.b=e}function de(t,e){t.b&&t.b==e?t.b=null:t.a&&t.a.contains(e)&&kd(t.a.a,Wd(e))}function ee(t){if(null!=t.b)return t.c.concat(t.b.s);if(null!=t.a&&0!=t.a.a.c){var e=t.c;return ta(t.a.v(),function(t){e=e.concat(t.s)}),e}return ya(t.c)}function fe(t,e){t.c=t.c.concat(e)}function ge(){}function he(){this.a=new ge}function ie(t,e,n){var r=n||"";try{hd(t,function(t,n){var o=t;p(t)&&(o=Db(t)),e.push(r+n+"="+encodeURIComponent(o))})}catch(t){throw e.push(r+"type="+encodeURIComponent("_badmap")),t}}function je(t,e){var n=new qc;I(n,"TestLoadImage: loading "+t);var r=new Image;r.onload=ia(ke,n,r,"TestLoadImage: loaded",!0,e),r.onerror=ia(ke,n,r,"TestLoadImage: error",!1,e),r.onabort=ia(ke,n,r,"TestLoadImage: abort",!1,e),r.ontimeout=ia(ke,n,r,"TestLoadImage: timeout",!1,e),k.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=t}function ke(t,e,n,r,o){try{I(t,n),e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null,o(r)}catch(e){wc(t,e)}}function T(t){B.call(this),this.headers=new N,this.F=t||null,this.f=!1,this.D=this.a=null,this.M=this.s="",this.j=0,this.g="",this.h=this.I=this.o=this.H=!1,this.l=0,this.B=null,this.N=le,this.C=this.m=!1}function qe(t){return z&&Ta(9)&&"number"==typeof t.timeout&&void 0!==t.ontimeout}function va(t){return"content-type"==t.toLowerCase()}function oe(t,e){t.f=!1,t.a&&(t.h=!0,t.a.abort(),t.h=!1),t.g=e,t.j=5,re(t),se(t)}function re(t){t.H||(t.H=!0,t.dispatchEvent("complete"),t.dispatchEvent("error"))}function te(t){if(t.f&&void 0!==goog)if(t.D[1]&&4==M(t)&&2==t.W())F(t.b,U(t,"Local request error detected and ignored"));else if(t.o&&4==M(t))Zb(t.La,0,t);else if(t.dispatchEvent("readystatechange"),4==M(t)){F(t.b,U(t,"Request complete")),t.f=!1;try{var e=t.W();t:switch(e){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var n=!0;break t;default:n=!1}var r;if(!(r=n)){var o;if(o=0===e){var i=(t.s+"").match(ld)[1]||null;if(!i&&k.self&&k.self.location){var a=k.self.location.protocol;i=a.substr(0,a.length-1)}o=!me.test(i?i.toLowerCase():"")}r=o}r?(t.dispatchEvent("complete"),t.dispatchEvent("success")):(t.j=6,t.g=t.Ga()+" ["+t.W()+"]",re(t))}finally{se(t)}}}function se(t,e){if(t.a){pe(t);var n=t.a,r=t.D[0]?aa:null;t.a=null,t.D=null,e||t.dispatchEvent("ready");try{n.onreadystatechange=r}catch(e){(t=t.b)&&t.log(gc,"Problem encountered resetting onreadystatechange: "+e.message,void 0)}}}function pe(t){t.a&&t.C&&(t.a.ontimeout=null),t.B&&(k.clearTimeout(t.B),t.B=null)}function M(t){return t.a?t.a.readyState:0}function U(t,e){return e+" ["+t.M+" "+t.s+" "+t.W()+"]"}function ue(t){var e="";return Ba(t,function(t,n){e+=n,e+=":",e+=t,e+="\r\n"}),e}function ve(t,e,n){t:{for(r in n){var r=!1;break t}r=!0}if(r)return t;if(n=ue(n),l(t)){if(e=encodeURIComponent(e+""),n=null!=n?"="+encodeURIComponent(n+""):"",e+=n){if(n=t.indexOf("#"),0>n&&(n=t.length),0>(r=t.indexOf("?"))||r>n){r=n;var o=""}else o=t.substring(r+1,n);t=[t.substr(0,r),o,t.substr(n)],n=t[1],t[1]=e?n?n+"&"+e:e:n,t=t[0]+(t[1]?"?"+t[1]:"")+t[2]}return t}return Q(t,e,n),t}function we(t){this.ya=0,this.g=[],this.a=new qc,this.H=new Vd,this.ja=this.wa=this.F=this.ka=this.b=this.J=this.j=this.U=this.h=this.M=this.i=null,this.Ua=this.P=0,this.la=this.B=this.o=this.m=this.l=this.f=null,this.s=this.xa=this.N=-1,this.T=this.w=this.C=0,this.S=t&&t.supportsCrossDomainXhr||!1,this.I="",this.c=new Yd(t&&t.concurrentRequestLimit),this.ma=new he,this.D=!t||void 0===t.backgroundChannelTest||t.backgroundChannelTest,this.Ta=t&&t.fastHandshake||!1,t&&t.Ea&&this.a.Ea()}function xe(e){if(I(e.a,"disconnect()"),ye(e),3==e.G){var n=e.P++,r=L(e.F);Q(r,"SID",e.I),Q(r,"RID",n),Q(r,"TYPE","terminate"),ze(e,r),n=new K(e,e.a,n,void 0),n.J=2,n.h=Tc(L(r)),r=!1,k.navigator&&k.navigator.sendBeacon&&(r=k.navigator.sendBeacon(""+n.h,"")),!r&&k.Image&&((new Image).src=n.h,r=!0),r||(n.a=n.i.da(null),n.a.fa(n.h)),n.D=t(),Wc(n)}Ae(e)}function ye(t){t.B&&(t.B.abort(),t.B=null),t.b&&(t.b.cancel(),t.b=null),t.m&&(k.clearTimeout(t.m),t.m=null),Be(t),t.c.cancel(),t.l&&(k.clearTimeout(t.l),t.l=null)}function Ce(t,e){1e3==t.g.length&&xc(t.a,function(){return"Already have 1000 queued maps upon queueing "+Db(e)}),t.g.push(new Xd(t.Ua++,e)),3==t.G&&De(t)}function De(t){be(t.c)||t.l||(t.l=Ec(r(t.Oa,t),0),t.C=0)}function Ee(t,e){var n=t.c;return(n.b?1:n.a?n.a.u():0)>=t.c.f-(t.l?1:0)?(xc(t.a,"Unexpected retry request is scheduled."),!1):t.l?(I(t.a,"Use the retry request that is already scheduled."),t.g=e.s.concat(t.g),!0):!(1==t.G||2==t.G||2<=t.C||(I(t.a,"Going to retry POST"),t.l=Ec(r(t.Oa,t,e),Fe(t,t.C)),t.C++,0))}function He(t,e){var n;n=e?e.f:t.P++;var r=L(t.F);Q(r,"SID",t.I),Q(r,"RID",n),Q(r,"AID",t.N),ze(t,r),t.h&&t.i&&ve(r,t.h,t.i),n=new K(t,t.a,n,t.C+1),null===t.h&&(n.j=t.i),e&&(t.g=e.s.concat(t.g)),e=Ge(t,n),n.setTimeout(Math.round(1e4)+Math.round(1e4*Math.random())),ae(t.c,n),Sc(n,r,e)}function ze(t,e){t.f&&hd({},function(t,n){Q(e,n,t)})}function Ge(t,e){var n=Math.min(t.g.length,1e3),o=t.f?r(t.f.Va,t.f,t):null;t:for(var i=t.g,a=-1;;){var s=["count="+n];-1==a?0(h-=a))a=Math.max(0,i[c].a-100),u=!1;else try{ie(l,s,"req"+h+"_")}catch(t){o&&o(l)}}if(u){o=s.join("&");break t}}return t=t.g.splice(0,n),e.s=t,o}function Ie(t){if(!t.b&&!t.m){t.T=1;var e=t.Na;Tb||Ub(),Wb||(Tb(),Wb=!0),Pb.add(e,t),t.w=0}}function Je(t){return t.b||t.m?(xc(t.a,"Request already in progress"),!1):!(3<=t.w||(I(t.a,"Going to retry GET"),t.T++,t.m=Ec(r(t.Na,t),Fe(t,t.w)),t.w++,0))}function Sd(t,e,n){I(t.a,"Test Connection Finished");var r=e.m;r&&$d(t.c,r),t.la=n,t.s=e.f,I(t.a,"connectChannel_()"),t.F=Ke(t,t.ka),De(t)}function Ud(t,e){I(t.a,"Test Connection Failed"),t.s=e.f,V(t,2)}function Be(t){null!=t.o&&(k.clearTimeout(t.o),t.o=null)}function Fe(t,e){var n=5e3+Math.floor(1e4*Math.random());return t.ra()||(I(t.a,"Inactive channel"),n*=2),n*e}function V(t,e){if(H(t.a,"Error code "+e),2==e){var n=null;t.f&&(n=null);var o=r(t.hb,t);n||(n=new P("//www.google.com/images/cleardot.gif"),k.location&&"http"==k.location.protocol||nd(n,"https"),Tc(n)),je(""+n,o)}else J(2);I(t.a,"HttpChannel: error - "+e),t.G=0,t.f&&t.f.Ba(e),Ae(t),ye(t)}function Ae(t){if(t.G=0,t.s=-1,t.f){var e=ee(t.c);0==e.length&&0==t.g.length||(I(t.a,function(){return"Number of undelivered maps, pending: "+e.length+", outgoing: "+t.g.length}),t.c.c.length=0,ya(t.g),t.g.length=0),t.f.Aa()}}function Ke(t,e){return e=Le(t,null,e),I(t.a,"GetForwardChannelUri: "+e),e}function Td(t,e,n){return e=Le(t,t.ia()?e:null,n),I(t.a,"GetBackChannelUri: "+e),e}function Le(t,e,n){var r=Cd(n);if(""!=r.b)e&&od(r,e+"."+r.b),pd(r,r.i);else{var o,i=k.location;o=e?e+"."+i.hostname:i.hostname,r=Dd(i.protocol,o,i.port,n)}return t.U&&Ba(t.U,function(t,e){Q(r,e,t)}),e=t.j,n=t.J,e&&n&&Q(r,e,n),Q(r,"VER",t.oa),ze(t,r),r}function Me(){}function Ne(t){for(var e=arguments[0],n=1;nthis.c)throw Error(We);this.a=new Te,this.b=new S,this.g=null,this.ba()}function Xe(t){if("function"==typeof t.Z)t.Z();else for(var e in t)t[e]=null}function Ye(t,e){this.a=t,this.b=e}function Ze(t){if(this.a=[],t)t:{if(t instanceof Ze){var e=t.O();if(t=t.v(),0>=this.u()){for(var n=this.a,r=0;r>1,t[r].a>n.a);)t[e]=t[r],e=r;t[e]=n}function af(){Ze.call(this)}function X(t,e){this.f=new af,Ve.call(this,t,e)}function Y(t,e,n,r){this.l=t,this.j=!!r,X.call(this,e,n)}var g,goog=goog||{},k=this,q="closure_uid_"+(1e9*Math.random()>>>0),ea=0,t=Date.now||function(){return+new Date};u(ja,Error),ja.prototype.name="CustomError";var la=String.prototype.trim?function(t){return t.trim()}:function(t){return t.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")};u(na,ja),na.prototype.name="AssertionError";var qa=0,ra={};w.prototype.i=!1,w.prototype.Z=function(){if(!this.i&&(this.i=!0,this.A(),0!=qa)){var t=this[q]||(this[q]=++ea);delete ra[t]}},w.prototype.A=function(){if(this.w)for(;this.w.length;)this.w.shift()()};var sa=Array.prototype.indexOf?function(t,e){return Array.prototype.indexOf.call(t,e,void 0)}:function(t,e){if(l(t))return l(e)&&1==e.length?t.indexOf(e,0):-1;for(var n=0;nparseFloat(Qa)){Pa=Sa+"";break t}}Pa=Qa}var Ja={},Ua,Va=k.document;Ua=Va&&z?Oa()||("CSS1Compat"==Va.compatMode?parseInt(Pa,10):5):void 0;var Wa=Object.freeze||function(t){return t},Xa=!z||9<=+Ua,Ya=z&&!Ta("9"),Za=function(){if(!k.addEventListener||!Object.defineProperty)return!1;var t=!1,e=Object.defineProperty({},"passive",{get:function(){t=!0}});return k.addEventListener("test",aa,e),k.removeEventListener("test",aa,e),t}();A.prototype.b=function(){this.Pa=!1},u($a,A);var ab=Wa({2:"touch",3:"pen",4:"mouse"});$a.prototype.b=function(){$a.L.b.call(this);var t=this.c;if(t.preventDefault)t.preventDefault();else if(t.returnValue=!1,Ya)try{(t.ctrlKey||112<=t.keyCode&&123>=t.keyCode)&&(t.keyCode=-1)}catch(t){}};var bb="closure_listenable_"+(1e6*Math.random()|0),db=0;gb.prototype.add=function(t,e,n,r,o){var i=""+t;(t=this.a[i])||(t=this.a[i]=[],this.b++);var a=hb(t,e,r,o);return-1>>0);u(B,w),B.prototype[bb]=!0,g=B.prototype,g.addEventListener=function(t,e,n,r){nb(this,t,e,n,r)},g.removeEventListener=function(t,e,n,r){vb(this,t,e,n,r)},g.dispatchEvent=function(t){var e,n=this.J;if(n)for(e=[];n;n=n.J)e.push(n);n=this.P;var r=t.type||t;if(l(t))t=new A(t,n);else if(t instanceof A)t.target=t.target||n;else{var o=t;t=new A(r,n),Ga(t,o)}if(o=!0,e)for(var i=e.length-1;0<=i;i--){var a=t.a=e[i];o=Ab(a,r,!0,t)&&o}if(a=t.a=n,o=Ab(a,r,!0,t)&&o,o=Ab(a,r,!1,t)&&o,e)for(i=0;i=lc(this).value)for(da(e)&&(e=e()),t=new dc(t,e+"",this.f),n&&(t.a=n),n=this;n;)n=n.a};var mc={},nc=null;qc.prototype.Ea=function(){this.b=!1};var yc=new B;u(zc,A),u(Bc,A),u(Cc,A);var Fc={NO_ERROR:0,jb:1,qb:2,pb:3,mb:4,ob:5,rb:6,Ra:7,TIMEOUT:8,ub:9},Gc={lb:"complete",yb:"success",Sa:"error",Ra:"abort",wb:"ready",xb:"readystatechange",TIMEOUT:"timeout",sb:"incrementaldata",vb:"progress",nb:"downloadprogress",zb:"uploadprogress"};Hc.prototype.a=null;var Kc;u(Lc,Hc),Kc=new Lc;var Nc=45e3,Oc=250,Qc={},Rc={};g=K.prototype,g.setTimeout=function(t){this.S=t},g.fb=function(t){t=t.target;var e=this.I;e&&3==M(t)?(I(this.b,"Throttling readystatechange."),e.Xa()):this.Qa(t)},g.Qa=function(t){try{t==this.a?Yc(this):E(this.b.a,"Called back with an unexpected xmlhttp")}catch(t){if(I(this.b,"Failed call to OnXmlHttpReadyStateChanged_"),this.a&&this.a.V()){var e=this;wc(this.b,t,function(){return"ResponseText: "+e.a.V()})}else wc(this.b,t,"No response text")}},g.eb=function(){var t=M(this.a),e=this.a.V();this.Fe&&this.la&&0==this.w&&!this.o&&(this.o=Ec(r(this.$a,this),6e3)));else I(this.a,"Bad POST response data returned"),V(this,11)}else if(this.b==t&&Be(this),!/^[\s\xa0]*$/.test(e))for(e=o=this.ma.a.parse(e),o=0;oe-this.g)){for(var n;0this.c&&0=o)i=void 0;else{if(1==o)wa(r);else{r[0]=r.pop(),r=0,n=n.a,o=n.length;for(var a=n[r];r>1;){var s=2*r+1,u=2*r+2;if(s=ua.a)break;n[r]=n[s],r=s}n[r]=a}i=i.b}i.apply(this,[e])}},g.na=function(t){X.L.na.call(this,t),this.sa()},g.ba=function(){X.L.ba.call(this),this.sa()},g.A=function(){X.L.A.call(this),k.clearTimeout(void 0),wa(this.f.a),this.f=null},u(Y,X),Y.prototype.qa=function(){var t=new T,e=this.l;return e&&e.forEach(function(e,n){t.headers.set(n,e)}),this.j&&(t.m=!0),t},Y.prototype.ta=function(t){return!t.i&&!t.a},Oe.prototype.createWebChannel=Oe.prototype.a,W.prototype.send=W.prototype.l,W.prototype.open=W.prototype.j,W.prototype.close=W.prototype.close,Fc.NO_ERROR=0,Fc.TIMEOUT=8,Fc.HTTP_ERROR=6,Gc.COMPLETE="complete",Md.EventType=Nd,Nd.OPEN="a",Nd.CLOSE="b",Nd.ERROR="c",Nd.MESSAGE="d",B.prototype.listen=B.prototype.aa,Y.prototype.getObject=Y.prototype.ea,Y.prototype.releaseObject=Y.prototype.gb,T.prototype.listenOnce=T.prototype.Ha,T.prototype.getLastError=T.prototype.Za,T.prototype.getLastErrorCode=T.prototype.Fa,T.prototype.getStatus=T.prototype.W,T.prototype.getStatusText=T.prototype.Ga,T.prototype.getResponseJson=T.prototype.Ya,T.prototype.getResponseText=T.prototype.V,T.prototype.getResponseText=T.prototype.V,T.prototype.send=T.prototype.fa,module.exports={createWebChannelTransport:Se,ErrorCode:Fc,EventType:Gc,WebChannel:Md,XhrIoPool:Y}}).call(void 0!==global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})}).call(exports,__webpack_require__(12))}},[113])}catch(t){throw Error("Cannot instantiate firebase-firestore.js - be sure to load firebase-app.js first.")} +//# sourceMappingURL=firebase-firestore.js.map \ No newline at end of file