/******/ (function(modules) { // webpackBootstrap
/******/ 	// install a JSONP callback for chunk loading
/******/ 	function webpackJsonpCallback(data) {
/******/ 		var chunkIds = data[0];
/******/ 		var moreModules = data[1];
/******/
/******/
/******/ 		// add "moreModules" to the modules object,
/******/ 		// then flag all "chunkIds" as loaded and fire callback
/******/ 		var moduleId, chunkId, i = 0, resolves = [];
/******/ 		for(;i < chunkIds.length; i++) {
/******/ 			chunkId = chunkIds[i];
/******/ 			if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ 				resolves.push(installedChunks[chunkId][0]);
/******/ 			}
/******/ 			installedChunks[chunkId] = 0;
/******/ 		}
/******/ 		for(moduleId in moreModules) {
/******/ 			if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
/******/ 				modules[moduleId] = moreModules[moduleId];
/******/ 			}
/******/ 		}
/******/ 		if(parentJsonpFunction) parentJsonpFunction(data);
/******/
/******/ 		while(resolves.length) {
/******/ 			resolves.shift()();
/******/ 		}
/******/
/******/ 	};
/******/
/******/
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// object to store loaded and loading chunks
/******/ 	// undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ 	// Promise = chunk loading, 0 = chunk loaded
/******/ 	var installedChunks = {
/******/ 		178: 0
/******/ 	};
/******/
/******/
/******/
/******/ 	// script path function
/******/ 	function jsonpScriptSrc(chunkId) {
/******/ 		return __webpack_require__.p + "" + ({"0":"locales/dayjs/af","1":"locales/dayjs/ar","2":"locales/dayjs/ar-dz","3":"locales/dayjs/ar-kw","4":"locales/dayjs/ar-ly","5":"locales/dayjs/ar-ma","6":"locales/dayjs/ar-sa","7":"locales/dayjs/ar-tn","8":"locales/dayjs/az","9":"locales/dayjs/be","10":"locales/dayjs/bg","11":"locales/dayjs/bi","12":"locales/dayjs/bm","13":"locales/dayjs/bn","14":"locales/dayjs/bo","15":"locales/dayjs/br","16":"locales/dayjs/bs","17":"locales/dayjs/ca","18":"locales/dayjs/cs","19":"locales/dayjs/cv","20":"locales/dayjs/cy","21":"locales/dayjs/da","22":"locales/dayjs/de","23":"locales/dayjs/de-at","24":"locales/dayjs/de-ch","25":"locales/dayjs/dv","26":"locales/dayjs/el","27":"locales/dayjs/en","28":"locales/dayjs/en-SG","29":"locales/dayjs/en-au","30":"locales/dayjs/en-ca","31":"locales/dayjs/en-gb","32":"locales/dayjs/en-ie","33":"locales/dayjs/en-il","34":"locales/dayjs/en-in","35":"locales/dayjs/en-nz","36":"locales/dayjs/en-tt","37":"locales/dayjs/eo","38":"locales/dayjs/es","39":"locales/dayjs/es-do","40":"locales/dayjs/es-pr","41":"locales/dayjs/es-us","42":"locales/dayjs/et","43":"locales/dayjs/eu","44":"locales/dayjs/fa","45":"locales/dayjs/fi","46":"locales/dayjs/fo","47":"locales/dayjs/fr","48":"locales/dayjs/fr-ca","49":"locales/dayjs/fr-ch","50":"locales/dayjs/fy","51":"locales/dayjs/ga","52":"locales/dayjs/gd","53":"locales/dayjs/gl","54":"locales/dayjs/gom-latn","55":"locales/dayjs/gu","56":"locales/dayjs/he","57":"locales/dayjs/hi","58":"locales/dayjs/hr","59":"locales/dayjs/ht","60":"locales/dayjs/hu","61":"locales/dayjs/hy-am","62":"locales/dayjs/id","63":"locales/dayjs/is","64":"locales/dayjs/it","65":"locales/dayjs/it-ch","66":"locales/dayjs/ja","67":"locales/dayjs/jv","68":"locales/dayjs/ka","69":"locales/dayjs/kk","70":"locales/dayjs/km","71":"locales/dayjs/kn","72":"locales/dayjs/ko","73":"locales/dayjs/ku","74":"locales/dayjs/ky","75":"locales/dayjs/lb","76":"locales/dayjs/lo","77":"locales/dayjs/lt","78":"locales/dayjs/lv","79":"locales/dayjs/me","80":"locales/dayjs/mi","81":"locales/dayjs/mk","82":"locales/dayjs/ml","83":"locales/dayjs/mn","84":"locales/dayjs/mr","85":"locales/dayjs/ms","86":"locales/dayjs/ms-my","87":"locales/dayjs/mt","88":"locales/dayjs/my","89":"locales/dayjs/nb","90":"locales/dayjs/ne","91":"locales/dayjs/nl","92":"locales/dayjs/nl-be","93":"locales/dayjs/nn","94":"locales/dayjs/oc-lnc","95":"locales/dayjs/pa-in","96":"locales/dayjs/pl","97":"locales/dayjs/pt","98":"locales/dayjs/pt-br","99":"locales/dayjs/ro","100":"locales/dayjs/ru","101":"locales/dayjs/rw","102":"locales/dayjs/sd","103":"locales/dayjs/se","104":"locales/dayjs/si","105":"locales/dayjs/sk","106":"locales/dayjs/sl","107":"locales/dayjs/sq","108":"locales/dayjs/sr","109":"locales/dayjs/sr-cyrl","110":"locales/dayjs/ss","111":"locales/dayjs/sv","112":"locales/dayjs/sw","113":"locales/dayjs/ta","114":"locales/dayjs/te","115":"locales/dayjs/tet","116":"locales/dayjs/tg","117":"locales/dayjs/th","118":"locales/dayjs/tk","119":"locales/dayjs/tl-ph","120":"locales/dayjs/tlh","121":"locales/dayjs/tr","122":"locales/dayjs/tzl","123":"locales/dayjs/tzm","124":"locales/dayjs/tzm-latn","125":"locales/dayjs/ug-cn","126":"locales/dayjs/uk","127":"locales/dayjs/ur","128":"locales/dayjs/uz","129":"locales/dayjs/uz-latn","130":"locales/dayjs/vi","131":"locales/dayjs/x-pseudo","132":"locales/dayjs/yo","133":"locales/dayjs/zh","134":"locales/dayjs/zh-cn","135":"locales/dayjs/zh-hk","136":"locales/dayjs/zh-tw","137":"emojis","138":"icons","139":"locales/af-LC_MESSAGES-converse-po","140":"locales/ar-LC_MESSAGES-converse-po","141":"locales/bg-LC_MESSAGES-converse-po","142":"locales/ca-LC_MESSAGES-converse-po","143":"locales/cs-LC_MESSAGES-converse-po","144":"locales/da-LC_MESSAGES-converse-po","145":"locales/dayjs/index-d-ts","146":"locales/dayjs/types-d-ts","147":"locales/de-LC_MESSAGES-converse-po","148":"locales/eo-LC_MESSAGES-converse-po","149":"locales/es-LC_MESSAGES-converse-po","150":"locales/eu-LC_MESSAGES-converse-po","151":"locales/fi-LC_MESSAGES-converse-po","152":"locales/fr-LC_MESSAGES-converse-po","153":"locales/gl-LC_MESSAGES-converse-po","154":"locales/he-LC_MESSAGES-converse-po","155":"locales/hi-LC_MESSAGES-converse-po","156":"locales/hu-LC_MESSAGES-converse-po","157":"locales/id-LC_MESSAGES-converse-po","158":"locales/it-LC_MESSAGES-converse-po","159":"locales/ja-LC_MESSAGES-converse-po","160":"locales/lt-LC_MESSAGES-converse-po","161":"locales/mr-LC_MESSAGES-converse-po","162":"locales/nb-LC_MESSAGES-converse-po","163":"locales/nl-LC_MESSAGES-converse-po","164":"locales/nl_BE-LC_MESSAGES-converse-po","165":"locales/oc-LC_MESSAGES-converse-po","166":"locales/pl-LC_MESSAGES-converse-po","167":"locales/pt-LC_MESSAGES-converse-po","168":"locales/pt_BR-LC_MESSAGES-converse-po","169":"locales/ro-LC_MESSAGES-converse-po","170":"locales/ru-LC_MESSAGES-converse-po","171":"locales/sv-LC_MESSAGES-converse-po","172":"locales/th-LC_MESSAGES-converse-po","173":"locales/tr-LC_MESSAGES-converse-po","174":"locales/uk-LC_MESSAGES-converse-po","175":"locales/vi-LC_MESSAGES-converse-po","176":"locales/zh_CN-LC_MESSAGES-converse-po","177":"locales/zh_TW-LC_MESSAGES-converse-po"}[chunkId]||chunkId) + ".js"
/******/ 	}
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/ 	// This file contains only the entry chunk.
/******/ 	// The chunk loading function for additional chunks
/******/ 	__webpack_require__.e = function requireEnsure(chunkId) {
/******/ 		var promises = [];
/******/
/******/
/******/ 		// JSONP chunk loading for javascript
/******/
/******/ 		var installedChunkData = installedChunks[chunkId];
/******/ 		if(installedChunkData !== 0) { // 0 means "already installed".
/******/
/******/ 			// a Promise means "currently loading".
/******/ 			if(installedChunkData) {
/******/ 				promises.push(installedChunkData[2]);
/******/ 			} else {
/******/ 				// setup Promise in chunk cache
/******/ 				var promise = new Promise(function(resolve, reject) {
/******/ 					installedChunkData = installedChunks[chunkId] = [resolve, reject];
/******/ 				});
/******/ 				promises.push(installedChunkData[2] = promise);
/******/
/******/ 				// start chunk loading
/******/ 				var script = document.createElement('script');
/******/ 				var onScriptComplete;
/******/
/******/ 				script.charset = 'utf-8';
/******/ 				script.timeout = 120;
/******/ 				if (__webpack_require__.nc) {
/******/ 					script.setAttribute("nonce", __webpack_require__.nc);
/******/ 				}
/******/ 				script.src = jsonpScriptSrc(chunkId);
/******/
/******/ 				// create error before stack unwound to get useful stacktrace later
/******/ 				var error = new Error();
/******/ 				onScriptComplete = function (event) {
/******/ 					// avoid mem leaks in IE.
/******/ 					script.onerror = script.onload = null;
/******/ 					clearTimeout(timeout);
/******/ 					var chunk = installedChunks[chunkId];
/******/ 					if(chunk !== 0) {
/******/ 						if(chunk) {
/******/ 							var errorType = event && (event.type === 'load' ? 'missing' : event.type);
/******/ 							var realSrc = event && event.target && event.target.src;
/******/ 							error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')';
/******/ 							error.name = 'ChunkLoadError';
/******/ 							error.type = errorType;
/******/ 							error.request = realSrc;
/******/ 							chunk[1](error);
/******/ 						}
/******/ 						installedChunks[chunkId] = undefined;
/******/ 					}
/******/ 				};
/******/ 				var timeout = setTimeout(function(){
/******/ 					onScriptComplete({ type: 'timeout', target: script });
/******/ 				}, 120000);
/******/ 				script.onerror = script.onload = onScriptComplete;
/******/ 				document.head.appendChild(script);
/******/ 			}
/******/ 		}
/******/ 		return Promise.all(promises);
/******/ 	};
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "/dist/";
/******/
/******/ 	// on error function for async loading
/******/ 	__webpack_require__.oe = function(err) { console.error(err); throw err; };
/******/
/******/ 	var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || [];
/******/ 	var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);
/******/ 	jsonpArray.push = webpackJsonpCallback;
/******/ 	jsonpArray = jsonpArray.slice();
/******/ 	for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);
/******/ 	var parentJsonpFunction = oldJsonpFunction;
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 321);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ $build; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* binding */ $msg; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ $iq; });
__webpack_require__.d(__webpack_exports__, "d", function() { return /* binding */ $pres; });
__webpack_require__.d(__webpack_exports__, "f", function() { return /* binding */ Strophe; });
__webpack_require__.d(__webpack_exports__, "e", function() { return /* reexport */ sha1["a" /* default */]; });

// UNUSED EXPORTS: MD5

// EXTERNAL MODULE: ./node_modules/strophe.js/src/shims.js
var shims = __webpack_require__(8);

// CONCATENATED MODULE: ./node_modules/strophe.js/src/md5.js
/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Everything that isn't used by Strophe has been stripped here!
 */

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
const safe_add = function (x, y) {
  const lsw = (x & 0xFFFF) + (y & 0xFFFF);
  const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return msw << 16 | lsw & 0xFFFF;
};
/*
 * Bitwise rotate a 32-bit number to the left.
 */


const bit_rol = function (num, cnt) {
  return num << cnt | num >>> 32 - cnt;
};
/*
 * Convert a string to an array of little-endian words
 */


const str2binl = function (str) {
  if (typeof str !== "string") {
    throw new Error("str2binl was passed a non-string");
  }

  const bin = [];

  for (let i = 0; i < str.length * 8; i += 8) {
    bin[i >> 5] |= (str.charCodeAt(i / 8) & 255) << i % 32;
  }

  return bin;
};
/*
 * Convert an array of little-endian words to a string
 */


const binl2str = function (bin) {
  let str = "";

  for (let i = 0; i < bin.length * 32; i += 8) {
    str += String.fromCharCode(bin[i >> 5] >>> i % 32 & 255);
  }

  return str;
};
/*
 * Convert an array of little-endian words to a hex string.
 */


const binl2hex = function (binarray) {
  const hex_tab = "0123456789abcdef";
  let str = "";

  for (let i = 0; i < binarray.length * 4; i++) {
    str += hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 + 4 & 0xF) + hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 & 0xF);
  }

  return str;
};
/*
 * These functions implement the four basic operations the algorithm uses.
 */


const md5_cmn = function (q, a, b, x, s, t) {
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
};

const md5_ff = function (a, b, c, d, x, s, t) {
  return md5_cmn(b & c | ~b & d, a, b, x, s, t);
};

const md5_gg = function (a, b, c, d, x, s, t) {
  return md5_cmn(b & d | c & ~d, a, b, x, s, t);
};

const md5_hh = function (a, b, c, d, x, s, t) {
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
};

const md5_ii = function (a, b, c, d, x, s, t) {
  return md5_cmn(c ^ (b | ~d), a, b, x, s, t);
};
/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */


const core_md5 = function (x, len) {
  /* append padding */
  x[len >> 5] |= 0x80 << len % 32;
  x[(len + 64 >>> 9 << 4) + 14] = len;
  let a = 1732584193;
  let b = -271733879;
  let c = -1732584194;
  let d = 271733878;
  let olda, oldb, oldc, oldd;

  for (let i = 0; i < x.length; i += 16) {
    olda = a;
    oldb = b;
    oldc = c;
    oldd = d;
    a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
    d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
    b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
    d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
    c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
    d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
    d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
    a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
    d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
    c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
    b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
    d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
    c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
    d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
    c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
    a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
    d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
    c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
    b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
    a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
    d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
    b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
    d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
    c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
    d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
    a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
    d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
    b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
    a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
    d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
    c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
    d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
    d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
    a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
    d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
    b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }

  return [a, b, c, d];
};
/*
 * These are the functions you'll usually want to call.
 * They take string arguments and return either hex or base-64 encoded
 * strings.
 */


const MD5 = {
  hexdigest: function (s) {
    return binl2hex(core_md5(str2binl(s), s.length * 8));
  },
  hash: function (s) {
    return binl2str(core_md5(str2binl(s), s.length * 8));
  }
};

// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl.js
/** Class: Strophe.SASLMechanism
 *
 *  Encapsulates an SASL authentication mechanism.
 *
 *  User code may override the priority for each mechanism or disable it completely.
 *  See <priority> for information about changing priority and <test> for informatian on
 *  how to disable a mechanism.
 *
 *  By default, all mechanisms are enabled and the priorities are
 *
 *      SCRAM-SHA-1 - 60
 *      PLAIN       - 50
 *      OAUTHBEARER - 40
 *      X-OAUTH2    - 30
 *      ANONYMOUS   - 20
 *      EXTERNAL    - 10
 *
 *  See: Strophe.Connection.addSupportedSASLMechanisms
 */
class SASLMechanism {
  /**
   * PrivateConstructor: Strophe.SASLMechanism
   * SASL auth mechanism abstraction.
   *
   *  Parameters:
   *    (String) name - SASL Mechanism name.
   *    (Boolean) isClientFirst - If client should send response first without challenge.
   *    (Number) priority - Priority.
   *
   *  Returns:
   *    A new Strophe.SASLMechanism object.
   */
  constructor(name, isClientFirst, priority) {
    /** PrivateVariable: mechname
     *  Mechanism name.
     */
    this.mechname = name;
    /** PrivateVariable: isClientFirst
     *  If client sends response without initial server challenge.
     */

    this.isClientFirst = isClientFirst;
    /** Variable: priority
     *  Determines which <SASLMechanism> is chosen for authentication (Higher is better).
     *  Users may override this to prioritize mechanisms differently.
     *
     *  Example: (This will cause Strophe to choose the mechanism that the server sent first)
     *
     *  > Strophe.SASLPlain.priority = Strophe.SASLSHA1.priority;
     *
     *  See <SASL mechanisms> for a list of available mechanisms.
     *
     */

    this.priority = priority;
  }
  /**
   *  Function: test
   *  Checks if mechanism able to run.
   *  To disable a mechanism, make this return false;
   *
   *  To disable plain authentication run
   *  > Strophe.SASLPlain.test = function() {
   *  >   return false;
   *  > }
   *
   *  See <SASL mechanisms> for a list of available mechanisms.
   *
   *  Parameters:
   *    (Strophe.Connection) connection - Target Connection.
   *
   *  Returns:
   *    (Boolean) If mechanism was able to run.
   */


  test() {
    // eslint-disable-line class-methods-use-this
    return true;
  }
  /** PrivateFunction: onStart
   *  Called before starting mechanism on some connection.
   *
   *  Parameters:
   *    (Strophe.Connection) connection - Target Connection.
   */


  onStart(connection) {
    this._connection = connection;
  }
  /** PrivateFunction: onChallenge
   *  Called by protocol implementation on incoming challenge.
   *
   *  By deafult, if the client is expected to send data first (isClientFirst === true),
   *  this method is called with `challenge` as null on the first call,
   *  unless `clientChallenge` is overridden in the relevant subclass.
   *
   *  Parameters:
   *    (Strophe.Connection) connection - Target Connection.
   *    (String) challenge - current challenge to handle.
   *
   *  Returns:
   *    (String) Mechanism response.
   */


  onChallenge(connection, challenge) {
    // eslint-disable-line
    throw new Error("You should implement challenge handling!");
  }
  /** PrivateFunction: clientChallenge
   *  Called by the protocol implementation if the client is expected to send
   *  data first in the authentication exchange (i.e. isClientFirst === true).
   *
   *  Parameters:
   *    (Strophe.Connection) connection - Target Connection.
   *
   *  Returns:
   *    (String) Mechanism response.
   */


  clientChallenge(connection) {
    if (!this.isClientFirst) {
      throw new Error("clientChallenge should not be called if isClientFirst is false!");
    }

    return this.onChallenge(connection);
  }
  /** PrivateFunction: onFailure
   *  Protocol informs mechanism implementation about SASL failure.
   */


  onFailure() {
    this._connection = null;
  }
  /** PrivateFunction: onSuccess
   *  Protocol informs mechanism implementation about SASL success.
   */


  onSuccess() {
    this._connection = null;
  }

}
// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-anon.js
 // Building SASL callbacks

class sasl_anon_SASLAnonymous extends SASLMechanism {
  /** PrivateConstructor: SASLAnonymous
   *  SASL ANONYMOUS authentication.
   */
  constructor(mechname = 'ANONYMOUS', isClientFirst = false, priority = 20) {
    super(mechname, isClientFirst, priority);
  }

  test(connection) {
    // eslint-disable-line class-methods-use-this
    return connection.authcid === null;
  }

}
// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-external.js

class sasl_external_SASLExternal extends SASLMechanism {
  /** PrivateConstructor: SASLExternal
   *  SASL EXTERNAL authentication.
   *
   *  The EXTERNAL mechanism allows a client to request the server to use
   *  credentials established by means external to the mechanism to
   *  authenticate the client. The external means may be, for instance,
   *  TLS services.
   */
  constructor(mechname = 'EXTERNAL', isClientFirst = true, priority = 10) {
    super(mechname, isClientFirst, priority);
  }

  onChallenge(connection) {
    // eslint-disable-line class-methods-use-this

    /** According to XEP-178, an authzid SHOULD NOT be presented when the
     * authcid contained or implied in the client certificate is the JID (i.e.
     * authzid) with which the user wants to log in as.
     *
     * To NOT send the authzid, the user should therefore set the authcid equal
     * to the JID when instantiating a new Strophe.Connection object.
     */
    return connection.authcid === connection.authzid ? '' : connection.authzid;
  }

}
// CONCATENATED MODULE: ./node_modules/strophe.js/src/utils.js
const utils = {
  utf16to8: function (str) {
    var i, c;
    var out = "";
    var len = str.length;

    for (i = 0; i < len; i++) {
      c = str.charCodeAt(i);

      if (c >= 0x0000 && c <= 0x007F) {
        out += str.charAt(i);
      } else if (c > 0x07FF) {
        out += String.fromCharCode(0xE0 | c >> 12 & 0x0F);
        out += String.fromCharCode(0x80 | c >> 6 & 0x3F);
        out += String.fromCharCode(0x80 | c >> 0 & 0x3F);
      } else {
        out += String.fromCharCode(0xC0 | c >> 6 & 0x1F);
        out += String.fromCharCode(0x80 | c >> 0 & 0x3F);
      }
    }

    return out;
  },
  addCookies: function (cookies) {
    /* Parameters:
     *  (Object) cookies - either a map of cookie names
     *    to string values or to maps of cookie values.
     *
     * For example:
     * { "myCookie": "1234" }
     *
     * or:
     * { "myCookie": {
     *      "value": "1234",
     *      "domain": ".example.org",
     *      "path": "/",
     *      "expires": expirationDate
     *      }
     *  }
     *
     *  These values get passed to Strophe.Connection via
     *   options.cookies
     */
    cookies = cookies || {};

    for (const cookieName in cookies) {
      if (Object.prototype.hasOwnProperty.call(cookies, cookieName)) {
        let expires = '';
        let domain = '';
        let path = '';
        const cookieObj = cookies[cookieName];
        const isObj = typeof cookieObj === "object";
        const cookieValue = escape(unescape(isObj ? cookieObj.value : cookieObj));

        if (isObj) {
          expires = cookieObj.expires ? ";expires=" + cookieObj.expires : '';
          domain = cookieObj.domain ? ";domain=" + cookieObj.domain : '';
          path = cookieObj.path ? ";path=" + cookieObj.path : '';
        }

        document.cookie = cookieName + '=' + cookieValue + expires + domain + path;
      }
    }
  }
};

// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-oauthbearer.js


class sasl_oauthbearer_SASLOAuthBearer extends SASLMechanism {
  /** PrivateConstructor: SASLOAuthBearer
   *  SASL OAuth Bearer authentication.
   */
  constructor(mechname = 'OAUTHBEARER', isClientFirst = true, priority = 40) {
    super(mechname, isClientFirst, priority);
  }

  test(connection) {
    // eslint-disable-line class-methods-use-this
    return connection.pass !== null;
  }

  onChallenge(connection) {
    // eslint-disable-line class-methods-use-this
    let auth_str = 'n,';

    if (connection.authcid !== null) {
      auth_str = auth_str + 'a=' + connection.authzid;
    }

    auth_str = auth_str + ',';
    auth_str = auth_str + "\u0001";
    auth_str = auth_str + 'auth=Bearer ';
    auth_str = auth_str + connection.pass;
    auth_str = auth_str + "\u0001";
    auth_str = auth_str + "\u0001";
    return utils.utf16to8(auth_str);
  }

}
// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-plain.js


class sasl_plain_SASLPlain extends SASLMechanism {
  /** PrivateConstructor: SASLPlain
   *  SASL PLAIN authentication.
   */
  constructor(mechname = 'PLAIN', isClientFirst = true, priority = 50) {
    super(mechname, isClientFirst, priority);
  }

  test(connection) {
    // eslint-disable-line class-methods-use-this
    return connection.authcid !== null;
  }

  onChallenge(connection) {
    // eslint-disable-line class-methods-use-this
    const {
      authcid,
      authzid,
      domain,
      pass
    } = connection;

    if (!domain) {
      throw new Error("SASLPlain onChallenge: domain is not defined!");
    } // Only include authzid if it differs from authcid.
    // See: https://tools.ietf.org/html/rfc6120#section-6.3.8


    let auth_str = authzid !== `${authcid}@${domain}` ? authzid : '';
    auth_str = auth_str + "\u0000";
    auth_str = auth_str + authcid;
    auth_str = auth_str + "\u0000";
    auth_str = auth_str + pass;
    return utils.utf16to8(auth_str);
  }

}
// EXTERNAL MODULE: ./node_modules/strophe.js/src/sha1.js
var sha1 = __webpack_require__(6);

// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-sha1.js




class sasl_sha1_SASLSHA1 extends SASLMechanism {
  /** PrivateConstructor: SASLSHA1
   *  SASL SCRAM SHA 1 authentication.
   */
  constructor(mechname = 'SCRAM-SHA-1', isClientFirst = true, priority = 60) {
    super(mechname, isClientFirst, priority);
  }

  test(connection) {
    // eslint-disable-line class-methods-use-this
    return connection.authcid !== null;
  }

  onChallenge(connection, challenge) {
    // eslint-disable-line class-methods-use-this
    let nonce, salt, iter, Hi, U, U_old, i, k;
    let responseText = "c=biws,";
    let authMessage = `${connection._sasl_data["client-first-message-bare"]},${challenge},`;
    const cnonce = connection._sasl_data.cnonce;
    const attribMatch = /([a-z]+)=([^,]+)(,|$)/;

    while (challenge.match(attribMatch)) {
      const matches = challenge.match(attribMatch);
      challenge = challenge.replace(matches[0], "");

      switch (matches[1]) {
        case "r":
          nonce = matches[2];
          break;

        case "s":
          salt = matches[2];
          break;

        case "i":
          iter = matches[2];
          break;
      }
    }

    if (nonce.substr(0, cnonce.length) !== cnonce) {
      connection._sasl_data = {};
      return connection._sasl_failure_cb();
    }

    responseText += "r=" + nonce;
    authMessage += responseText;
    salt = atob(salt);
    salt += "\x00\x00\x00\x01";
    const pass = utils.utf16to8(connection.pass);
    Hi = U_old = sha1["a" /* default */].core_hmac_sha1(pass, salt);

    for (i = 1; i < iter; i++) {
      U = sha1["a" /* default */].core_hmac_sha1(pass, sha1["a" /* default */].binb2str(U_old));

      for (k = 0; k < 5; k++) {
        Hi[k] ^= U[k];
      }

      U_old = U;
    }

    Hi = sha1["a" /* default */].binb2str(Hi);
    const clientKey = sha1["a" /* default */].core_hmac_sha1(Hi, "Client Key");
    const serverKey = sha1["a" /* default */].str_hmac_sha1(Hi, "Server Key");
    const clientSignature = sha1["a" /* default */].core_hmac_sha1(sha1["a" /* default */].str_sha1(sha1["a" /* default */].binb2str(clientKey)), authMessage);
    connection._sasl_data["server-signature"] = sha1["a" /* default */].b64_hmac_sha1(serverKey, authMessage);

    for (k = 0; k < 5; k++) {
      clientKey[k] ^= clientSignature[k];
    }

    responseText += ",p=" + btoa(sha1["a" /* default */].binb2str(clientKey));
    return responseText;
  }

  clientChallenge(connection, test_cnonce) {
    // eslint-disable-line class-methods-use-this
    const cnonce = test_cnonce || MD5.hexdigest("" + Math.random() * 1234567890);
    let auth_str = "n=" + utils.utf16to8(connection.authcid);
    auth_str += ",r=";
    auth_str += cnonce;
    connection._sasl_data.cnonce = cnonce;
    connection._sasl_data["client-first-message-bare"] = auth_str;
    auth_str = "n,," + auth_str;
    return auth_str;
  }

}
// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-xoauth2.js


class sasl_xoauth2_SASLXOAuth2 extends SASLMechanism {
  /** PrivateConstructor: SASLXOAuth2
   *  SASL X-OAuth2 authentication.
   */
  constructor(mechname = 'X-OAUTH2', isClientFirst = true, priority = 30) {
    super(mechname, isClientFirst, priority);
  }

  test(connection) {
    // eslint-disable-line class-methods-use-this
    return connection.pass !== null;
  }

  onChallenge(connection) {
    // eslint-disable-line class-methods-use-this
    let auth_str = '\u0000';

    if (connection.authcid !== null) {
      auth_str = auth_str + connection.authzid;
    }

    auth_str = auth_str + "\u0000";
    auth_str = auth_str + connection.pass;
    return utils.utf16to8(auth_str);
  }

}
// EXTERNAL MODULE: ./node_modules/abab/index.js
var abab = __webpack_require__(40);

// CONCATENATED MODULE: ./node_modules/strophe.js/src/core.js
/*
    This program is distributed under the terms of the MIT license.
    Please see the LICENSE file for details.

    Copyright 2006-2018, OGG, LLC
*/

/*global define, document, sessionStorage, setTimeout, clearTimeout, ActiveXObject, DOMParser, btoa, atob */












/** Function: $build
 *  Create a Strophe.Builder.
 *  This is an alias for 'new Strophe.Builder(name, attrs)'.
 *
 *  Parameters:
 *    (String) name - The root element name.
 *    (Object) attrs - The attributes for the root element in object notation.
 *
 *  Returns:
 *    A new Strophe.Builder object.
 */

function $build(name, attrs) {
  return new Strophe.Builder(name, attrs);
}
/** Function: $msg
 *  Create a Strophe.Builder with a <message/> element as the root.
 *
 *  Parameters:
 *    (Object) attrs - The <message/> element attributes in object notation.
 *
 *  Returns:
 *    A new Strophe.Builder object.
 */

function $msg(attrs) {
  return new Strophe.Builder("message", attrs);
}
/** Function: $iq
 *  Create a Strophe.Builder with an <iq/> element as the root.
 *
 *  Parameters:
 *    (Object) attrs - The <iq/> element attributes in object notation.
 *
 *  Returns:
 *    A new Strophe.Builder object.
 */

function $iq(attrs) {
  return new Strophe.Builder("iq", attrs);
}
/** Function: $pres
 *  Create a Strophe.Builder with a <presence/> element as the root.
 *
 *  Parameters:
 *    (Object) attrs - The <presence/> element attributes in object notation.
 *
 *  Returns:
 *    A new Strophe.Builder object.
 */

function $pres(attrs) {
  return new Strophe.Builder("presence", attrs);
}
/** Class: Strophe
 *  An object container for all Strophe library functions.
 *
 *  This class is just a container for all the objects and constants
 *  used in the library.  It is not meant to be instantiated, but to
 *  provide a namespace for library objects, constants, and functions.
 */

const Strophe = {
  /** Constant: VERSION */
  VERSION: "1.4.1",

  /** Constants: XMPP Namespace Constants
   *  Common namespace constants from the XMPP RFCs and XEPs.
   *
   *  NS.HTTPBIND - HTTP BIND namespace from XEP 124.
   *  NS.BOSH - BOSH namespace from XEP 206.
   *  NS.CLIENT - Main XMPP client namespace.
   *  NS.AUTH - Legacy authentication namespace.
   *  NS.ROSTER - Roster operations namespace.
   *  NS.PROFILE - Profile namespace.
   *  NS.DISCO_INFO - Service discovery info namespace from XEP 30.
   *  NS.DISCO_ITEMS - Service discovery items namespace from XEP 30.
   *  NS.MUC - Multi-User Chat namespace from XEP 45.
   *  NS.SASL - XMPP SASL namespace from RFC 3920.
   *  NS.STREAM - XMPP Streams namespace from RFC 3920.
   *  NS.BIND - XMPP Binding namespace from RFC 3920 and RFC 6120.
   *  NS.SESSION - XMPP Session namespace from RFC 3920.
   *  NS.XHTML_IM - XHTML-IM namespace from XEP 71.
   *  NS.XHTML - XHTML body namespace from XEP 71.
   */
  NS: {
    HTTPBIND: "http://jabber.org/protocol/httpbind",
    BOSH: "urn:xmpp:xbosh",
    CLIENT: "jabber:client",
    AUTH: "jabber:iq:auth",
    ROSTER: "jabber:iq:roster",
    PROFILE: "jabber:iq:profile",
    DISCO_INFO: "http://jabber.org/protocol/disco#info",
    DISCO_ITEMS: "http://jabber.org/protocol/disco#items",
    MUC: "http://jabber.org/protocol/muc",
    SASL: "urn:ietf:params:xml:ns:xmpp-sasl",
    STREAM: "http://etherx.jabber.org/streams",
    FRAMING: "urn:ietf:params:xml:ns:xmpp-framing",
    BIND: "urn:ietf:params:xml:ns:xmpp-bind",
    SESSION: "urn:ietf:params:xml:ns:xmpp-session",
    VERSION: "jabber:iq:version",
    STANZAS: "urn:ietf:params:xml:ns:xmpp-stanzas",
    XHTML_IM: "http://jabber.org/protocol/xhtml-im",
    XHTML: "http://www.w3.org/1999/xhtml"
  },

  /** Constants: XHTML_IM Namespace
   *  contains allowed tags, tag attributes, and css properties.
   *  Used in the createHtml function to filter incoming html into the allowed XHTML-IM subset.
   *  See http://xmpp.org/extensions/xep-0071.html#profile-summary for the list of recommended
   *  allowed tags and their attributes.
   */
  XHTML: {
    tags: ['a', 'blockquote', 'br', 'cite', 'em', 'img', 'li', 'ol', 'p', 'span', 'strong', 'ul', 'body'],
    attributes: {
      'a': ['href'],
      'blockquote': ['style'],
      'br': [],
      'cite': ['style'],
      'em': [],
      'img': ['src', 'alt', 'style', 'height', 'width'],
      'li': ['style'],
      'ol': ['style'],
      'p': ['style'],
      'span': ['style'],
      'strong': [],
      'ul': ['style'],
      'body': []
    },
    css: ['background-color', 'color', 'font-family', 'font-size', 'font-style', 'font-weight', 'margin-left', 'margin-right', 'text-align', 'text-decoration'],

    /** Function: XHTML.validTag
     *
     * Utility method to determine whether a tag is allowed
     * in the XHTML_IM namespace.
     *
     * XHTML tag names are case sensitive and must be lower case.
     */
    validTag(tag) {
      for (let i = 0; i < Strophe.XHTML.tags.length; i++) {
        if (tag === Strophe.XHTML.tags[i]) {
          return true;
        }
      }

      return false;
    },

    /** Function: XHTML.validAttribute
     *
     * Utility method to determine whether an attribute is allowed
     * as recommended per XEP-0071
     *
     * XHTML attribute names are case sensitive and must be lower case.
     */
    validAttribute(tag, attribute) {
      if (typeof Strophe.XHTML.attributes[tag] !== 'undefined' && Strophe.XHTML.attributes[tag].length > 0) {
        for (let i = 0; i < Strophe.XHTML.attributes[tag].length; i++) {
          if (attribute === Strophe.XHTML.attributes[tag][i]) {
            return true;
          }
        }
      }

      return false;
    },

    validCSS(style) {
      for (let i = 0; i < Strophe.XHTML.css.length; i++) {
        if (style === Strophe.XHTML.css[i]) {
          return true;
        }
      }

      return false;
    }

  },

  /** Constants: Connection Status Constants
   *  Connection status constants for use by the connection handler
   *  callback.
   *
   *  Status.ERROR - An error has occurred
   *  Status.CONNECTING - The connection is currently being made
   *  Status.CONNFAIL - The connection attempt failed
   *  Status.AUTHENTICATING - The connection is authenticating
   *  Status.AUTHFAIL - The authentication attempt failed
   *  Status.CONNECTED - The connection has succeeded
   *  Status.DISCONNECTED - The connection has been terminated
   *  Status.DISCONNECTING - The connection is currently being terminated
   *  Status.ATTACHED - The connection has been attached
   *  Status.REDIRECT - The connection has been redirected
   *  Status.CONNTIMEOUT - The connection has timed out
   */
  Status: {
    ERROR: 0,
    CONNECTING: 1,
    CONNFAIL: 2,
    AUTHENTICATING: 3,
    AUTHFAIL: 4,
    CONNECTED: 5,
    DISCONNECTED: 6,
    DISCONNECTING: 7,
    ATTACHED: 8,
    REDIRECT: 9,
    CONNTIMEOUT: 10,
    BINDREQUIRED: 11,
    ATTACHFAIL: 12
  },
  ErrorCondition: {
    BAD_FORMAT: "bad-format",
    CONFLICT: "conflict",
    MISSING_JID_NODE: "x-strophe-bad-non-anon-jid",
    NO_AUTH_MECH: "no-auth-mech",
    UNKNOWN_REASON: "unknown"
  },

  /** Constants: Log Level Constants
   *  Logging level indicators.
   *
   *  LogLevel.DEBUG - Debug output
   *  LogLevel.INFO - Informational output
   *  LogLevel.WARN - Warnings
   *  LogLevel.ERROR - Errors
   *  LogLevel.FATAL - Fatal errors
   */
  LogLevel: {
    DEBUG: 0,
    INFO: 1,
    WARN: 2,
    ERROR: 3,
    FATAL: 4
  },

  /** PrivateConstants: DOM Element Type Constants
   *  DOM element types.
   *
   *  ElementType.NORMAL - Normal element.
   *  ElementType.TEXT - Text data element.
   *  ElementType.FRAGMENT - XHTML fragment element.
   */
  ElementType: {
    NORMAL: 1,
    TEXT: 3,
    CDATA: 4,
    FRAGMENT: 11
  },

  /** PrivateConstants: Timeout Values
   *  Timeout values for error states.  These values are in seconds.
   *  These should not be changed unless you know exactly what you are
   *  doing.
   *
   *  TIMEOUT - Timeout multiplier. A waiting request will be considered
   *      failed after Math.floor(TIMEOUT * wait) seconds have elapsed.
   *      This defaults to 1.1, and with default wait, 66 seconds.
   *  SECONDARY_TIMEOUT - Secondary timeout multiplier. In cases where
   *      Strophe can detect early failure, it will consider the request
   *      failed if it doesn't return after
   *      Math.floor(SECONDARY_TIMEOUT * wait) seconds have elapsed.
   *      This defaults to 0.1, and with default wait, 6 seconds.
   */
  TIMEOUT: 1.1,
  SECONDARY_TIMEOUT: 0.1,

  /** Function: addNamespace
   *  This function is used to extend the current namespaces in
   *  Strophe.NS.  It takes a key and a value with the key being the
   *  name of the new namespace, with its actual value.
   *  For example:
   *  Strophe.addNamespace('PUBSUB', "http://jabber.org/protocol/pubsub");
   *
   *  Parameters:
   *    (String) name - The name under which the namespace will be
   *      referenced under Strophe.NS
   *    (String) value - The actual namespace.
   */
  addNamespace(name, value) {
    Strophe.NS[name] = value;
  },

  /** Function: forEachChild
   *  Map a function over some or all child elements of a given element.
   *
   *  This is a small convenience function for mapping a function over
   *  some or all of the children of an element.  If elemName is null, all
   *  children will be passed to the function, otherwise only children
   *  whose tag names match elemName will be passed.
   *
   *  Parameters:
   *    (XMLElement) elem - The element to operate on.
   *    (String) elemName - The child element tag name filter.
   *    (Function) func - The function to apply to each child.  This
   *      function should take a single argument, a DOM element.
   */
  forEachChild(elem, elemName, func) {
    for (let i = 0; i < elem.childNodes.length; i++) {
      const childNode = elem.childNodes[i];

      if (childNode.nodeType === Strophe.ElementType.NORMAL && (!elemName || this.isTagEqual(childNode, elemName))) {
        func(childNode);
      }
    }
  },

  /** Function: isTagEqual
   *  Compare an element's tag name with a string.
   *
   *  This function is case sensitive.
   *
   *  Parameters:
   *    (XMLElement) el - A DOM element.
   *    (String) name - The element name.
   *
   *  Returns:
   *    true if the element's tag name matches _el_, and false
   *    otherwise.
   */
  isTagEqual(el, name) {
    return el.tagName === name;
  },

  /** PrivateVariable: _xmlGenerator
   *  _Private_ variable that caches a DOM document to
   *  generate elements.
   */
  _xmlGenerator: null,

  /** Function: xmlGenerator
   *  Get the DOM document to generate elements.
   *
   *  Returns:
   *    The currently used DOM document.
   */
  xmlGenerator() {
    if (!Strophe._xmlGenerator) {
      Strophe._xmlGenerator = shims["c" /* getDummyXMLDOMDocument */]();
    }

    return Strophe._xmlGenerator;
  },

  /** Function: xmlElement
   *  Create an XML DOM element.
   *
   *  This function creates an XML DOM element correctly across all
   *  implementations. Note that these are not HTML DOM elements, which
   *  aren't appropriate for XMPP stanzas.
   *
   *  Parameters:
   *    (String) name - The name for the element.
   *    (Array|Object) attrs - An optional array or object containing
   *      key/value pairs to use as element attributes. The object should
   *      be in the format {'key': 'value'} or {key: 'value'}. The array
   *      should have the format [['key1', 'value1'], ['key2', 'value2']].
   *    (String) text - The text child data for the element.
   *
   *  Returns:
   *    A new XML DOM element.
   */
  xmlElement(name) {
    if (!name) {
      return null;
    }

    const node = Strophe.xmlGenerator().createElement(name); // FIXME: this should throw errors if args are the wrong type or
    // there are more than two optional args

    for (let a = 1; a < arguments.length; a++) {
      const arg = arguments[a];

      if (!arg) {
        continue;
      }

      if (typeof arg === "string" || typeof arg === "number") {
        node.appendChild(Strophe.xmlTextNode(arg));
      } else if (typeof arg === "object" && typeof arg.sort === "function") {
        for (let i = 0; i < arg.length; i++) {
          const attr = arg[i];

          if (typeof attr === "object" && typeof attr.sort === "function" && attr[1] !== undefined && attr[1] !== null) {
            node.setAttribute(attr[0], attr[1]);
          }
        }
      } else if (typeof arg === "object") {
        for (const k in arg) {
          if (Object.prototype.hasOwnProperty.call(arg, k) && arg[k] !== undefined && arg[k] !== null) {
            node.setAttribute(k, arg[k]);
          }
        }
      }
    }

    return node;
  },

  /*  Function: xmlescape
   *  Excapes invalid xml characters.
   *
   *  Parameters:
   *     (String) text - text to escape.
   *
   *  Returns:
   *      Escaped text.
   */
  xmlescape(text) {
    text = text.replace(/\&/g, "&amp;");
    text = text.replace(/</g, "&lt;");
    text = text.replace(/>/g, "&gt;");
    text = text.replace(/'/g, "&apos;");
    text = text.replace(/"/g, "&quot;");
    return text;
  },

  /*  Function: xmlunescape
  *  Unexcapes invalid xml characters.
  *
  *  Parameters:
  *     (String) text - text to unescape.
  *
  *  Returns:
  *      Unescaped text.
  */
  xmlunescape(text) {
    text = text.replace(/\&amp;/g, "&");
    text = text.replace(/&lt;/g, "<");
    text = text.replace(/&gt;/g, ">");
    text = text.replace(/&apos;/g, "'");
    text = text.replace(/&quot;/g, "\"");
    return text;
  },

  /** Function: xmlTextNode
   *  Creates an XML DOM text node.
   *
   *  Provides a cross implementation version of document.createTextNode.
   *
   *  Parameters:
   *    (String) text - The content of the text node.
   *
   *  Returns:
   *    A new XML DOM text node.
   */
  xmlTextNode(text) {
    return Strophe.xmlGenerator().createTextNode(text);
  },

  /** Function: xmlHtmlNode
   *  Creates an XML DOM html node.
   *
   *  Parameters:
   *    (String) html - The content of the html node.
   *
   *  Returns:
   *    A new XML DOM text node.
   */
  xmlHtmlNode(html) {
    let node; //ensure text is escaped

    if (shims["a" /* DOMParser */]) {
      const parser = new shims["a" /* DOMParser */]();
      node = parser.parseFromString(html, "text/xml");
    } else {
      node = new ActiveXObject("Microsoft.XMLDOM");
      node.async = "false";
      node.loadXML(html);
    }

    return node;
  },

  /** Function: getText
   *  Get the concatenation of all text children of an element.
   *
   *  Parameters:
   *    (XMLElement) elem - A DOM element.
   *
   *  Returns:
   *    A String with the concatenated text of all text element children.
   */
  getText(elem) {
    if (!elem) {
      return null;
    }

    let str = "";

    if (elem.childNodes.length === 0 && elem.nodeType === Strophe.ElementType.TEXT) {
      str += elem.nodeValue;
    }

    for (let i = 0; i < elem.childNodes.length; i++) {
      if (elem.childNodes[i].nodeType === Strophe.ElementType.TEXT) {
        str += elem.childNodes[i].nodeValue;
      }
    }

    return Strophe.xmlescape(str);
  },

  /** Function: copyElement
   *  Copy an XML DOM element.
   *
   *  This function copies a DOM element and all its descendants and returns
   *  the new copy.
   *
   *  Parameters:
   *    (XMLElement) elem - A DOM element.
   *
   *  Returns:
   *    A new, copied DOM element tree.
   */
  copyElement(elem) {
    let el;

    if (elem.nodeType === Strophe.ElementType.NORMAL) {
      el = Strophe.xmlElement(elem.tagName);

      for (let i = 0; i < elem.attributes.length; i++) {
        el.setAttribute(elem.attributes[i].nodeName, elem.attributes[i].value);
      }

      for (let i = 0; i < elem.childNodes.length; i++) {
        el.appendChild(Strophe.copyElement(elem.childNodes[i]));
      }
    } else if (elem.nodeType === Strophe.ElementType.TEXT) {
      el = Strophe.xmlGenerator().createTextNode(elem.nodeValue);
    }

    return el;
  },

  /** Function: createHtml
   *  Copy an HTML DOM element into an XML DOM.
   *
   *  This function copies a DOM element and all its descendants and returns
   *  the new copy.
   *
   *  Parameters:
   *    (HTMLElement) elem - A DOM element.
   *
   *  Returns:
   *    A new, copied DOM element tree.
   */
  createHtml(elem) {
    let el;

    if (elem.nodeType === Strophe.ElementType.NORMAL) {
      const tag = elem.nodeName.toLowerCase(); // XHTML tags must be lower case.

      if (Strophe.XHTML.validTag(tag)) {
        try {
          el = Strophe.xmlElement(tag);

          for (let i = 0; i < Strophe.XHTML.attributes[tag].length; i++) {
            const attribute = Strophe.XHTML.attributes[tag][i];
            let value = elem.getAttribute(attribute);

            if (typeof value === 'undefined' || value === null || value === '' || value === false || value === 0) {
              continue;
            }

            if (attribute === 'style' && typeof value === 'object' && typeof value.cssText !== 'undefined') {
              value = value.cssText; // we're dealing with IE, need to get CSS out
            } // filter out invalid css styles


            if (attribute === 'style') {
              const css = [];
              const cssAttrs = value.split(';');

              for (let j = 0; j < cssAttrs.length; j++) {
                const attr = cssAttrs[j].split(':');
                const cssName = attr[0].replace(/^\s*/, "").replace(/\s*$/, "").toLowerCase();

                if (Strophe.XHTML.validCSS(cssName)) {
                  const cssValue = attr[1].replace(/^\s*/, "").replace(/\s*$/, "");
                  css.push(cssName + ': ' + cssValue);
                }
              }

              if (css.length > 0) {
                value = css.join('; ');
                el.setAttribute(attribute, value);
              }
            } else {
              el.setAttribute(attribute, value);
            }
          }

          for (let i = 0; i < elem.childNodes.length; i++) {
            el.appendChild(Strophe.createHtml(elem.childNodes[i]));
          }
        } catch (e) {
          // invalid elements
          el = Strophe.xmlTextNode('');
        }
      } else {
        el = Strophe.xmlGenerator().createDocumentFragment();

        for (let i = 0; i < elem.childNodes.length; i++) {
          el.appendChild(Strophe.createHtml(elem.childNodes[i]));
        }
      }
    } else if (elem.nodeType === Strophe.ElementType.FRAGMENT) {
      el = Strophe.xmlGenerator().createDocumentFragment();

      for (let i = 0; i < elem.childNodes.length; i++) {
        el.appendChild(Strophe.createHtml(elem.childNodes[i]));
      }
    } else if (elem.nodeType === Strophe.ElementType.TEXT) {
      el = Strophe.xmlTextNode(elem.nodeValue);
    }

    return el;
  },

  /** Function: escapeNode
   *  Escape the node part (also called local part) of a JID.
   *
   *  Parameters:
   *    (String) node - A node (or local part).
   *
   *  Returns:
   *    An escaped node (or local part).
   */
  escapeNode(node) {
    if (typeof node !== "string") {
      return node;
    }

    return node.replace(/^\s+|\s+$/g, '').replace(/\\/g, "\\5c").replace(/ /g, "\\20").replace(/\"/g, "\\22").replace(/\&/g, "\\26").replace(/\'/g, "\\27").replace(/\//g, "\\2f").replace(/:/g, "\\3a").replace(/</g, "\\3c").replace(/>/g, "\\3e").replace(/@/g, "\\40");
  },

  /** Function: unescapeNode
   *  Unescape a node part (also called local part) of a JID.
   *
   *  Parameters:
   *    (String) node - A node (or local part).
   *
   *  Returns:
   *    An unescaped node (or local part).
   */
  unescapeNode(node) {
    if (typeof node !== "string") {
      return node;
    }

    return node.replace(/\\20/g, " ").replace(/\\22/g, '"').replace(/\\26/g, "&").replace(/\\27/g, "'").replace(/\\2f/g, "/").replace(/\\3a/g, ":").replace(/\\3c/g, "<").replace(/\\3e/g, ">").replace(/\\40/g, "@").replace(/\\5c/g, "\\");
  },

  /** Function: getNodeFromJid
   *  Get the node portion of a JID String.
   *
   *  Parameters:
   *    (String) jid - A JID.
   *
   *  Returns:
   *    A String containing the node.
   */
  getNodeFromJid(jid) {
    if (jid.indexOf("@") < 0) {
      return null;
    }

    return jid.split("@")[0];
  },

  /** Function: getDomainFromJid
   *  Get the domain portion of a JID String.
   *
   *  Parameters:
   *    (String) jid - A JID.
   *
   *  Returns:
   *    A String containing the domain.
   */
  getDomainFromJid(jid) {
    const bare = Strophe.getBareJidFromJid(jid);

    if (bare.indexOf("@") < 0) {
      return bare;
    } else {
      const parts = bare.split("@");
      parts.splice(0, 1);
      return parts.join('@');
    }
  },

  /** Function: getResourceFromJid
   *  Get the resource portion of a JID String.
   *
   *  Parameters:
   *    (String) jid - A JID.
   *
   *  Returns:
   *    A String containing the resource.
   */
  getResourceFromJid(jid) {
    if (!jid) {
      return null;
    }

    const s = jid.split("/");

    if (s.length < 2) {
      return null;
    }

    s.splice(0, 1);
    return s.join('/');
  },

  /** Function: getBareJidFromJid
   *  Get the bare JID from a JID String.
   *
   *  Parameters:
   *    (String) jid - A JID.
   *
   *  Returns:
   *    A String containing the bare JID.
   */
  getBareJidFromJid(jid) {
    return jid ? jid.split("/")[0] : null;
  },

  /** PrivateFunction: _handleError
   *  _Private_ function that properly logs an error to the console
   */
  _handleError(e) {
    if (typeof e.stack !== "undefined") {
      Strophe.fatal(e.stack);
    }

    if (e.sourceURL) {
      Strophe.fatal("error: " + this.handler + " " + e.sourceURL + ":" + e.line + " - " + e.name + ": " + e.message);
    } else if (e.fileName) {
      Strophe.fatal("error: " + this.handler + " " + e.fileName + ":" + e.lineNumber + " - " + e.name + ": " + e.message);
    } else {
      Strophe.fatal("error: " + e.message);
    }
  },

  /** Function: log
   *  User overrideable logging function.
   *
   *  This function is called whenever the Strophe library calls any
   *  of the logging functions.  The default implementation of this
   *  function logs only fatal errors.  If client code wishes to handle the logging
   *  messages, it should override this with
   *  > Strophe.log = function (level, msg) {
   *  >   (user code here)
   *  > };
   *
   *  Please note that data sent and received over the wire is logged
   *  via Strophe.Connection.rawInput() and Strophe.Connection.rawOutput().
   *
   *  The different levels and their meanings are
   *
   *    DEBUG - Messages useful for debugging purposes.
   *    INFO - Informational messages.  This is mostly information like
   *      'disconnect was called' or 'SASL auth succeeded'.
   *    WARN - Warnings about potential problems.  This is mostly used
   *      to report transient connection errors like request timeouts.
   *    ERROR - Some error occurred.
   *    FATAL - A non-recoverable fatal error occurred.
   *
   *  Parameters:
   *    (Integer) level - The log level of the log message.  This will
   *      be one of the values in Strophe.LogLevel.
   *    (String) msg - The log message.
   */
  log(level, msg) {
    if (level === this.LogLevel.FATAL) {
      var _console;

      (_console = console) === null || _console === void 0 ? void 0 : _console.error(msg);
    }
  },

  /** Function: debug
   *  Log a message at the Strophe.LogLevel.DEBUG level.
   *
   *  Parameters:
   *    (String) msg - The log message.
   */
  debug(msg) {
    this.log(this.LogLevel.DEBUG, msg);
  },

  /** Function: info
   *  Log a message at the Strophe.LogLevel.INFO level.
   *
   *  Parameters:
   *    (String) msg - The log message.
   */
  info(msg) {
    this.log(this.LogLevel.INFO, msg);
  },

  /** Function: warn
   *  Log a message at the Strophe.LogLevel.WARN level.
   *
   *  Parameters:
   *    (String) msg - The log message.
   */
  warn(msg) {
    this.log(this.LogLevel.WARN, msg);
  },

  /** Function: error
   *  Log a message at the Strophe.LogLevel.ERROR level.
   *
   *  Parameters:
   *    (String) msg - The log message.
   */
  error(msg) {
    this.log(this.LogLevel.ERROR, msg);
  },

  /** Function: fatal
   *  Log a message at the Strophe.LogLevel.FATAL level.
   *
   *  Parameters:
   *    (String) msg - The log message.
   */
  fatal(msg) {
    this.log(this.LogLevel.FATAL, msg);
  },

  /** Function: serialize
   *  Render a DOM element and all descendants to a String.
   *
   *  Parameters:
   *    (XMLElement) elem - A DOM element.
   *
   *  Returns:
   *    The serialized element tree as a String.
   */
  serialize(elem) {
    if (!elem) {
      return null;
    }

    if (typeof elem.tree === "function") {
      elem = elem.tree();
    }

    const names = [...Array(elem.attributes.length).keys()].map(i => elem.attributes[i].nodeName);
    names.sort();
    let result = names.reduce((a, n) => `${a} ${n}="${Strophe.xmlescape(elem.attributes.getNamedItem(n).value)}"`, `<${elem.nodeName}`);

    if (elem.childNodes.length > 0) {
      result += ">";

      for (let i = 0; i < elem.childNodes.length; i++) {
        const child = elem.childNodes[i];

        switch (child.nodeType) {
          case Strophe.ElementType.NORMAL:
            // normal element, so recurse
            result += Strophe.serialize(child);
            break;

          case Strophe.ElementType.TEXT:
            // text element to escape values
            result += Strophe.xmlescape(child.nodeValue);
            break;

          case Strophe.ElementType.CDATA:
            // cdata section so don't escape values
            result += "<![CDATA[" + child.nodeValue + "]]>";
        }
      }

      result += "</" + elem.nodeName + ">";
    } else {
      result += "/>";
    }

    return result;
  },

  /** PrivateVariable: _requestId
   *  _Private_ variable that keeps track of the request ids for
   *  connections.
   */
  _requestId: 0,

  /** PrivateVariable: Strophe.connectionPlugins
   *  _Private_ variable Used to store plugin names that need
   *  initialization on Strophe.Connection construction.
   */
  _connectionPlugins: {},

  /** Function: addConnectionPlugin
   *  Extends the Strophe.Connection object with the given plugin.
   *
   *  Parameters:
   *    (String) name - The name of the extension.
   *    (Object) ptype - The plugin's prototype.
   */
  addConnectionPlugin(name, ptype) {
    Strophe._connectionPlugins[name] = ptype;
  }

};
/** Class: Strophe.Builder
 *  XML DOM builder.
 *
 *  This object provides an interface similar to JQuery but for building
 *  DOM elements easily and rapidly.  All the functions except for toString()
 *  and tree() return the object, so calls can be chained.  Here's an
 *  example using the $iq() builder helper.
 *  > $iq({to: 'you', from: 'me', type: 'get', id: '1'})
 *  >     .c('query', {xmlns: 'strophe:example'})
 *  >     .c('example')
 *  >     .toString()
 *
 *  The above generates this XML fragment
 *  > <iq to='you' from='me' type='get' id='1'>
 *  >   <query xmlns='strophe:example'>
 *  >     <example/>
 *  >   </query>
 *  > </iq>
 *  The corresponding DOM manipulations to get a similar fragment would be
 *  a lot more tedious and probably involve several helper variables.
 *
 *  Since adding children makes new operations operate on the child, up()
 *  is provided to traverse up the tree.  To add two children, do
 *  > builder.c('child1', ...).up().c('child2', ...)
 *  The next operation on the Builder will be relative to the second child.
 */

/** Constructor: Strophe.Builder
 *  Create a Strophe.Builder object.
 *
 *  The attributes should be passed in object notation.  For example
 *  > let b = new Builder('message', {to: 'you', from: 'me'});
 *  or
 *  > let b = new Builder('messsage', {'xml:lang': 'en'});
 *
 *  Parameters:
 *    (String) name - The name of the root element.
 *    (Object) attrs - The attributes for the root element in object notation.
 *
 *  Returns:
 *    A new Strophe.Builder.
 */

Strophe.Builder = class Builder {
  constructor(name, attrs) {
    // Set correct namespace for jabber:client elements
    if (name === "presence" || name === "message" || name === "iq") {
      if (attrs && !attrs.xmlns) {
        attrs.xmlns = Strophe.NS.CLIENT;
      } else if (!attrs) {
        attrs = {
          xmlns: Strophe.NS.CLIENT
        };
      }
    } // Holds the tree being built.


    this.nodeTree = Strophe.xmlElement(name, attrs); // Points to the current operation node.

    this.node = this.nodeTree;
  }
  /** Function: tree
   *  Return the DOM tree.
   *
   *  This function returns the current DOM tree as an element object.  This
   *  is suitable for passing to functions like Strophe.Connection.send().
   *
   *  Returns:
   *    The DOM tree as a element object.
   */


  tree() {
    return this.nodeTree;
  }
  /** Function: toString
   *  Serialize the DOM tree to a String.
   *
   *  This function returns a string serialization of the current DOM
   *  tree.  It is often used internally to pass data to a
   *  Strophe.Request object.
   *
   *  Returns:
   *    The serialized DOM tree in a String.
   */


  toString() {
    return Strophe.serialize(this.nodeTree);
  }
  /** Function: up
   *  Make the current parent element the new current element.
   *
   *  This function is often used after c() to traverse back up the tree.
   *  For example, to add two children to the same element
   *  > builder.c('child1', {}).up().c('child2', {});
   *
   *  Returns:
   *    The Stophe.Builder object.
   */


  up() {
    this.node = this.node.parentNode;
    return this;
  }
  /** Function: root
   *  Make the root element the new current element.
   *
   *  When at a deeply nested element in the tree, this function can be used
   *  to jump back to the root of the tree, instead of having to repeatedly
   *  call up().
   *
   *  Returns:
   *    The Stophe.Builder object.
   */


  root() {
    this.node = this.nodeTree;
    return this;
  }
  /** Function: attrs
   *  Add or modify attributes of the current element.
   *
   *  The attributes should be passed in object notation.  This function
   *  does not move the current element pointer.
   *
   *  Parameters:
   *    (Object) moreattrs - The attributes to add/modify in object notation.
   *
   *  Returns:
   *    The Strophe.Builder object.
   */


  attrs(moreattrs) {
    for (const k in moreattrs) {
      if (Object.prototype.hasOwnProperty.call(moreattrs, k)) {
        if (moreattrs[k] === undefined) {
          this.node.removeAttribute(k);
        } else {
          this.node.setAttribute(k, moreattrs[k]);
        }
      }
    }

    return this;
  }
  /** Function: c
   *  Add a child to the current element and make it the new current
   *  element.
   *
   *  This function moves the current element pointer to the child,
   *  unless text is provided.  If you need to add another child, it
   *  is necessary to use up() to go back to the parent in the tree.
   *
   *  Parameters:
   *    (String) name - The name of the child.
   *    (Object) attrs - The attributes of the child in object notation.
   *    (String) text - The text to add to the child.
   *
   *  Returns:
   *    The Strophe.Builder object.
   */


  c(name, attrs, text) {
    const child = Strophe.xmlElement(name, attrs, text);
    this.node.appendChild(child);

    if (typeof text !== "string" && typeof text !== "number") {
      this.node = child;
    }

    return this;
  }
  /** Function: cnode
   *  Add a child to the current element and make it the new current
   *  element.
   *
   *  This function is the same as c() except that instead of using a
   *  name and an attributes object to create the child it uses an
   *  existing DOM element object.
   *
   *  Parameters:
   *    (XMLElement) elem - A DOM element.
   *
   *  Returns:
   *    The Strophe.Builder object.
   */


  cnode(elem) {
    let impNode;
    const xmlGen = Strophe.xmlGenerator();

    try {
      impNode = xmlGen.importNode !== undefined;
    } catch (e) {
      impNode = false;
    }

    const newElem = impNode ? xmlGen.importNode(elem, true) : Strophe.copyElement(elem);
    this.node.appendChild(newElem);
    this.node = newElem;
    return this;
  }
  /** Function: t
   *  Add a child text element.
   *
   *  This *does not* make the child the new current element since there
   *  are no children of text elements.
   *
   *  Parameters:
   *    (String) text - The text data to append to the current element.
   *
   *  Returns:
   *    The Strophe.Builder object.
   */


  t(text) {
    const child = Strophe.xmlTextNode(text);
    this.node.appendChild(child);
    return this;
  }
  /** Function: h
   *  Replace current element contents with the HTML passed in.
   *
   *  This *does not* make the child the new current element
   *
   *  Parameters:
   *    (String) html - The html to insert as contents of current element.
   *
   *  Returns:
   *    The Strophe.Builder object.
   */


  h(html) {
    const fragment = Strophe.xmlGenerator().createElement('body'); // force the browser to try and fix any invalid HTML tags

    fragment.innerHTML = html; // copy cleaned html into an xml dom

    const xhtml = Strophe.createHtml(fragment);

    while (xhtml.childNodes.length > 0) {
      this.node.appendChild(xhtml.childNodes[0]);
    }

    return this;
  }

};
/** PrivateClass: Strophe.Handler
 *  _Private_ helper class for managing stanza handlers.
 *
 *  A Strophe.Handler encapsulates a user provided callback function to be
 *  executed when matching stanzas are received by the connection.
 *  Handlers can be either one-off or persistant depending on their
 *  return value. Returning true will cause a Handler to remain active, and
 *  returning false will remove the Handler.
 *
 *  Users will not use Strophe.Handler objects directly, but instead they
 *  will use Strophe.Connection.addHandler() and
 *  Strophe.Connection.deleteHandler().
 */

/** PrivateConstructor: Strophe.Handler
 *  Create and initialize a new Strophe.Handler.
 *
 *  Parameters:
 *    (Function) handler - A function to be executed when the handler is run.
 *    (String) ns - The namespace to match.
 *    (String) name - The element name to match.
 *    (String) type - The element type to match.
 *    (String) id - The element id attribute to match.
 *    (String) from - The element from attribute to match.
 *    (Object) options - Handler options
 *
 *  Returns:
 *    A new Strophe.Handler object.
 */

Strophe.Handler = function (handler, ns, name, type, id, from, options) {
  this.handler = handler;
  this.ns = ns;
  this.name = name;
  this.type = type;
  this.id = id;
  this.options = options || {
    'matchBareFromJid': false,
    'ignoreNamespaceFragment': false
  }; // BBB: Maintain backward compatibility with old `matchBare` option

  if (this.options.matchBare) {
    Strophe.warn('The "matchBare" option is deprecated, use "matchBareFromJid" instead.');
    this.options.matchBareFromJid = this.options.matchBare;
    delete this.options.matchBare;
  }

  if (this.options.matchBareFromJid) {
    this.from = from ? Strophe.getBareJidFromJid(from) : null;
  } else {
    this.from = from;
  } // whether the handler is a user handler or a system handler


  this.user = true;
};

Strophe.Handler.prototype = {
  /** PrivateFunction: getNamespace
   *  Returns the XML namespace attribute on an element.
   *  If `ignoreNamespaceFragment` was passed in for this handler, then the
   *  URL fragment will be stripped.
   *
   *  Parameters:
   *    (XMLElement) elem - The XML element with the namespace.
   *
   *  Returns:
   *    The namespace, with optionally the fragment stripped.
   */
  getNamespace(elem) {
    let elNamespace = elem.getAttribute("xmlns");

    if (elNamespace && this.options.ignoreNamespaceFragment) {
      elNamespace = elNamespace.split('#')[0];
    }

    return elNamespace;
  },

  /** PrivateFunction: namespaceMatch
   *  Tests if a stanza matches the namespace set for this Strophe.Handler.
   *
   *  Parameters:
   *    (XMLElement) elem - The XML element to test.
   *
   *  Returns:
   *    true if the stanza matches and false otherwise.
   */
  namespaceMatch(elem) {
    let nsMatch = false;

    if (!this.ns) {
      return true;
    } else {
      Strophe.forEachChild(elem, null, elem => {
        if (this.getNamespace(elem) === this.ns) {
          nsMatch = true;
        }
      });
      return nsMatch || this.getNamespace(elem) === this.ns;
    }
  },

  /** PrivateFunction: isMatch
   *  Tests if a stanza matches the Strophe.Handler.
   *
   *  Parameters:
   *    (XMLElement) elem - The XML element to test.
   *
   *  Returns:
   *    true if the stanza matches and false otherwise.
   */
  isMatch(elem) {
    let from = elem.getAttribute('from');

    if (this.options.matchBareFromJid) {
      from = Strophe.getBareJidFromJid(from);
    }

    const elem_type = elem.getAttribute("type");

    if (this.namespaceMatch(elem) && (!this.name || Strophe.isTagEqual(elem, this.name)) && (!this.type || (Array.isArray(this.type) ? this.type.indexOf(elem_type) !== -1 : elem_type === this.type)) && (!this.id || elem.getAttribute("id") === this.id) && (!this.from || from === this.from)) {
      return true;
    }

    return false;
  },

  /** PrivateFunction: run
   *  Run the callback on a matching stanza.
   *
   *  Parameters:
   *    (XMLElement) elem - The DOM element that triggered the
   *      Strophe.Handler.
   *
   *  Returns:
   *    A boolean indicating if the handler should remain active.
   */
  run(elem) {
    let result = null;

    try {
      result = this.handler(elem);
    } catch (e) {
      Strophe._handleError(e);

      throw e;
    }

    return result;
  },

  /** PrivateFunction: toString
   *  Get a String representation of the Strophe.Handler object.
   *
   *  Returns:
   *    A String.
   */
  toString() {
    return "{Handler: " + this.handler + "(" + this.name + "," + this.id + "," + this.ns + ")}";
  }

};
/** PrivateClass: Strophe.TimedHandler
 *  _Private_ helper class for managing timed handlers.
 *
 *  A Strophe.TimedHandler encapsulates a user provided callback that
 *  should be called after a certain period of time or at regular
 *  intervals.  The return value of the callback determines whether the
 *  Strophe.TimedHandler will continue to fire.
 *
 *  Users will not use Strophe.TimedHandler objects directly, but instead
 *  they will use Strophe.Connection.addTimedHandler() and
 *  Strophe.Connection.deleteTimedHandler().
 */

Strophe.TimedHandler = class TimedHandler {
  /** PrivateConstructor: Strophe.TimedHandler
   *  Create and initialize a new Strophe.TimedHandler object.
   *
   *  Parameters:
   *    (Integer) period - The number of milliseconds to wait before the
   *      handler is called.
   *    (Function) handler - The callback to run when the handler fires.  This
   *      function should take no arguments.
   *
   *  Returns:
   *    A new Strophe.TimedHandler object.
   */
  constructor(period, handler) {
    this.period = period;
    this.handler = handler;
    this.lastCalled = new Date().getTime();
    this.user = true;
  }
  /** PrivateFunction: run
   *  Run the callback for the Strophe.TimedHandler.
   *
   *  Returns:
   *    true if the Strophe.TimedHandler should be called again, and false
   *      otherwise.
   */


  run() {
    this.lastCalled = new Date().getTime();
    return this.handler();
  }
  /** PrivateFunction: reset
   *  Reset the last called time for the Strophe.TimedHandler.
   */


  reset() {
    this.lastCalled = new Date().getTime();
  }
  /** PrivateFunction: toString
   *  Get a string representation of the Strophe.TimedHandler object.
   *
   *  Returns:
   *    The string representation.
   */


  toString() {
    return "{TimedHandler: " + this.handler + "(" + this.period + ")}";
  }

};
/** Class: Strophe.Connection
 *  XMPP Connection manager.
 *
 *  This class is the main part of Strophe.  It manages a BOSH or websocket
 *  connection to an XMPP server and dispatches events to the user callbacks
 *  as data arrives. It supports SASL PLAIN, SASL SCRAM-SHA-1
 *  and legacy authentication.
 *
 *  After creating a Strophe.Connection object, the user will typically
 *  call connect() with a user supplied callback to handle connection level
 *  events like authentication failure, disconnection, or connection
 *  complete.
 *
 *  The user will also have several event handlers defined by using
 *  addHandler() and addTimedHandler().  These will allow the user code to
 *  respond to interesting stanzas or do something periodically with the
 *  connection. These handlers will be active once authentication is
 *  finished.
 *
 *  To send data to the connection, use send().
 */

/** Constructor: Strophe.Connection
 *  Create and initialize a Strophe.Connection object.
 *
 *  The transport-protocol for this connection will be chosen automatically
 *  based on the given service parameter. URLs starting with "ws://" or
 *  "wss://" will use WebSockets, URLs starting with "http://", "https://"
 *  or without a protocol will use BOSH.
 *
 *  To make Strophe connect to the current host you can leave out the protocol
 *  and host part and just pass the path, e.g.
 *
 *  > let conn = new Strophe.Connection("/http-bind/");
 *
 *  Options common to both Websocket and BOSH:
 *  ------------------------------------------
 *
 *  cookies:
 *
 *  The *cookies* option allows you to pass in cookies to be added to the
 *  document. These cookies will then be included in the BOSH XMLHttpRequest
 *  or in the websocket connection.
 *
 *  The passed in value must be a map of cookie names and string values.
 *
 *  > { "myCookie": {
 *  >     "value": "1234",
 *  >     "domain": ".example.org",
 *  >     "path": "/",
 *  >     "expires": expirationDate
 *  >     }
 *  > }
 *
 *  Note that cookies can't be set in this way for other domains (i.e. cross-domain).
 *  Those cookies need to be set under those domains, for example they can be
 *  set server-side by making a XHR call to that domain to ask it to set any
 *  necessary cookies.
 *
 *  mechanisms:
 *
 *  The *mechanisms* option allows you to specify the SASL mechanisms that this
 *  instance of Strophe.Connection (and therefore your XMPP client) will
 *  support.
 *
 *  The value must be an array of objects with Strophe.SASLMechanism
 *  prototypes.
 *
 *  If nothing is specified, then the following mechanisms (and their
 *  priorities) are registered:
 *
 *      SCRAM-SHA-1 - 60
 *      PLAIN       - 50
 *      OAUTHBEARER - 40
 *      X-OAUTH2    - 30
 *      ANONYMOUS   - 20
 *      EXTERNAL    - 10
 *
 *  explicitResourceBinding:
 *
 *  If `explicitResourceBinding` is set to a truthy value, then the XMPP client
 *  needs to explicitly call `Strophe.Connection.prototype.bind` once the XMPP
 *  server has advertised the "urn:ietf:params:xml:ns:xmpp-bind" feature.
 *
 *  Making this step explicit allows client authors to first finish other
 *  stream related tasks, such as setting up an XEP-0198 Stream Management
 *  session, before binding the JID resource for this session.
 *
 *  WebSocket options:
 *  ------------------
 *
 *  protocol:
 *
 *  If you want to connect to the current host with a WebSocket connection you
 *  can tell Strophe to use WebSockets through a "protocol" attribute in the
 *  optional options parameter. Valid values are "ws" for WebSocket and "wss"
 *  for Secure WebSocket.
 *  So to connect to "wss://CURRENT_HOSTNAME/xmpp-websocket" you would call
 *
 *  > let conn = new Strophe.Connection("/xmpp-websocket/", {protocol: "wss"});
 *
 *  Note that relative URLs _NOT_ starting with a "/" will also include the path
 *  of the current site.
 *
 *  Also because downgrading security is not permitted by browsers, when using
 *  relative URLs both BOSH and WebSocket connections will use their secure
 *  variants if the current connection to the site is also secure (https).
 *
 *  worker:
 *
 *  Set this option to URL from where the shared worker script should be loaded.
 *
 *  To run the websocket connection inside a shared worker.
 *  This allows you to share a single websocket-based connection between
 *  multiple Strophe.Connection instances, for example one per browser tab.
 *
 *  The script to use is the one in `src/shared-connection-worker.js`.
 *
 *  BOSH options:
 *  -------------
 *
 *  By adding "sync" to the options, you can control if requests will
 *  be made synchronously or not. The default behaviour is asynchronous.
 *  If you want to make requests synchronous, make "sync" evaluate to true.
 *  > let conn = new Strophe.Connection("/http-bind/", {sync: true});
 *
 *  You can also toggle this on an already established connection.
 *  > conn.options.sync = true;
 *
 *  The *customHeaders* option can be used to provide custom HTTP headers to be
 *  included in the XMLHttpRequests made.
 *
 *  The *keepalive* option can be used to instruct Strophe to maintain the
 *  current BOSH session across interruptions such as webpage reloads.
 *
 *  It will do this by caching the sessions tokens in sessionStorage, and when
 *  "restore" is called it will check whether there are cached tokens with
 *  which it can resume an existing session.
 *
 *  The *withCredentials* option should receive a Boolean value and is used to
 *  indicate wether cookies should be included in ajax requests (by default
 *  they're not).
 *  Set this value to true if you are connecting to a BOSH service
 *  and for some reason need to send cookies to it.
 *  In order for this to work cross-domain, the server must also enable
 *  credentials by setting the Access-Control-Allow-Credentials response header
 *  to "true". For most usecases however this setting should be false (which
 *  is the default).
 *  Additionally, when using Access-Control-Allow-Credentials, the
 *  Access-Control-Allow-Origin header can't be set to the wildcard "*", but
 *  instead must be restricted to actual domains.
 *
 *  The *contentType* option can be set to change the default Content-Type
 *  of "text/xml; charset=utf-8", which can be useful to reduce the amount of
 *  CORS preflight requests that are sent to the server.
 *
 *  Parameters:
 *    (String) service - The BOSH or WebSocket service URL.
 *    (Object) options - A hash of configuration options
 *
 *  Returns:
 *    A new Strophe.Connection object.
 */

Strophe.Connection = class Connection {
  constructor(service, options) {
    // The service URL
    this.service = service; // Configuration options

    this.options = options || {};
    this.setProtocol();
    /* The connected JID. */

    this.jid = "";
    /* the JIDs domain */

    this.domain = null;
    /* stream:features */

    this.features = null; // SASL

    this._sasl_data = {};
    this.do_bind = false;
    this.do_session = false;
    this.mechanisms = {}; // handler lists

    this.timedHandlers = [];
    this.handlers = [];
    this.removeTimeds = [];
    this.removeHandlers = [];
    this.addTimeds = [];
    this.addHandlers = [];
    this.protocolErrorHandlers = {
      'HTTP': {},
      'websocket': {}
    };
    this._idleTimeout = null;
    this._disconnectTimeout = null;
    this.authenticated = false;
    this.connected = false;
    this.disconnecting = false;
    this.do_authentication = true;
    this.paused = false;
    this.restored = false;
    this._data = [];
    this._uniqueId = 0;
    this._sasl_success_handler = null;
    this._sasl_failure_handler = null;
    this._sasl_challenge_handler = null; // Max retries before disconnecting

    this.maxRetries = 5; // Call onIdle callback every 1/10th of a second

    this._idleTimeout = setTimeout(() => this._onIdle(), 100);
    utils.addCookies(this.options.cookies);
    this.registerSASLMechanisms(this.options.mechanisms); // initialize plugins

    for (const k in Strophe._connectionPlugins) {
      if (Object.prototype.hasOwnProperty.call(Strophe._connectionPlugins, k)) {
        const F = function () {};

        F.prototype = Strophe._connectionPlugins[k];
        this[k] = new F();
        this[k].init(this);
      }
    }
  }
  /** Function: setProtocol
   *  Select protocal based on this.options or this.service
   */


  setProtocol() {
    const proto = this.options.protocol || "";

    if (this.options.worker) {
      this._proto = new Strophe.WorkerWebsocket(this);
    } else if (this.service.indexOf("ws:") === 0 || this.service.indexOf("wss:") === 0 || proto.indexOf("ws") === 0) {
      this._proto = new Strophe.Websocket(this);
    } else {
      this._proto = new Strophe.Bosh(this);
    }
  }
  /** Function: reset
   *  Reset the connection.
   *
   *  This function should be called after a connection is disconnected
   *  before that connection is reused.
   */


  reset() {
    this._proto._reset(); // SASL


    this.do_session = false;
    this.do_bind = false; // handler lists

    this.timedHandlers = [];
    this.handlers = [];
    this.removeTimeds = [];
    this.removeHandlers = [];
    this.addTimeds = [];
    this.addHandlers = [];
    this.authenticated = false;
    this.connected = false;
    this.disconnecting = false;
    this.restored = false;
    this._data = [];
    this._requests = [];
    this._uniqueId = 0;
  }
  /** Function: pause
   *  Pause the request manager.
   *
   *  This will prevent Strophe from sending any more requests to the
   *  server.  This is very useful for temporarily pausing
   *  BOSH-Connections while a lot of send() calls are happening quickly.
   *  This causes Strophe to send the data in a single request, saving
   *  many request trips.
   */


  pause() {
    this.paused = true;
  }
  /** Function: resume
   *  Resume the request manager.
   *
   *  This resumes after pause() has been called.
   */


  resume() {
    this.paused = false;
  }
  /** Function: getUniqueId
   *  Generate a unique ID for use in <iq/> elements.
   *
   *  All <iq/> stanzas are required to have unique id attributes.  This
   *  function makes creating these easy.  Each connection instance has
   *  a counter which starts from zero, and the value of this counter
   *  plus a colon followed by the suffix becomes the unique id. If no
   *  suffix is supplied, the counter is used as the unique id.
   *
   *  Suffixes are used to make debugging easier when reading the stream
   *  data, and their use is recommended.  The counter resets to 0 for
   *  every new connection for the same reason.  For connections to the
   *  same server that authenticate the same way, all the ids should be
   *  the same, which makes it easy to see changes.  This is useful for
   *  automated testing as well.
   *
   *  Parameters:
   *    (String) suffix - A optional suffix to append to the id.
   *
   *  Returns:
   *    A unique string to be used for the id attribute.
   */


  getUniqueId(suffix) {
    // eslint-disable-line class-methods-use-this
    const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      const r = Math.random() * 16 | 0,
            v = c === 'x' ? r : r & 0x3 | 0x8;
      return v.toString(16);
    });

    if (typeof suffix === "string" || typeof suffix === "number") {
      return uuid + ":" + suffix;
    } else {
      return uuid + "";
    }
  }
  /** Function: addProtocolErrorHandler
   *  Register a handler function for when a protocol (websocker or HTTP)
   *  error occurs.
   *
   *  NOTE: Currently only HTTP errors for BOSH requests are handled.
   *  Patches that handle websocket errors would be very welcome.
   *
   *  Parameters:
   *    (String) protocol - 'HTTP' or 'websocket'
   *    (Integer) status_code - Error status code (e.g 500, 400 or 404)
   *    (Function) callback - Function that will fire on Http error
   *
   *  Example:
   *  function onError(err_code){
   *    //do stuff
   *  }
   *
   *  let conn = Strophe.connect('http://example.com/http-bind');
   *  conn.addProtocolErrorHandler('HTTP', 500, onError);
   *  // Triggers HTTP 500 error and onError handler will be called
   *  conn.connect('user_jid@incorrect_jabber_host', 'secret', onConnect);
   */


  addProtocolErrorHandler(protocol, status_code, callback) {
    this.protocolErrorHandlers[protocol][status_code] = callback;
  }
  /** Function: connect
   *  Starts the connection process.
   *
   *  As the connection process proceeds, the user supplied callback will
   *  be triggered multiple times with status updates.  The callback
   *  should take two arguments - the status code and the error condition.
   *
   *  The status code will be one of the values in the Strophe.Status
   *  constants.  The error condition will be one of the conditions
   *  defined in RFC 3920 or the condition 'strophe-parsererror'.
   *
   *  The Parameters _wait_, _hold_ and _route_ are optional and only relevant
   *  for BOSH connections. Please see XEP 124 for a more detailed explanation
   *  of the optional parameters.
   *
   *  Parameters:
   *    (String) jid - The user's JID.  This may be a bare JID,
   *      or a full JID.  If a node is not supplied, SASL OAUTHBEARER or
   *      SASL ANONYMOUS authentication will be attempted (OAUTHBEARER will
   *      process the provided password value as an access token).
   *    (String) pass - The user's password.
   *    (Function) callback - The connect callback function.
   *    (Integer) wait - The optional HTTPBIND wait value.  This is the
   *      time the server will wait before returning an empty result for
   *      a request.  The default setting of 60 seconds is recommended.
   *    (Integer) hold - The optional HTTPBIND hold value.  This is the
   *      number of connections the server will hold at one time.  This
   *      should almost always be set to 1 (the default).
   *    (String) route - The optional route value.
   *    (String) authcid - The optional alternative authentication identity
   *      (username) if intending to impersonate another user.
   *      When using the SASL-EXTERNAL authentication mechanism, for example
   *      with client certificates, then the authcid value is used to
   *      determine whether an authorization JID (authzid) should be sent to
   *      the server. The authzid should NOT be sent to the server if the
   *      authzid and authcid are the same. So to prevent it from being sent
   *      (for example when the JID is already contained in the client
   *      certificate), set authcid to that same JID. See XEP-178 for more
   *      details.
   */


  connect(jid, pass, callback, wait, hold, route, authcid) {
    this.jid = jid;
    /** Variable: authzid
     *  Authorization identity.
     */

    this.authzid = Strophe.getBareJidFromJid(this.jid);
    /** Variable: authcid
     *  Authentication identity (User name).
     */

    this.authcid = authcid || Strophe.getNodeFromJid(this.jid);
    /** Variable: pass
     *  Authentication identity (User password).
     */

    this.pass = pass;
    this.connect_callback = callback;
    this.disconnecting = false;
    this.connected = false;
    this.authenticated = false;
    this.restored = false; // parse jid for domain

    this.domain = Strophe.getDomainFromJid(this.jid);

    this._changeConnectStatus(Strophe.Status.CONNECTING, null);

    this._proto._connect(wait, hold, route);
  }
  /** Function: attach
   *  Attach to an already created and authenticated BOSH session.
   *
   *  This function is provided to allow Strophe to attach to BOSH
   *  sessions which have been created externally, perhaps by a Web
   *  application.  This is often used to support auto-login type features
   *  without putting user credentials into the page.
   *
   *  Parameters:
   *    (String) jid - The full JID that is bound by the session.
   *    (String) sid - The SID of the BOSH session.
   *    (String) rid - The current RID of the BOSH session.  This RID
   *      will be used by the next request.
   *    (Function) callback The connect callback function.
   *    (Integer) wait - The optional HTTPBIND wait value.  This is the
   *      time the server will wait before returning an empty result for
   *      a request.  The default setting of 60 seconds is recommended.
   *      Other settings will require tweaks to the Strophe.TIMEOUT value.
   *    (Integer) hold - The optional HTTPBIND hold value.  This is the
   *      number of connections the server will hold at one time.  This
   *      should almost always be set to 1 (the default).
   *    (Integer) wind - The optional HTTBIND window value.  This is the
   *      allowed range of request ids that are valid.  The default is 5.
   */


  attach(jid, sid, rid, callback, wait, hold, wind) {
    if (this._proto._attach) {
      return this._proto._attach(jid, sid, rid, callback, wait, hold, wind);
    } else {
      const error = new Error('The "attach" method is not available for your connection protocol');
      error.name = 'StropheSessionError';
      throw error;
    }
  }
  /** Function: restore
   *  Attempt to restore a cached BOSH session.
   *
   *  This function is only useful in conjunction with providing the
   *  "keepalive":true option when instantiating a new Strophe.Connection.
   *
   *  When "keepalive" is set to true, Strophe will cache the BOSH tokens
   *  RID (Request ID) and SID (Session ID) and then when this function is
   *  called, it will attempt to restore the session from those cached
   *  tokens.
   *
   *  This function must therefore be called instead of connect or attach.
   *
   *  For an example on how to use it, please see examples/restore.js
   *
   *  Parameters:
   *    (String) jid - The user's JID.  This may be a bare JID or a full JID.
   *    (Function) callback - The connect callback function.
   *    (Integer) wait - The optional HTTPBIND wait value.  This is the
   *      time the server will wait before returning an empty result for
   *      a request.  The default setting of 60 seconds is recommended.
   *    (Integer) hold - The optional HTTPBIND hold value.  This is the
   *      number of connections the server will hold at one time.  This
   *      should almost always be set to 1 (the default).
   *    (Integer) wind - The optional HTTBIND window value.  This is the
   *      allowed range of request ids that are valid.  The default is 5.
   */


  restore(jid, callback, wait, hold, wind) {
    if (this._sessionCachingSupported()) {
      this._proto._restore(jid, callback, wait, hold, wind);
    } else {
      const error = new Error('The "restore" method can only be used with a BOSH connection.');
      error.name = 'StropheSessionError';
      throw error;
    }
  }
  /** PrivateFunction: _sessionCachingSupported
   * Checks whether sessionStorage and JSON are supported and whether we're
   * using BOSH.
   */


  _sessionCachingSupported() {
    if (this._proto instanceof Strophe.Bosh) {
      if (!JSON) {
        return false;
      }

      try {
        sessionStorage.setItem('_strophe_', '_strophe_');
        sessionStorage.removeItem('_strophe_');
      } catch (e) {
        return false;
      }

      return true;
    }

    return false;
  }
  /** Function: xmlInput
   *  User overrideable function that receives XML data coming into the
   *  connection.
   *
   *  The default function does nothing.  User code can override this with
   *  > Strophe.Connection.xmlInput = function (elem) {
   *  >   (user code)
   *  > };
   *
   *  Due to limitations of current Browsers' XML-Parsers the opening and closing
   *  <stream> tag for WebSocket-Connoctions will be passed as selfclosing here.
   *
   *  BOSH-Connections will have all stanzas wrapped in a <body> tag. See
   *  <Strophe.Bosh.strip> if you want to strip this tag.
   *
   *  Parameters:
   *    (XMLElement) elem - The XML data received by the connection.
   */


  xmlInput(elem) {
    // eslint-disable-line
    return;
  }
  /** Function: xmlOutput
   *  User overrideable function that receives XML data sent to the
   *  connection.
   *
   *  The default function does nothing.  User code can override this with
   *  > Strophe.Connection.xmlOutput = function (elem) {
   *  >   (user code)
   *  > };
   *
   *  Due to limitations of current Browsers' XML-Parsers the opening and closing
   *  <stream> tag for WebSocket-Connoctions will be passed as selfclosing here.
   *
   *  BOSH-Connections will have all stanzas wrapped in a <body> tag. See
   *  <Strophe.Bosh.strip> if you want to strip this tag.
   *
   *  Parameters:
   *    (XMLElement) elem - The XMLdata sent by the connection.
   */


  xmlOutput(elem) {
    // eslint-disable-line
    return;
  }
  /** Function: rawInput
   *  User overrideable function that receives raw data coming into the
   *  connection.
   *
   *  The default function does nothing.  User code can override this with
   *  > Strophe.Connection.rawInput = function (data) {
   *  >   (user code)
   *  > };
   *
   *  Parameters:
   *    (String) data - The data received by the connection.
   */


  rawInput(data) {
    // eslint-disable-line
    return;
  }
  /** Function: rawOutput
   *  User overrideable function that receives raw data sent to the
   *  connection.
   *
   *  The default function does nothing.  User code can override this with
   *  > Strophe.Connection.rawOutput = function (data) {
   *  >   (user code)
   *  > };
   *
   *  Parameters:
   *    (String) data - The data sent by the connection.
   */


  rawOutput(data) {
    // eslint-disable-line
    return;
  }
  /** Function: nextValidRid
   *  User overrideable function that receives the new valid rid.
   *
   *  The default function does nothing. User code can override this with
   *  > Strophe.Connection.nextValidRid = function (rid) {
   *  >    (user code)
   *  > };
   *
   *  Parameters:
   *    (Number) rid - The next valid rid
   */


  nextValidRid(rid) {
    // eslint-disable-line
    return;
  }
  /** Function: send
   *  Send a stanza.
   *
   *  This function is called to push data onto the send queue to
   *  go out over the wire.  Whenever a request is sent to the BOSH
   *  server, all pending data is sent and the queue is flushed.
   *
   *  Parameters:
   *    (XMLElement |
   *     [XMLElement] |
   *     Strophe.Builder) elem - The stanza to send.
   */


  send(elem) {
    if (elem === null) {
      return;
    }

    if (typeof elem.sort === "function") {
      for (let i = 0; i < elem.length; i++) {
        this._queueData(elem[i]);
      }
    } else if (typeof elem.tree === "function") {
      this._queueData(elem.tree());
    } else {
      this._queueData(elem);
    }

    this._proto._send();
  }
  /** Function: flush
   *  Immediately send any pending outgoing data.
   *
   *  Normally send() queues outgoing data until the next idle period
   *  (100ms), which optimizes network use in the common cases when
   *  several send()s are called in succession. flush() can be used to
   *  immediately send all pending data.
   */


  flush() {
    // cancel the pending idle period and run the idle function
    // immediately
    clearTimeout(this._idleTimeout);

    this._onIdle();
  }
  /** Function: sendPresence
   *  Helper function to send presence stanzas. The main benefit is for
   *  sending presence stanzas for which you expect a responding presence
   *  stanza with the same id (for example when leaving a chat room).
   *
   *  Parameters:
   *    (XMLElement) elem - The stanza to send.
   *    (Function) callback - The callback function for a successful request.
   *    (Function) errback - The callback function for a failed or timed
   *      out request.  On timeout, the stanza will be null.
   *    (Integer) timeout - The time specified in milliseconds for a
   *      timeout to occur.
   *
   *  Returns:
   *    The id used to send the presence.
   */


  sendPresence(elem, callback, errback, timeout) {
    let timeoutHandler = null;

    if (typeof elem.tree === "function") {
      elem = elem.tree();
    }

    let id = elem.getAttribute('id');

    if (!id) {
      // inject id if not found
      id = this.getUniqueId("sendPresence");
      elem.setAttribute("id", id);
    }

    if (typeof callback === "function" || typeof errback === "function") {
      const handler = this.addHandler(stanza => {
        // remove timeout handler if there is one
        if (timeoutHandler) {
          this.deleteTimedHandler(timeoutHandler);
        }

        if (stanza.getAttribute('type') === 'error') {
          if (errback) {
            errback(stanza);
          }
        } else if (callback) {
          callback(stanza);
        }
      }, null, 'presence', null, id); // if timeout specified, set up a timeout handler.

      if (timeout) {
        timeoutHandler = this.addTimedHandler(timeout, () => {
          // get rid of normal handler
          this.deleteHandler(handler); // call errback on timeout with null stanza

          if (errback) {
            errback(null);
          }

          return false;
        });
      }
    }

    this.send(elem);
    return id;
  }
  /** Function: sendIQ
   *  Helper function to send IQ stanzas.
   *
   *  Parameters:
   *    (XMLElement) elem - The stanza to send.
   *    (Function) callback - The callback function for a successful request.
   *    (Function) errback - The callback function for a failed or timed
   *      out request.  On timeout, the stanza will be null.
   *    (Integer) timeout - The time specified in milliseconds for a
   *      timeout to occur.
   *
   *  Returns:
   *    The id used to send the IQ.
  */


  sendIQ(elem, callback, errback, timeout) {
    let timeoutHandler = null;

    if (typeof elem.tree === "function") {
      elem = elem.tree();
    }

    let id = elem.getAttribute('id');

    if (!id) {
      // inject id if not found
      id = this.getUniqueId("sendIQ");
      elem.setAttribute("id", id);
    }

    if (typeof callback === "function" || typeof errback === "function") {
      const handler = this.addHandler(stanza => {
        // remove timeout handler if there is one
        if (timeoutHandler) {
          this.deleteTimedHandler(timeoutHandler);
        }

        const iqtype = stanza.getAttribute('type');

        if (iqtype === 'result') {
          if (callback) {
            callback(stanza);
          }
        } else if (iqtype === 'error') {
          if (errback) {
            errback(stanza);
          }
        } else {
          const error = new Error(`Got bad IQ type of ${iqtype}`);
          error.name = "StropheError";
          throw error;
        }
      }, null, 'iq', ['error', 'result'], id); // if timeout specified, set up a timeout handler.

      if (timeout) {
        timeoutHandler = this.addTimedHandler(timeout, () => {
          // get rid of normal handler
          this.deleteHandler(handler); // call errback on timeout with null stanza

          if (errback) {
            errback(null);
          }

          return false;
        });
      }
    }

    this.send(elem);
    return id;
  }
  /** PrivateFunction: _queueData
   *  Queue outgoing data for later sending.  Also ensures that the data
   *  is a DOMElement.
   */


  _queueData(element) {
    if (element === null || !element.tagName || !element.childNodes) {
      const error = new Error("Cannot queue non-DOMElement.");
      error.name = "StropheError";
      throw error;
    }

    this._data.push(element);
  }
  /** PrivateFunction: _sendRestart
   *  Send an xmpp:restart stanza.
   */


  _sendRestart() {
    this._data.push("restart");

    this._proto._sendRestart();

    this._idleTimeout = setTimeout(() => this._onIdle(), 100);
  }
  /** Function: addTimedHandler
   *  Add a timed handler to the connection.
   *
   *  This function adds a timed handler.  The provided handler will
   *  be called every period milliseconds until it returns false,
   *  the connection is terminated, or the handler is removed.  Handlers
   *  that wish to continue being invoked should return true.
   *
   *  Because of method binding it is necessary to save the result of
   *  this function if you wish to remove a handler with
   *  deleteTimedHandler().
   *
   *  Note that user handlers are not active until authentication is
   *  successful.
   *
   *  Parameters:
   *    (Integer) period - The period of the handler.
   *    (Function) handler - The callback function.
   *
   *  Returns:
   *    A reference to the handler that can be used to remove it.
   */


  addTimedHandler(period, handler) {
    const thand = new Strophe.TimedHandler(period, handler);
    this.addTimeds.push(thand);
    return thand;
  }
  /** Function: deleteTimedHandler
   *  Delete a timed handler for a connection.
   *
   *  This function removes a timed handler from the connection.  The
   *  handRef parameter is *not* the function passed to addTimedHandler(),
   *  but is the reference returned from addTimedHandler().
   *
   *  Parameters:
   *    (Strophe.TimedHandler) handRef - The handler reference.
   */


  deleteTimedHandler(handRef) {
    // this must be done in the Idle loop so that we don't change
    // the handlers during iteration
    this.removeTimeds.push(handRef);
  }
  /** Function: addHandler
   *  Add a stanza handler for the connection.
   *
   *  This function adds a stanza handler to the connection.  The
   *  handler callback will be called for any stanza that matches
   *  the parameters.  Note that if multiple parameters are supplied,
   *  they must all match for the handler to be invoked.
   *
   *  The handler will receive the stanza that triggered it as its argument.
   *  *The handler should return true if it is to be invoked again;
   *  returning false will remove the handler after it returns.*
   *
   *  As a convenience, the ns parameters applies to the top level element
   *  and also any of its immediate children.  This is primarily to make
   *  matching /iq/query elements easy.
   *
   *  Options
   *  ~~~~~~~
   *  With the options argument, you can specify boolean flags that affect how
   *  matches are being done.
   *
   *  Currently two flags exist:
   *
   *  - matchBareFromJid:
   *      When set to true, the from parameter and the
   *      from attribute on the stanza will be matched as bare JIDs instead
   *      of full JIDs. To use this, pass {matchBareFromJid: true} as the
   *      value of options. The default value for matchBareFromJid is false.
   *
   *  - ignoreNamespaceFragment:
   *      When set to true, a fragment specified on the stanza's namespace
   *      URL will be ignored when it's matched with the one configured for
   *      the handler.
   *
   *      This means that if you register like this:
   *      >   connection.addHandler(
   *      >       handler,
   *      >       'http://jabber.org/protocol/muc',
   *      >       null, null, null, null,
   *      >       {'ignoreNamespaceFragment': true}
   *      >   );
   *
   *      Then a stanza with XML namespace of
   *      'http://jabber.org/protocol/muc#user' will also be matched. If
   *      'ignoreNamespaceFragment' is false, then only stanzas with
   *      'http://jabber.org/protocol/muc' will be matched.
   *
   *  Deleting the handler
   *  ~~~~~~~~~~~~~~~~~~~~
   *  The return value should be saved if you wish to remove the handler
   *  with deleteHandler().
   *
   *  Parameters:
   *    (Function) handler - The user callback.
   *    (String) ns - The namespace to match.
   *    (String) name - The stanza name to match.
   *    (String|Array) type - The stanza type (or types if an array) to match.
   *    (String) id - The stanza id attribute to match.
   *    (String) from - The stanza from attribute to match.
   *    (String) options - The handler options
   *
   *  Returns:
   *    A reference to the handler that can be used to remove it.
   */


  addHandler(handler, ns, name, type, id, from, options) {
    const hand = new Strophe.Handler(handler, ns, name, type, id, from, options);
    this.addHandlers.push(hand);
    return hand;
  }
  /** Function: deleteHandler
   *  Delete a stanza handler for a connection.
   *
   *  This function removes a stanza handler from the connection.  The
   *  handRef parameter is *not* the function passed to addHandler(),
   *  but is the reference returned from addHandler().
   *
   *  Parameters:
   *    (Strophe.Handler) handRef - The handler reference.
   */


  deleteHandler(handRef) {
    // this must be done in the Idle loop so that we don't change
    // the handlers during iteration
    this.removeHandlers.push(handRef); // If a handler is being deleted while it is being added,
    // prevent it from getting added

    const i = this.addHandlers.indexOf(handRef);

    if (i >= 0) {
      this.addHandlers.splice(i, 1);
    }
  }
  /** Function: registerSASLMechanisms
   *
   * Register the SASL mechanisms which will be supported by this instance of
   * Strophe.Connection (i.e. which this XMPP client will support).
   *
   *  Parameters:
   *    (Array) mechanisms - Array of objects with Strophe.SASLMechanism prototypes
   *
   */


  registerSASLMechanisms(mechanisms) {
    this.mechanisms = {};
    mechanisms = mechanisms || [Strophe.SASLAnonymous, Strophe.SASLExternal, Strophe.SASLOAuthBearer, Strophe.SASLXOAuth2, Strophe.SASLPlain, Strophe.SASLSHA1];
    mechanisms.forEach(m => this.registerSASLMechanism(m));
  }
  /** Function: registerSASLMechanism
   *
   * Register a single SASL mechanism, to be supported by this client.
   *
   *  Parameters:
   *    (Object) mechanism - Object with a Strophe.SASLMechanism prototype
   *
   */


  registerSASLMechanism(Mechanism) {
    const mechanism = new Mechanism();
    this.mechanisms[mechanism.mechname] = mechanism;
  }
  /** Function: disconnect
   *  Start the graceful disconnection process.
   *
   *  This function starts the disconnection process.  This process starts
   *  by sending unavailable presence and sending BOSH body of type
   *  terminate.  A timeout handler makes sure that disconnection happens
   *  even if the BOSH server does not respond.
   *  If the Connection object isn't connected, at least tries to abort all pending requests
   *  so the connection object won't generate successful requests (which were already opened).
   *
   *  The user supplied connection callback will be notified of the
   *  progress as this process happens.
   *
   *  Parameters:
   *    (String) reason - The reason the disconnect is occuring.
   */


  disconnect(reason) {
    this._changeConnectStatus(Strophe.Status.DISCONNECTING, reason);

    if (reason) {
      Strophe.warn("Disconnect was called because: " + reason);
    } else {
      Strophe.info("Disconnect was called");
    }

    if (this.connected) {
      let pres = false;
      this.disconnecting = true;

      if (this.authenticated) {
        pres = $pres({
          'xmlns': Strophe.NS.CLIENT,
          'type': 'unavailable'
        });
      } // setup timeout handler


      this._disconnectTimeout = this._addSysTimedHandler(3000, this._onDisconnectTimeout.bind(this));

      this._proto._disconnect(pres);
    } else {
      Strophe.warn("Disconnect was called before Strophe connected to the server");

      this._proto._abortAllRequests();

      this._doDisconnect();
    }
  }
  /** PrivateFunction: _changeConnectStatus
   *  _Private_ helper function that makes sure plugins and the user's
   *  callback are notified of connection status changes.
   *
   *  Parameters:
   *    (Integer) status - the new connection status, one of the values
   *      in Strophe.Status
   *    (String) condition - the error condition or null
   *    (XMLElement) elem - The triggering stanza.
   */


  _changeConnectStatus(status, condition, elem) {
    // notify all plugins listening for status changes
    for (const k in Strophe._connectionPlugins) {
      if (Object.prototype.hasOwnProperty.call(Strophe._connectionPlugins, k)) {
        const plugin = this[k];

        if (plugin.statusChanged) {
          try {
            plugin.statusChanged(status, condition);
          } catch (err) {
            Strophe.error(`${k} plugin caused an exception changing status: ${err}`);
          }
        }
      }
    } // notify the user's callback


    if (this.connect_callback) {
      try {
        this.connect_callback(status, condition, elem);
      } catch (e) {
        Strophe._handleError(e);

        Strophe.error(`User connection callback caused an exception: ${e}`);
      }
    }
  }
  /** PrivateFunction: _doDisconnect
   *  _Private_ function to disconnect.
   *
   *  This is the last piece of the disconnection logic.  This resets the
   *  connection and alerts the user's connection callback.
   */


  _doDisconnect(condition) {
    if (typeof this._idleTimeout === "number") {
      clearTimeout(this._idleTimeout);
    } // Cancel Disconnect Timeout


    if (this._disconnectTimeout !== null) {
      this.deleteTimedHandler(this._disconnectTimeout);
      this._disconnectTimeout = null;
    }

    Strophe.debug("_doDisconnect was called");

    this._proto._doDisconnect();

    this.authenticated = false;
    this.disconnecting = false;
    this.restored = false; // delete handlers

    this.handlers = [];
    this.timedHandlers = [];
    this.removeTimeds = [];
    this.removeHandlers = [];
    this.addTimeds = [];
    this.addHandlers = []; // tell the parent we disconnected

    this._changeConnectStatus(Strophe.Status.DISCONNECTED, condition);

    this.connected = false;
  }
  /** PrivateFunction: _dataRecv
   *  _Private_ handler to processes incoming data from the the connection.
   *
   *  Except for _connect_cb handling the initial connection request,
   *  this function handles the incoming data for all requests.  This
   *  function also fires stanza handlers that match each incoming
   *  stanza.
   *
   *  Parameters:
   *    (Strophe.Request) req - The request that has data ready.
   *    (string) req - The stanza a raw string (optiona).
   */


  _dataRecv(req, raw) {
    const elem = this._proto._reqToData(req);

    if (elem === null) {
      return;
    }

    if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
      if (elem.nodeName === this._proto.strip && elem.childNodes.length) {
        this.xmlInput(elem.childNodes[0]);
      } else {
        this.xmlInput(elem);
      }
    }

    if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
      if (raw) {
        this.rawInput(raw);
      } else {
        this.rawInput(Strophe.serialize(elem));
      }
    } // remove handlers scheduled for deletion


    while (this.removeHandlers.length > 0) {
      const hand = this.removeHandlers.pop();
      const i = this.handlers.indexOf(hand);

      if (i >= 0) {
        this.handlers.splice(i, 1);
      }
    } // add handlers scheduled for addition


    while (this.addHandlers.length > 0) {
      this.handlers.push(this.addHandlers.pop());
    } // handle graceful disconnect


    if (this.disconnecting && this._proto._emptyQueue()) {
      this._doDisconnect();

      return;
    }

    const type = elem.getAttribute("type");

    if (type !== null && type === "terminate") {
      // Don't process stanzas that come in after disconnect
      if (this.disconnecting) {
        return;
      } // an error occurred


      let cond = elem.getAttribute("condition");
      const conflict = elem.getElementsByTagName("conflict");

      if (cond !== null) {
        if (cond === "remote-stream-error" && conflict.length > 0) {
          cond = "conflict";
        }

        this._changeConnectStatus(Strophe.Status.CONNFAIL, cond);
      } else {
        this._changeConnectStatus(Strophe.Status.CONNFAIL, Strophe.ErrorCondition.UNKOWN_REASON);
      }

      this._doDisconnect(cond);

      return;
    } // send each incoming stanza through the handler chain


    Strophe.forEachChild(elem, null, child => {
      // process handlers
      const newList = this.handlers;
      this.handlers = [];

      for (let i = 0; i < newList.length; i++) {
        const hand = newList[i]; // encapsulate 'handler.run' not to lose the whole handler list if
        // one of the handlers throws an exception

        try {
          if (hand.isMatch(child) && (this.authenticated || !hand.user)) {
            if (hand.run(child)) {
              this.handlers.push(hand);
            }
          } else {
            this.handlers.push(hand);
          }
        } catch (e) {
          // if the handler throws an exception, we consider it as false
          Strophe.warn('Removing Strophe handlers due to uncaught exception: ' + e.message);
        }
      }
    });
  }
  /** PrivateFunction: _connect_cb
   *  _Private_ handler for initial connection request.
   *
   *  This handler is used to process the initial connection request
   *  response from the BOSH server. It is used to set up authentication
   *  handlers and start the authentication process.
   *
   *  SASL authentication will be attempted if available, otherwise
   *  the code will fall back to legacy authentication.
   *
   *  Parameters:
   *    (Strophe.Request) req - The current request.
   *    (Function) _callback - low level (xmpp) connect callback function.
   *      Useful for plugins with their own xmpp connect callback (when they
   *      want to do something special).
   */


  _connect_cb(req, _callback, raw) {
    Strophe.debug("_connect_cb was called");
    this.connected = true;
    let bodyWrap;

    try {
      bodyWrap = this._proto._reqToData(req);
    } catch (e) {
      if (e.name !== Strophe.ErrorCondition.BAD_FORMAT) {
        throw e;
      }

      this._changeConnectStatus(Strophe.Status.CONNFAIL, Strophe.ErrorCondition.BAD_FORMAT);

      this._doDisconnect(Strophe.ErrorCondition.BAD_FORMAT);
    }

    if (!bodyWrap) {
      return;
    }

    if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
      if (bodyWrap.nodeName === this._proto.strip && bodyWrap.childNodes.length) {
        this.xmlInput(bodyWrap.childNodes[0]);
      } else {
        this.xmlInput(bodyWrap);
      }
    }

    if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
      if (raw) {
        this.rawInput(raw);
      } else {
        this.rawInput(Strophe.serialize(bodyWrap));
      }
    }

    const conncheck = this._proto._connect_cb(bodyWrap);

    if (conncheck === Strophe.Status.CONNFAIL) {
      return;
    } // Check for the stream:features tag


    let hasFeatures;

    if (bodyWrap.getElementsByTagNameNS) {
      hasFeatures = bodyWrap.getElementsByTagNameNS(Strophe.NS.STREAM, "features").length > 0;
    } else {
      hasFeatures = bodyWrap.getElementsByTagName("stream:features").length > 0 || bodyWrap.getElementsByTagName("features").length > 0;
    }

    if (!hasFeatures) {
      this._proto._no_auth_received(_callback);

      return;
    }

    const matched = Array.from(bodyWrap.getElementsByTagName("mechanism")).map(m => this.mechanisms[m.textContent]).filter(m => m);

    if (matched.length === 0) {
      if (bodyWrap.getElementsByTagName("auth").length === 0) {
        // There are no matching SASL mechanisms and also no legacy
        // auth available.
        this._proto._no_auth_received(_callback);

        return;
      }
    }

    if (this.do_authentication !== false) {
      this.authenticate(matched);
    }
  }
  /** Function: sortMechanismsByPriority
   *
   *  Sorts an array of objects with prototype SASLMechanism according to
   *  their priorities.
   *
   *  Parameters:
   *    (Array) mechanisms - Array of SASL mechanisms.
   *
   */


  sortMechanismsByPriority(mechanisms) {
    // eslint-disable-line class-methods-use-this
    // Sorting mechanisms according to priority.
    for (let i = 0; i < mechanisms.length - 1; ++i) {
      let higher = i;

      for (let j = i + 1; j < mechanisms.length; ++j) {
        if (mechanisms[j].priority > mechanisms[higher].priority) {
          higher = j;
        }
      }

      if (higher !== i) {
        const swap = mechanisms[i];
        mechanisms[i] = mechanisms[higher];
        mechanisms[higher] = swap;
      }
    }

    return mechanisms;
  }
  /** Function: authenticate
   * Set up authentication
   *
   *  Continues the initial connection request by setting up authentication
   *  handlers and starting the authentication process.
   *
   *  SASL authentication will be attempted if available, otherwise
   *  the code will fall back to legacy authentication.
   *
   *  Parameters:
   *    (Array) matched - Array of SASL mechanisms supported.
   *
   */


  authenticate(matched) {
    if (!this._attemptSASLAuth(matched)) {
      this._attemptLegacyAuth();
    }
  }
  /** PrivateFunction: _attemptSASLAuth
   *
   *  Iterate through an array of SASL mechanisms and attempt authentication
   *  with the highest priority (enabled) mechanism.
   *
   *  Parameters:
   *    (Array) mechanisms - Array of SASL mechanisms.
   *
   *  Returns:
   *    (Boolean) mechanism_found - true or false, depending on whether a
   *          valid SASL mechanism was found with which authentication could be
   *          started.
   */


  _attemptSASLAuth(mechanisms) {
    mechanisms = this.sortMechanismsByPriority(mechanisms || []);
    let mechanism_found = false;

    for (let i = 0; i < mechanisms.length; ++i) {
      if (!mechanisms[i].test(this)) {
        continue;
      }

      this._sasl_success_handler = this._addSysHandler(this._sasl_success_cb.bind(this), null, "success", null, null);
      this._sasl_failure_handler = this._addSysHandler(this._sasl_failure_cb.bind(this), null, "failure", null, null);
      this._sasl_challenge_handler = this._addSysHandler(this._sasl_challenge_cb.bind(this), null, "challenge", null, null);
      this._sasl_mechanism = mechanisms[i];

      this._sasl_mechanism.onStart(this);

      const request_auth_exchange = $build("auth", {
        'xmlns': Strophe.NS.SASL,
        'mechanism': this._sasl_mechanism.mechname
      });

      if (this._sasl_mechanism.isClientFirst) {
        const response = this._sasl_mechanism.clientChallenge(this);

        request_auth_exchange.t(Object(abab["btoa"])(response));
      }

      this.send(request_auth_exchange.tree());
      mechanism_found = true;
      break;
    }

    return mechanism_found;
  }
  /** PrivateFunction: _sasl_challenge_cb
   *  _Private_ handler for the SASL challenge
   *
   */


  _sasl_challenge_cb(elem) {
    const challenge = Object(abab["atob"])(Strophe.getText(elem));

    const response = this._sasl_mechanism.onChallenge(this, challenge);

    const stanza = $build('response', {
      'xmlns': Strophe.NS.SASL
    });

    if (response !== "") {
      stanza.t(Object(abab["btoa"])(response));
    }

    this.send(stanza.tree());
    return true;
  }
  /** PrivateFunction: _attemptLegacyAuth
   *
   *  Attempt legacy (i.e. non-SASL) authentication.
   */


  _attemptLegacyAuth() {
    if (Strophe.getNodeFromJid(this.jid) === null) {
      // we don't have a node, which is required for non-anonymous
      // client connections
      this._changeConnectStatus(Strophe.Status.CONNFAIL, Strophe.ErrorCondition.MISSING_JID_NODE);

      this.disconnect(Strophe.ErrorCondition.MISSING_JID_NODE);
    } else {
      // Fall back to legacy authentication
      this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null);

      this._addSysHandler(this._onLegacyAuthIQResult.bind(this), null, null, null, "_auth_1");

      this.send($iq({
        'type': "get",
        'to': this.domain,
        'id': "_auth_1"
      }).c("query", {
        xmlns: Strophe.NS.AUTH
      }).c("username", {}).t(Strophe.getNodeFromJid(this.jid)).tree());
    }
  }
  /** PrivateFunction: _onLegacyAuthIQResult
   *  _Private_ handler for legacy authentication.
   *
   *  This handler is called in response to the initial <iq type='get'/>
   *  for legacy authentication.  It builds an authentication <iq/> and
   *  sends it, creating a handler (calling back to _auth2_cb()) to
   *  handle the result
   *
   *  Parameters:
   *    (XMLElement) elem - The stanza that triggered the callback.
   *
   *  Returns:
   *    false to remove the handler.
   */


  _onLegacyAuthIQResult(elem) {
    // eslint-disable-line no-unused-vars
    // build plaintext auth iq
    const iq = $iq({
      type: "set",
      id: "_auth_2"
    }).c('query', {
      xmlns: Strophe.NS.AUTH
    }).c('username', {}).t(Strophe.getNodeFromJid(this.jid)).up().c('password').t(this.pass);

    if (!Strophe.getResourceFromJid(this.jid)) {
      // since the user has not supplied a resource, we pick
      // a default one here.  unlike other auth methods, the server
      // cannot do this for us.
      this.jid = Strophe.getBareJidFromJid(this.jid) + '/strophe';
    }

    iq.up().c('resource', {}).t(Strophe.getResourceFromJid(this.jid));

    this._addSysHandler(this._auth2_cb.bind(this), null, null, null, "_auth_2");

    this.send(iq.tree());
    return false;
  }
  /** PrivateFunction: _sasl_success_cb
   *  _Private_ handler for succesful SASL authentication.
   *
   *  Parameters:
   *    (XMLElement) elem - The matching stanza.
   *
   *  Returns:
   *    false to remove the handler.
   */


  _sasl_success_cb(elem) {
    if (this._sasl_data["server-signature"]) {
      let serverSignature;
      const success = Object(abab["atob"])(Strophe.getText(elem));
      const attribMatch = /([a-z]+)=([^,]+)(,|$)/;
      const matches = success.match(attribMatch);

      if (matches[1] === "v") {
        serverSignature = matches[2];
      }

      if (serverSignature !== this._sasl_data["server-signature"]) {
        // remove old handlers
        this.deleteHandler(this._sasl_failure_handler);
        this._sasl_failure_handler = null;

        if (this._sasl_challenge_handler) {
          this.deleteHandler(this._sasl_challenge_handler);
          this._sasl_challenge_handler = null;
        }

        this._sasl_data = {};
        return this._sasl_failure_cb(null);
      }
    }

    Strophe.info("SASL authentication succeeded.");

    if (this._sasl_mechanism) {
      this._sasl_mechanism.onSuccess();
    } // remove old handlers


    this.deleteHandler(this._sasl_failure_handler);
    this._sasl_failure_handler = null;

    if (this._sasl_challenge_handler) {
      this.deleteHandler(this._sasl_challenge_handler);
      this._sasl_challenge_handler = null;
    }

    const streamfeature_handlers = [];

    const wrapper = (handlers, elem) => {
      while (handlers.length) {
        this.deleteHandler(handlers.pop());
      }

      this._onStreamFeaturesAfterSASL(elem);

      return false;
    };

    streamfeature_handlers.push(this._addSysHandler(elem => wrapper(streamfeature_handlers, elem), null, "stream:features", null, null));
    streamfeature_handlers.push(this._addSysHandler(elem => wrapper(streamfeature_handlers, elem), Strophe.NS.STREAM, "features", null, null)); // we must send an xmpp:restart now

    this._sendRestart();

    return false;
  }
  /** PrivateFunction: _onStreamFeaturesAfterSASL
   *  Parameters:
   *    (XMLElement) elem - The matching stanza.
   *
   *  Returns:
   *    false to remove the handler.
   */


  _onStreamFeaturesAfterSASL(elem) {
    // save stream:features for future usage
    this.features = elem;

    for (let i = 0; i < elem.childNodes.length; i++) {
      const child = elem.childNodes[i];

      if (child.nodeName === 'bind') {
        this.do_bind = true;
      }

      if (child.nodeName === 'session') {
        this.do_session = true;
      }
    }

    if (!this.do_bind) {
      this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);

      return false;
    } else if (!this.options.explicitResourceBinding) {
      this.bind();
    } else {
      this._changeConnectStatus(Strophe.Status.BINDREQUIRED, null);
    }

    return false;
  }
  /** Function: bind
   *
   *  Sends an IQ to the XMPP server to bind a JID resource for this session.
   *
   *  https://tools.ietf.org/html/rfc6120#section-7.5
   *
   *  If `explicitResourceBinding` was set to a truthy value in the options
   *  passed to the Strophe.Connection constructor, then this function needs
   *  to be called explicitly by the client author.
   *
   *  Otherwise it'll be called automatically as soon as the XMPP server
   *  advertises the "urn:ietf:params:xml:ns:xmpp-bind" stream feature.
   */


  bind() {
    if (!this.do_bind) {
      Strophe.log(Strophe.LogLevel.INFO, `Strophe.Connection.prototype.bind called but "do_bind" is false`);
      return;
    }

    this._addSysHandler(this._onResourceBindResultIQ.bind(this), null, null, null, "_bind_auth_2");

    const resource = Strophe.getResourceFromJid(this.jid);

    if (resource) {
      this.send($iq({
        type: "set",
        id: "_bind_auth_2"
      }).c('bind', {
        xmlns: Strophe.NS.BIND
      }).c('resource', {}).t(resource).tree());
    } else {
      this.send($iq({
        type: "set",
        id: "_bind_auth_2"
      }).c('bind', {
        xmlns: Strophe.NS.BIND
      }).tree());
    }
  }
  /** PrivateFunction: _onResourceBindIQ
   *  _Private_ handler for binding result and session start.
   *
   *  Parameters:
   *    (XMLElement) elem - The matching stanza.
   *
   *  Returns:
   *    false to remove the handler.
   */


  _onResourceBindResultIQ(elem) {
    if (elem.getAttribute("type") === "error") {
      Strophe.warn("Resource binding failed.");
      const conflict = elem.getElementsByTagName("conflict");
      let condition;

      if (conflict.length > 0) {
        condition = Strophe.ErrorCondition.CONFLICT;
      }

      this._changeConnectStatus(Strophe.Status.AUTHFAIL, condition, elem);

      return false;
    } // TODO - need to grab errors


    const bind = elem.getElementsByTagName("bind");

    if (bind.length > 0) {
      const jidNode = bind[0].getElementsByTagName("jid");

      if (jidNode.length > 0) {
        this.authenticated = true;
        this.jid = Strophe.getText(jidNode[0]);

        if (this.do_session) {
          this._establishSession();
        } else {
          this._changeConnectStatus(Strophe.Status.CONNECTED, null);
        }
      }
    } else {
      Strophe.warn("Resource binding failed.");

      this._changeConnectStatus(Strophe.Status.AUTHFAIL, null, elem);

      return false;
    }
  }
  /** PrivateFunction: _establishSession
   *  Send IQ request to establish a session with the XMPP server.
   *
   *  See https://xmpp.org/rfcs/rfc3921.html#session
   *
   *  Note: The protocol for session establishment has been determined as
   *  unnecessary and removed in RFC-6121.
   */


  _establishSession() {
    if (!this.do_session) {
      throw new Error(`Strophe.Connection.prototype._establishSession ` + `called but apparently ${Strophe.NS.SESSION} wasn't advertised by the server`);
    }

    this._addSysHandler(this._onSessionResultIQ.bind(this), null, null, null, "_session_auth_2");

    this.send($iq({
      type: "set",
      id: "_session_auth_2"
    }).c('session', {
      xmlns: Strophe.NS.SESSION
    }).tree());
  }
  /** PrivateFunction: _onSessionResultIQ
   *  _Private_ handler for the server's IQ response to a client's session
   *  request.
   *
   *  This sets Connection.authenticated to true on success, which
   *  starts the processing of user handlers.
   *
   *  See https://xmpp.org/rfcs/rfc3921.html#session
   *
   *  Note: The protocol for session establishment has been determined as
   *  unnecessary and removed in RFC-6121.
   *
   *  Parameters:
   *    (XMLElement) elem - The matching stanza.
   *
   *  Returns:
   *    false to remove the handler.
   */


  _onSessionResultIQ(elem) {
    if (elem.getAttribute("type") === "result") {
      this.authenticated = true;

      this._changeConnectStatus(Strophe.Status.CONNECTED, null);
    } else if (elem.getAttribute("type") === "error") {
      this.authenticated = false;
      Strophe.warn("Session creation failed.");

      this._changeConnectStatus(Strophe.Status.AUTHFAIL, null, elem);

      return false;
    }

    return false;
  }
  /** PrivateFunction: _sasl_failure_cb
   *  _Private_ handler for SASL authentication failure.
   *
   *  Parameters:
   *    (XMLElement) elem - The matching stanza.
   *
   *  Returns:
   *    false to remove the handler.
   */


  _sasl_failure_cb(elem) {
    // delete unneeded handlers
    if (this._sasl_success_handler) {
      this.deleteHandler(this._sasl_success_handler);
      this._sasl_success_handler = null;
    }

    if (this._sasl_challenge_handler) {
      this.deleteHandler(this._sasl_challenge_handler);
      this._sasl_challenge_handler = null;
    }

    if (this._sasl_mechanism) this._sasl_mechanism.onFailure();

    this._changeConnectStatus(Strophe.Status.AUTHFAIL, null, elem);

    return false;
  }
  /** PrivateFunction: _auth2_cb
   *  _Private_ handler to finish legacy authentication.
   *
   *  This handler is called when the result from the jabber:iq:auth
   *  <iq/> stanza is returned.
   *
   *  Parameters:
   *    (XMLElement) elem - The stanza that triggered the callback.
   *
   *  Returns:
   *    false to remove the handler.
   */


  _auth2_cb(elem) {
    if (elem.getAttribute("type") === "result") {
      this.authenticated = true;

      this._changeConnectStatus(Strophe.Status.CONNECTED, null);
    } else if (elem.getAttribute("type") === "error") {
      this._changeConnectStatus(Strophe.Status.AUTHFAIL, null, elem);

      this.disconnect('authentication failed');
    }

    return false;
  }
  /** PrivateFunction: _addSysTimedHandler
   *  _Private_ function to add a system level timed handler.
   *
   *  This function is used to add a Strophe.TimedHandler for the
   *  library code.  System timed handlers are allowed to run before
   *  authentication is complete.
   *
   *  Parameters:
   *    (Integer) period - The period of the handler.
   *    (Function) handler - The callback function.
   */


  _addSysTimedHandler(period, handler) {
    const thand = new Strophe.TimedHandler(period, handler);
    thand.user = false;
    this.addTimeds.push(thand);
    return thand;
  }
  /** PrivateFunction: _addSysHandler
   *  _Private_ function to add a system level stanza handler.
   *
   *  This function is used to add a Strophe.Handler for the
   *  library code.  System stanza handlers are allowed to run before
   *  authentication is complete.
   *
   *  Parameters:
   *    (Function) handler - The callback function.
   *    (String) ns - The namespace to match.
   *    (String) name - The stanza name to match.
   *    (String) type - The stanza type attribute to match.
   *    (String) id - The stanza id attribute to match.
   */


  _addSysHandler(handler, ns, name, type, id) {
    const hand = new Strophe.Handler(handler, ns, name, type, id);
    hand.user = false;
    this.addHandlers.push(hand);
    return hand;
  }
  /** PrivateFunction: _onDisconnectTimeout
   *  _Private_ timeout handler for handling non-graceful disconnection.
   *
   *  If the graceful disconnect process does not complete within the
   *  time allotted, this handler finishes the disconnect anyway.
   *
   *  Returns:
   *    false to remove the handler.
   */


  _onDisconnectTimeout() {
    Strophe.debug("_onDisconnectTimeout was called");

    this._changeConnectStatus(Strophe.Status.CONNTIMEOUT, null);

    this._proto._onDisconnectTimeout(); // actually disconnect


    this._doDisconnect();

    return false;
  }
  /** PrivateFunction: _onIdle
   *  _Private_ handler to process events during idle cycle.
   *
   *  This handler is called every 100ms to fire timed handlers that
   *  are ready and keep poll requests going.
   */


  _onIdle() {
    // add timed handlers scheduled for addition
    // NOTE: we add before remove in the case a timed handler is
    // added and then deleted before the next _onIdle() call.
    while (this.addTimeds.length > 0) {
      this.timedHandlers.push(this.addTimeds.pop());
    } // remove timed handlers that have been scheduled for deletion


    while (this.removeTimeds.length > 0) {
      const thand = this.removeTimeds.pop();
      const i = this.timedHandlers.indexOf(thand);

      if (i >= 0) {
        this.timedHandlers.splice(i, 1);
      }
    } // call ready timed handlers


    const now = new Date().getTime();
    const newList = [];

    for (let i = 0; i < this.timedHandlers.length; i++) {
      const thand = this.timedHandlers[i];

      if (this.authenticated || !thand.user) {
        const since = thand.lastCalled + thand.period;

        if (since - now <= 0) {
          if (thand.run()) {
            newList.push(thand);
          }
        } else {
          newList.push(thand);
        }
      }
    }

    this.timedHandlers = newList;
    clearTimeout(this._idleTimeout);

    this._proto._onIdle(); // reactivate the timer only if connected


    if (this.connected) {
      this._idleTimeout = setTimeout(() => this._onIdle(), 100);
    }
  }

};
Strophe.SASLMechanism = SASLMechanism;
/** Constants: SASL mechanisms
 *  Available authentication mechanisms
 *
 *  Strophe.SASLAnonymous   - SASL ANONYMOUS authentication.
 *  Strophe.SASLPlain       - SASL PLAIN authentication.
 *  Strophe.SASLSHA1        - SASL SCRAM-SHA-1 authentication
 *  Strophe.SASLOAuthBearer - SASL OAuth Bearer authentication
 *  Strophe.SASLExternal    - SASL EXTERNAL authentication
 *  Strophe.SASLXOAuth2     - SASL X-OAuth2 authentication
 */

Strophe.SASLAnonymous = sasl_anon_SASLAnonymous;
Strophe.SASLPlain = sasl_plain_SASLPlain;
Strophe.SASLSHA1 = sasl_sha1_SASLSHA1;
Strophe.SASLOAuthBearer = sasl_oauthbearer_SASLOAuthBearer;
Strophe.SASLExternal = sasl_external_SASLExternal;
Strophe.SASLXOAuth2 = sasl_xoauth2_SASLXOAuth2;

/* harmony default export */ var core = __webpack_exports__["g"] = ({
  'Strophe': Strophe,
  '$build': $build,
  '$iq': $iq,
  '$msg': $msg,
  '$pres': $pres,
  'SHA1': sha1["a" /* default */],
  'MD5': MD5,
  'b64_hmac_sha1': sha1["a" /* default */].b64_hmac_sha1,
  'b64_sha1': sha1["a" /* default */].b64_sha1,
  'str_hmac_sha1': sha1["a" /* default */].str_hmac_sha1,
  'str_sha1': sha1["a" /* default */].str_sha1
});

/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/* unused harmony export b64_sha1 */
/* harmony import */ var _bosh__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(152);
/* harmony import */ var _websocket__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(65);
/* harmony import */ var _worker_websocket__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(491);
/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(0);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "e", function() { return _core__WEBPACK_IMPORTED_MODULE_3__["f"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _core__WEBPACK_IMPORTED_MODULE_3__["a"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "b", function() { return _core__WEBPACK_IMPORTED_MODULE_3__["b"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "c", function() { return _core__WEBPACK_IMPORTED_MODULE_3__["c"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "d", function() { return _core__WEBPACK_IMPORTED_MODULE_3__["d"]; });

/*global global*/




global.$build = _core__WEBPACK_IMPORTED_MODULE_3__[/* default */ "g"].$build;
global.$iq = _core__WEBPACK_IMPORTED_MODULE_3__[/* default */ "g"].$iq;
global.$msg = _core__WEBPACK_IMPORTED_MODULE_3__[/* default */ "g"].$msg;
global.$pres = _core__WEBPACK_IMPORTED_MODULE_3__[/* default */ "g"].$pres;
global.Strophe = _core__WEBPACK_IMPORTED_MODULE_3__[/* default */ "g"].Strophe;

const {
  b64_sha1
} = _core__WEBPACK_IMPORTED_MODULE_3__[/* SHA1 */ "e"];
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(18)))

/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * Sizzle CSS Selector Engine v2.3.6
 * https://sizzlejs.com/
 *
 * Copyright JS Foundation and other contributors
 * Released under the MIT license
 * https://js.foundation/
 *
 * Date: 2021-02-16
 */
(function (window) {
  var i,
      support,
      Expr,
      getText,
      isXML,
      tokenize,
      compile,
      select,
      outermostContext,
      sortInput,
      hasDuplicate,
      // Local document vars
  setDocument,
      document,
      docElem,
      documentIsHTML,
      rbuggyQSA,
      rbuggyMatches,
      matches,
      contains,
      // Instance-specific data
  expando = "sizzle" + 1 * new Date(),
      preferredDoc = window.document,
      dirruns = 0,
      done = 0,
      classCache = createCache(),
      tokenCache = createCache(),
      compilerCache = createCache(),
      nonnativeSelectorCache = createCache(),
      sortOrder = function (a, b) {
    if (a === b) {
      hasDuplicate = true;
    }

    return 0;
  },
      // Instance methods
  hasOwn = {}.hasOwnProperty,
      arr = [],
      pop = arr.pop,
      pushNative = arr.push,
      push = arr.push,
      slice = arr.slice,
      // Use a stripped-down indexOf as it's faster than native
  // https://jsperf.com/thor-indexof-vs-for/5
  indexOf = function (list, elem) {
    var i = 0,
        len = list.length;

    for (; i < len; i++) {
      if (list[i] === elem) {
        return i;
      }
    }

    return -1;
  },
      booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + "ismap|loop|multiple|open|readonly|required|scoped",
      // Regular expressions
  // http://www.w3.org/TR/css3-selectors/#whitespace
  whitespace = "[\\x20\\t\\r\\n\\f]",
      // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram
  identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",
      // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
  attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2)
  "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5]
  // or strings [capture 3 or capture 4]"
  "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]",
      pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
  // 1. quoted (capture 3; capture 4 or capture 5)
  "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6)
  "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2)
  ".*" + ")\\)|)",
      // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
  rwhitespace = new RegExp(whitespace + "+", "g"),
      rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"),
      rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"),
      rcombinators = new RegExp("^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*"),
      rdescend = new RegExp(whitespace + "|>"),
      rpseudo = new RegExp(pseudos),
      ridentifier = new RegExp("^" + identifier + "$"),
      matchExpr = {
    "ID": new RegExp("^#(" + identifier + ")"),
    "CLASS": new RegExp("^\\.(" + identifier + ")"),
    "TAG": new RegExp("^(" + identifier + "|[*])"),
    "ATTR": new RegExp("^" + attributes),
    "PSEUDO": new RegExp("^" + pseudos),
    "CHILD": new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i"),
    "bool": new RegExp("^(?:" + booleans + ")$", "i"),
    // For use in libraries implementing .is()
    // We use this for POS matching in `select`
    "needsContext": new RegExp("^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i")
  },
      rhtml = /HTML$/i,
      rinputs = /^(?:input|select|textarea|button)$/i,
      rheader = /^h\d$/i,
      rnative = /^[^{]+\{\s*\[native \w/,
      // Easily-parseable/retrievable ID or TAG or CLASS selectors
  rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
      rsibling = /[+~]/,
      // CSS escapes
  // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
  runescape = new RegExp("\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g"),
      funescape = function (escape, nonHex) {
    var high = "0x" + escape.slice(1) - 0x10000;
    return nonHex ? // Strip the backslash prefix from a non-hex escape sequence
    nonHex : // Replace a hexadecimal escape sequence with the encoded Unicode code point
    // Support: IE <=11+
    // For values outside the Basic Multilingual Plane (BMP), manually construct a
    // surrogate pair
    high < 0 ? String.fromCharCode(high + 0x10000) : String.fromCharCode(high >> 10 | 0xD800, high & 0x3FF | 0xDC00);
  },
      // CSS string/identifier serialization
  // https://drafts.csswg.org/cssom/#common-serializing-idioms
  rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,
      fcssescape = function (ch, asCodePoint) {
    if (asCodePoint) {
      // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
      if (ch === "\0") {
        return "\uFFFD";
      } // Control characters and (dependent upon position) numbers get escaped as code points


      return ch.slice(0, -1) + "\\" + ch.charCodeAt(ch.length - 1).toString(16) + " ";
    } // Other potentially-special ASCII characters get backslash-escaped


    return "\\" + ch;
  },
      // Used for iframes
  // See setDocument()
  // Removing the function wrapper causes a "Permission Denied"
  // error in IE
  unloadHandler = function () {
    setDocument();
  },
      inDisabledFieldset = addCombinator(function (elem) {
    return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset";
  }, {
    dir: "parentNode",
    next: "legend"
  }); // Optimize for push.apply( _, NodeList )


  try {
    push.apply(arr = slice.call(preferredDoc.childNodes), preferredDoc.childNodes); // Support: Android<4.0
    // Detect silently failing push.apply
    // eslint-disable-next-line no-unused-expressions

    arr[preferredDoc.childNodes.length].nodeType;
  } catch (e) {
    push = {
      apply: arr.length ? // Leverage slice if possible
      function (target, els) {
        pushNative.apply(target, slice.call(els));
      } : // Support: IE<9
      // Otherwise append directly
      function (target, els) {
        var j = target.length,
            i = 0; // Can't trust NodeList.length

        while (target[j++] = els[i++]) {}

        target.length = j - 1;
      }
    };
  }

  function Sizzle(selector, context, results, seed) {
    var m,
        i,
        elem,
        nid,
        match,
        groups,
        newSelector,
        newContext = context && context.ownerDocument,
        // nodeType defaults to 9, since context defaults to document
    nodeType = context ? context.nodeType : 9;
    results = results || []; // Return early from calls with invalid selector or context

    if (typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11) {
      return results;
    } // Try to shortcut find operations (as opposed to filters) in HTML documents


    if (!seed) {
      setDocument(context);
      context = context || document;

      if (documentIsHTML) {
        // If the selector is sufficiently simple, try using a "get*By*" DOM method
        // (excepting DocumentFragment context, where the methods don't exist)
        if (nodeType !== 11 && (match = rquickExpr.exec(selector))) {
          // ID selector
          if (m = match[1]) {
            // Document context
            if (nodeType === 9) {
              if (elem = context.getElementById(m)) {
                // Support: IE, Opera, Webkit
                // TODO: identify versions
                // getElementById can match elements by name instead of ID
                if (elem.id === m) {
                  results.push(elem);
                  return results;
                }
              } else {
                return results;
              } // Element context

            } else {
              // Support: IE, Opera, Webkit
              // TODO: identify versions
              // getElementById can match elements by name instead of ID
              if (newContext && (elem = newContext.getElementById(m)) && contains(context, elem) && elem.id === m) {
                results.push(elem);
                return results;
              }
            } // Type selector

          } else if (match[2]) {
            push.apply(results, context.getElementsByTagName(selector));
            return results; // Class selector
          } else if ((m = match[3]) && support.getElementsByClassName && context.getElementsByClassName) {
            push.apply(results, context.getElementsByClassName(m));
            return results;
          }
        } // Take advantage of querySelectorAll


        if (support.qsa && !nonnativeSelectorCache[selector + " "] && (!rbuggyQSA || !rbuggyQSA.test(selector)) && ( // Support: IE 8 only
        // Exclude object elements
        nodeType !== 1 || context.nodeName.toLowerCase() !== "object")) {
          newSelector = selector;
          newContext = context; // qSA considers elements outside a scoping root when evaluating child or
          // descendant combinators, which is not what we want.
          // In such cases, we work around the behavior by prefixing every selector in the
          // list with an ID selector referencing the scope context.
          // The technique has to be used as well when a leading combinator is used
          // as such selectors are not recognized by querySelectorAll.
          // Thanks to Andrew Dupont for this technique.

          if (nodeType === 1 && (rdescend.test(selector) || rcombinators.test(selector))) {
            // Expand context for sibling selectors
            newContext = rsibling.test(selector) && testContext(context.parentNode) || context; // We can use :scope instead of the ID hack if the browser
            // supports it & if we're not changing the context.

            if (newContext !== context || !support.scope) {
              // Capture the context ID, setting it first if necessary
              if (nid = context.getAttribute("id")) {
                nid = nid.replace(rcssescape, fcssescape);
              } else {
                context.setAttribute("id", nid = expando);
              }
            } // Prefix every selector in the list


            groups = tokenize(selector);
            i = groups.length;

            while (i--) {
              groups[i] = (nid ? "#" + nid : ":scope") + " " + toSelector(groups[i]);
            }

            newSelector = groups.join(",");
          }

          try {
            push.apply(results, newContext.querySelectorAll(newSelector));
            return results;
          } catch (qsaError) {
            nonnativeSelectorCache(selector, true);
          } finally {
            if (nid === expando) {
              context.removeAttribute("id");
            }
          }
        }
      }
    } // All others


    return select(selector.replace(rtrim, "$1"), context, results, seed);
  }
  /**
   * Create key-value caches of limited size
   * @returns {function(string, object)} Returns the Object data after storing it on itself with
   *	property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
   *	deleting the oldest entry
   */


  function createCache() {
    var keys = [];

    function cache(key, value) {
      // Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
      if (keys.push(key + " ") > Expr.cacheLength) {
        // Only keep the most recent entries
        delete cache[keys.shift()];
      }

      return cache[key + " "] = value;
    }

    return cache;
  }
  /**
   * Mark a function for special use by Sizzle
   * @param {Function} fn The function to mark
   */


  function markFunction(fn) {
    fn[expando] = true;
    return fn;
  }
  /**
   * Support testing using an element
   * @param {Function} fn Passed the created element and returns a boolean result
   */


  function assert(fn) {
    var el = document.createElement("fieldset");

    try {
      return !!fn(el);
    } catch (e) {
      return false;
    } finally {
      // Remove from its parent by default
      if (el.parentNode) {
        el.parentNode.removeChild(el);
      } // release memory in IE


      el = null;
    }
  }
  /**
   * Adds the same handler for all of the specified attrs
   * @param {String} attrs Pipe-separated list of attributes
   * @param {Function} handler The method that will be applied
   */


  function addHandle(attrs, handler) {
    var arr = attrs.split("|"),
        i = arr.length;

    while (i--) {
      Expr.attrHandle[arr[i]] = handler;
    }
  }
  /**
   * Checks document order of two siblings
   * @param {Element} a
   * @param {Element} b
   * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
   */


  function siblingCheck(a, b) {
    var cur = b && a,
        diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes

    if (diff) {
      return diff;
    } // Check if b follows a


    if (cur) {
      while (cur = cur.nextSibling) {
        if (cur === b) {
          return -1;
        }
      }
    }

    return a ? 1 : -1;
  }
  /**
   * Returns a function to use in pseudos for input types
   * @param {String} type
   */


  function createInputPseudo(type) {
    return function (elem) {
      var name = elem.nodeName.toLowerCase();
      return name === "input" && elem.type === type;
    };
  }
  /**
   * Returns a function to use in pseudos for buttons
   * @param {String} type
   */


  function createButtonPseudo(type) {
    return function (elem) {
      var name = elem.nodeName.toLowerCase();
      return (name === "input" || name === "button") && elem.type === type;
    };
  }
  /**
   * Returns a function to use in pseudos for :enabled/:disabled
   * @param {Boolean} disabled true for :disabled; false for :enabled
   */


  function createDisabledPseudo(disabled) {
    // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
    return function (elem) {
      // Only certain elements can match :enabled or :disabled
      // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
      // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
      if ("form" in elem) {
        // Check for inherited disabledness on relevant non-disabled elements:
        // * listed form-associated elements in a disabled fieldset
        //   https://html.spec.whatwg.org/multipage/forms.html#category-listed
        //   https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
        // * option elements in a disabled optgroup
        //   https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
        // All such elements have a "form" property.
        if (elem.parentNode && elem.disabled === false) {
          // Option elements defer to a parent optgroup if present
          if ("label" in elem) {
            if ("label" in elem.parentNode) {
              return elem.parentNode.disabled === disabled;
            } else {
              return elem.disabled === disabled;
            }
          } // Support: IE 6 - 11
          // Use the isDisabled shortcut property to check for disabled fieldset ancestors


          return elem.isDisabled === disabled || // Where there is no isDisabled, check manually

          /* jshint -W018 */
          elem.isDisabled !== !disabled && inDisabledFieldset(elem) === disabled;
        }

        return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property.
        // Some victims get caught in our net (label, legend, menu, track), but it shouldn't
        // even exist on them, let alone have a boolean value.
      } else if ("label" in elem) {
        return elem.disabled === disabled;
      } // Remaining elements are neither :enabled nor :disabled


      return false;
    };
  }
  /**
   * Returns a function to use in pseudos for positionals
   * @param {Function} fn
   */


  function createPositionalPseudo(fn) {
    return markFunction(function (argument) {
      argument = +argument;
      return markFunction(function (seed, matches) {
        var j,
            matchIndexes = fn([], seed.length, argument),
            i = matchIndexes.length; // Match elements found at the specified indexes

        while (i--) {
          if (seed[j = matchIndexes[i]]) {
            seed[j] = !(matches[j] = seed[j]);
          }
        }
      });
    });
  }
  /**
   * Checks a node for validity as a Sizzle context
   * @param {Element|Object=} context
   * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
   */


  function testContext(context) {
    return context && typeof context.getElementsByTagName !== "undefined" && context;
  } // Expose support vars for convenience


  support = Sizzle.support = {};
  /**
   * Detects XML nodes
   * @param {Element|Object} elem An element or a document
   * @returns {Boolean} True iff elem is a non-HTML XML node
   */

  isXML = Sizzle.isXML = function (elem) {
    var namespace = elem && elem.namespaceURI,
        docElem = elem && (elem.ownerDocument || elem).documentElement; // Support: IE <=8
    // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes
    // https://bugs.jquery.com/ticket/4833

    return !rhtml.test(namespace || docElem && docElem.nodeName || "HTML");
  };
  /**
   * Sets document-related variables once based on the current document
   * @param {Element|Object} [doc] An element or document object to use to set the document
   * @returns {Object} Returns the current document
   */


  setDocument = Sizzle.setDocument = function (node) {
    var hasCompare,
        subWindow,
        doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected
    // Support: IE 11+, Edge 17 - 18+
    // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
    // two documents; shallow comparisons work.
    // eslint-disable-next-line eqeqeq

    if (doc == document || doc.nodeType !== 9 || !doc.documentElement) {
      return document;
    } // Update global variables


    document = doc;
    docElem = document.documentElement;
    documentIsHTML = !isXML(document); // Support: IE 9 - 11+, Edge 12 - 18+
    // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
    // Support: IE 11+, Edge 17 - 18+
    // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
    // two documents; shallow comparisons work.
    // eslint-disable-next-line eqeqeq

    if (preferredDoc != document && (subWindow = document.defaultView) && subWindow.top !== subWindow) {
      // Support: IE 11, Edge
      if (subWindow.addEventListener) {
        subWindow.addEventListener("unload", unloadHandler, false); // Support: IE 9 - 10 only
      } else if (subWindow.attachEvent) {
        subWindow.attachEvent("onunload", unloadHandler);
      }
    } // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only,
    // Safari 4 - 5 only, Opera <=11.6 - 12.x only
    // IE/Edge & older browsers don't support the :scope pseudo-class.
    // Support: Safari 6.0 only
    // Safari 6.0 supports :scope but it's an alias of :root there.


    support.scope = assert(function (el) {
      docElem.appendChild(el).appendChild(document.createElement("div"));
      return typeof el.querySelectorAll !== "undefined" && !el.querySelectorAll(":scope fieldset div").length;
    });
    /* Attributes
    ---------------------------------------------------------------------- */
    // Support: IE<8
    // Verify that getAttribute really returns attributes and not properties
    // (excepting IE8 booleans)

    support.attributes = assert(function (el) {
      el.className = "i";
      return !el.getAttribute("className");
    });
    /* getElement(s)By*
    ---------------------------------------------------------------------- */
    // Check if getElementsByTagName("*") returns only elements

    support.getElementsByTagName = assert(function (el) {
      el.appendChild(document.createComment(""));
      return !el.getElementsByTagName("*").length;
    }); // Support: IE<9

    support.getElementsByClassName = rnative.test(document.getElementsByClassName); // Support: IE<10
    // Check if getElementById returns elements by name
    // The broken getElementById methods don't pick up programmatically-set names,
    // so use a roundabout getElementsByName test

    support.getById = assert(function (el) {
      docElem.appendChild(el).id = expando;
      return !document.getElementsByName || !document.getElementsByName(expando).length;
    }); // ID filter and find

    if (support.getById) {
      Expr.filter["ID"] = function (id) {
        var attrId = id.replace(runescape, funescape);
        return function (elem) {
          return elem.getAttribute("id") === attrId;
        };
      };

      Expr.find["ID"] = function (id, context) {
        if (typeof context.getElementById !== "undefined" && documentIsHTML) {
          var elem = context.getElementById(id);
          return elem ? [elem] : [];
        }
      };
    } else {
      Expr.filter["ID"] = function (id) {
        var attrId = id.replace(runescape, funescape);
        return function (elem) {
          var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
          return node && node.value === attrId;
        };
      }; // Support: IE 6 - 7 only
      // getElementById is not reliable as a find shortcut


      Expr.find["ID"] = function (id, context) {
        if (typeof context.getElementById !== "undefined" && documentIsHTML) {
          var node,
              i,
              elems,
              elem = context.getElementById(id);

          if (elem) {
            // Verify the id attribute
            node = elem.getAttributeNode("id");

            if (node && node.value === id) {
              return [elem];
            } // Fall back on getElementsByName


            elems = context.getElementsByName(id);
            i = 0;

            while (elem = elems[i++]) {
              node = elem.getAttributeNode("id");

              if (node && node.value === id) {
                return [elem];
              }
            }
          }

          return [];
        }
      };
    } // Tag


    Expr.find["TAG"] = support.getElementsByTagName ? function (tag, context) {
      if (typeof context.getElementsByTagName !== "undefined") {
        return context.getElementsByTagName(tag); // DocumentFragment nodes don't have gEBTN
      } else if (support.qsa) {
        return context.querySelectorAll(tag);
      }
    } : function (tag, context) {
      var elem,
          tmp = [],
          i = 0,
          // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
      results = context.getElementsByTagName(tag); // Filter out possible comments

      if (tag === "*") {
        while (elem = results[i++]) {
          if (elem.nodeType === 1) {
            tmp.push(elem);
          }
        }

        return tmp;
      }

      return results;
    }; // Class

    Expr.find["CLASS"] = support.getElementsByClassName && function (className, context) {
      if (typeof context.getElementsByClassName !== "undefined" && documentIsHTML) {
        return context.getElementsByClassName(className);
      }
    };
    /* QSA/matchesSelector
    ---------------------------------------------------------------------- */
    // QSA and matchesSelector support
    // matchesSelector(:active) reports false when true (IE9/Opera 11.5)


    rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21)
    // We allow this because of a bug in IE8/9 that throws an error
    // whenever `document.activeElement` is accessed on an iframe
    // So, we allow :focus to pass through QSA all the time to avoid the IE error
    // See https://bugs.jquery.com/ticket/13378

    rbuggyQSA = [];

    if (support.qsa = rnative.test(document.querySelectorAll)) {
      // Build QSA regex
      // Regex strategy adopted from Diego Perini
      assert(function (el) {
        var input; // Select is set to empty string on purpose
        // This is to test IE's treatment of not explicitly
        // setting a boolean content attribute,
        // since its presence should be enough
        // https://bugs.jquery.com/ticket/12359

        docElem.appendChild(el).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16
        // Nothing should be selected when empty strings follow ^= or $= or *=
        // The test attribute must be unknown in Opera but "safe" for WinRT
        // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section

        if (el.querySelectorAll("[msallowcapture^='']").length) {
          rbuggyQSA.push("[*^$]=" + whitespace + "*(?:''|\"\")");
        } // Support: IE8
        // Boolean attributes and "value" are not treated correctly


        if (!el.querySelectorAll("[selected]").length) {
          rbuggyQSA.push("\\[" + whitespace + "*(?:value|" + booleans + ")");
        } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+


        if (!el.querySelectorAll("[id~=" + expando + "-]").length) {
          rbuggyQSA.push("~=");
        } // Support: IE 11+, Edge 15 - 18+
        // IE 11/Edge don't find elements on a `[name='']` query in some cases.
        // Adding a temporary attribute to the document before the selection works
        // around the issue.
        // Interestingly, IE 10 & older don't seem to have the issue.


        input = document.createElement("input");
        input.setAttribute("name", "");
        el.appendChild(input);

        if (!el.querySelectorAll("[name='']").length) {
          rbuggyQSA.push("\\[" + whitespace + "*name" + whitespace + "*=" + whitespace + "*(?:''|\"\")");
        } // Webkit/Opera - :checked should return selected option elements
        // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
        // IE8 throws error here and will not see later tests


        if (!el.querySelectorAll(":checked").length) {
          rbuggyQSA.push(":checked");
        } // Support: Safari 8+, iOS 8+
        // https://bugs.webkit.org/show_bug.cgi?id=136851
        // In-page `selector#id sibling-combinator selector` fails


        if (!el.querySelectorAll("a#" + expando + "+*").length) {
          rbuggyQSA.push(".#.+[+~]");
        } // Support: Firefox <=3.6 - 5 only
        // Old Firefox doesn't throw on a badly-escaped identifier.


        el.querySelectorAll("\\\f");
        rbuggyQSA.push("[\\r\\n\\f]");
      });
      assert(function (el) {
        el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>"; // Support: Windows 8 Native Apps
        // The type and name attributes are restricted during .innerHTML assignment

        var input = document.createElement("input");
        input.setAttribute("type", "hidden");
        el.appendChild(input).setAttribute("name", "D"); // Support: IE8
        // Enforce case-sensitivity of name attribute

        if (el.querySelectorAll("[name=d]").length) {
          rbuggyQSA.push("name" + whitespace + "*[*^$|!~]?=");
        } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
        // IE8 throws error here and will not see later tests


        if (el.querySelectorAll(":enabled").length !== 2) {
          rbuggyQSA.push(":enabled", ":disabled");
        } // Support: IE9-11+
        // IE's :disabled selector does not pick up the children of disabled fieldsets


        docElem.appendChild(el).disabled = true;

        if (el.querySelectorAll(":disabled").length !== 2) {
          rbuggyQSA.push(":enabled", ":disabled");
        } // Support: Opera 10 - 11 only
        // Opera 10-11 does not throw on post-comma invalid pseudos


        el.querySelectorAll("*,:x");
        rbuggyQSA.push(",.*:");
      });
    }

    if (support.matchesSelector = rnative.test(matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector)) {
      assert(function (el) {
        // Check to see if it's possible to do matchesSelector
        // on a disconnected node (IE 9)
        support.disconnectedMatch = matches.call(el, "*"); // This should fail with an exception
        // Gecko does not error, returns false instead

        matches.call(el, "[s!='']:x");
        rbuggyMatches.push("!=", pseudos);
      });
    }

    rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join("|"));
    rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join("|"));
    /* Contains
    ---------------------------------------------------------------------- */

    hasCompare = rnative.test(docElem.compareDocumentPosition); // Element contains another
    // Purposefully self-exclusive
    // As in, an element does not contain itself

    contains = hasCompare || rnative.test(docElem.contains) ? function (a, b) {
      var adown = a.nodeType === 9 ? a.documentElement : a,
          bup = b && b.parentNode;
      return a === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16));
    } : function (a, b) {
      if (b) {
        while (b = b.parentNode) {
          if (b === a) {
            return true;
          }
        }
      }

      return false;
    };
    /* Sorting
    ---------------------------------------------------------------------- */
    // Document order sorting

    sortOrder = hasCompare ? function (a, b) {
      // Flag for duplicate removal
      if (a === b) {
        hasDuplicate = true;
        return 0;
      } // Sort on method existence if only one input has compareDocumentPosition


      var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;

      if (compare) {
        return compare;
      } // Calculate position if both inputs belong to the same document
      // Support: IE 11+, Edge 17 - 18+
      // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
      // two documents; shallow comparisons work.
      // eslint-disable-next-line eqeqeq


      compare = (a.ownerDocument || a) == (b.ownerDocument || b) ? a.compareDocumentPosition(b) : // Otherwise we know they are disconnected
      1; // Disconnected nodes

      if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) {
        // Choose the first element that is related to our preferred document
        // Support: IE 11+, Edge 17 - 18+
        // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
        // two documents; shallow comparisons work.
        // eslint-disable-next-line eqeqeq
        if (a == document || a.ownerDocument == preferredDoc && contains(preferredDoc, a)) {
          return -1;
        } // Support: IE 11+, Edge 17 - 18+
        // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
        // two documents; shallow comparisons work.
        // eslint-disable-next-line eqeqeq


        if (b == document || b.ownerDocument == preferredDoc && contains(preferredDoc, b)) {
          return 1;
        } // Maintain original order


        return sortInput ? indexOf(sortInput, a) - indexOf(sortInput, b) : 0;
      }

      return compare & 4 ? -1 : 1;
    } : function (a, b) {
      // Exit early if the nodes are identical
      if (a === b) {
        hasDuplicate = true;
        return 0;
      }

      var cur,
          i = 0,
          aup = a.parentNode,
          bup = b.parentNode,
          ap = [a],
          bp = [b]; // Parentless nodes are either documents or disconnected

      if (!aup || !bup) {
        // Support: IE 11+, Edge 17 - 18+
        // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
        // two documents; shallow comparisons work.

        /* eslint-disable eqeqeq */
        return a == document ? -1 : b == document ? 1 :
        /* eslint-enable eqeqeq */
        aup ? -1 : bup ? 1 : sortInput ? indexOf(sortInput, a) - indexOf(sortInput, b) : 0; // If the nodes are siblings, we can do a quick check
      } else if (aup === bup) {
        return siblingCheck(a, b);
      } // Otherwise we need full lists of their ancestors for comparison


      cur = a;

      while (cur = cur.parentNode) {
        ap.unshift(cur);
      }

      cur = b;

      while (cur = cur.parentNode) {
        bp.unshift(cur);
      } // Walk down the tree looking for a discrepancy


      while (ap[i] === bp[i]) {
        i++;
      }

      return i ? // Do a sibling check if the nodes have a common ancestor
      siblingCheck(ap[i], bp[i]) : // Otherwise nodes in our document sort first
      // Support: IE 11+, Edge 17 - 18+
      // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
      // two documents; shallow comparisons work.

      /* eslint-disable eqeqeq */
      ap[i] == preferredDoc ? -1 : bp[i] == preferredDoc ? 1 :
      /* eslint-enable eqeqeq */
      0;
    };
    return document;
  };

  Sizzle.matches = function (expr, elements) {
    return Sizzle(expr, null, null, elements);
  };

  Sizzle.matchesSelector = function (elem, expr) {
    setDocument(elem);

    if (support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[expr + " "] && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
      try {
        var ret = matches.call(elem, expr); // IE 9's matchesSelector returns false on disconnected nodes

        if (ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document
        // fragment in IE 9
        elem.document && elem.document.nodeType !== 11) {
          return ret;
        }
      } catch (e) {
        nonnativeSelectorCache(expr, true);
      }
    }

    return Sizzle(expr, document, null, [elem]).length > 0;
  };

  Sizzle.contains = function (context, elem) {
    // Set document vars if needed
    // Support: IE 11+, Edge 17 - 18+
    // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
    // two documents; shallow comparisons work.
    // eslint-disable-next-line eqeqeq
    if ((context.ownerDocument || context) != document) {
      setDocument(context);
    }

    return contains(context, elem);
  };

  Sizzle.attr = function (elem, name) {
    // Set document vars if needed
    // Support: IE 11+, Edge 17 - 18+
    // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
    // two documents; shallow comparisons work.
    // eslint-disable-next-line eqeqeq
    if ((elem.ownerDocument || elem) != document) {
      setDocument(elem);
    }

    var fn = Expr.attrHandle[name.toLowerCase()],
        // Don't get fooled by Object.prototype properties (jQuery #13807)
    val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined;
    return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
  };

  Sizzle.escape = function (sel) {
    return (sel + "").replace(rcssescape, fcssescape);
  };

  Sizzle.error = function (msg) {
    throw new Error("Syntax error, unrecognized expression: " + msg);
  };
  /**
   * Document sorting and removing duplicates
   * @param {ArrayLike} results
   */


  Sizzle.uniqueSort = function (results) {
    var elem,
        duplicates = [],
        j = 0,
        i = 0; // Unless we *know* we can detect duplicates, assume their presence

    hasDuplicate = !support.detectDuplicates;
    sortInput = !support.sortStable && results.slice(0);
    results.sort(sortOrder);

    if (hasDuplicate) {
      while (elem = results[i++]) {
        if (elem === results[i]) {
          j = duplicates.push(i);
        }
      }

      while (j--) {
        results.splice(duplicates[j], 1);
      }
    } // Clear input after sorting to release objects
    // See https://github.com/jquery/sizzle/pull/225


    sortInput = null;
    return results;
  };
  /**
   * Utility function for retrieving the text value of an array of DOM nodes
   * @param {Array|Element} elem
   */


  getText = Sizzle.getText = function (elem) {
    var node,
        ret = "",
        i = 0,
        nodeType = elem.nodeType;

    if (!nodeType) {
      // If no nodeType, this is expected to be an array
      while (node = elem[i++]) {
        // Do not traverse comment nodes
        ret += getText(node);
      }
    } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
      // Use textContent for elements
      // innerText usage removed for consistency of new lines (jQuery #11153)
      if (typeof elem.textContent === "string") {
        return elem.textContent;
      } else {
        // Traverse its children
        for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
          ret += getText(elem);
        }
      }
    } else if (nodeType === 3 || nodeType === 4) {
      return elem.nodeValue;
    } // Do not include comment or processing instruction nodes


    return ret;
  };

  Expr = Sizzle.selectors = {
    // Can be adjusted by the user
    cacheLength: 50,
    createPseudo: markFunction,
    match: matchExpr,
    attrHandle: {},
    find: {},
    relative: {
      ">": {
        dir: "parentNode",
        first: true
      },
      " ": {
        dir: "parentNode"
      },
      "+": {
        dir: "previousSibling",
        first: true
      },
      "~": {
        dir: "previousSibling"
      }
    },
    preFilter: {
      "ATTR": function (match) {
        match[1] = match[1].replace(runescape, funescape); // Move the given value to match[3] whether quoted or unquoted

        match[3] = (match[3] || match[4] || match[5] || "").replace(runescape, funescape);

        if (match[2] === "~=") {
          match[3] = " " + match[3] + " ";
        }

        return match.slice(0, 4);
      },
      "CHILD": function (match) {
        /* matches from matchExpr["CHILD"]
        	1 type (only|nth|...)
        	2 what (child|of-type)
        	3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
        	4 xn-component of xn+y argument ([+-]?\d*n|)
        	5 sign of xn-component
        	6 x of xn-component
        	7 sign of y-component
        	8 y of y-component
        */
        match[1] = match[1].toLowerCase();

        if (match[1].slice(0, 3) === "nth") {
          // nth-* requires argument
          if (!match[3]) {
            Sizzle.error(match[0]);
          } // numeric x and y parameters for Expr.filter.CHILD
          // remember that false/true cast respectively to 0/1


          match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === "even" || match[3] === "odd"));
          match[5] = +(match[7] + match[8] || match[3] === "odd"); // other types prohibit arguments
        } else if (match[3]) {
          Sizzle.error(match[0]);
        }

        return match;
      },
      "PSEUDO": function (match) {
        var excess,
            unquoted = !match[6] && match[2];

        if (matchExpr["CHILD"].test(match[0])) {
          return null;
        } // Accept quoted arguments as-is


        if (match[3]) {
          match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments
        } else if (unquoted && rpseudo.test(unquoted) && ( // Get excess from tokenize (recursively)
        excess = tokenize(unquoted, true)) && ( // advance to the next closing parenthesis
        excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)) {
          // excess is a negative index
          match[0] = match[0].slice(0, excess);
          match[2] = unquoted.slice(0, excess);
        } // Return only captures needed by the pseudo filter method (type and argument)


        return match.slice(0, 3);
      }
    },
    filter: {
      "TAG": function (nodeNameSelector) {
        var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
        return nodeNameSelector === "*" ? function () {
          return true;
        } : function (elem) {
          return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
        };
      },
      "CLASS": function (className) {
        var pattern = classCache[className + " "];
        return pattern || (pattern = new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")) && classCache(className, function (elem) {
          return pattern.test(typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "");
        });
      },
      "ATTR": function (name, operator, check) {
        return function (elem) {
          var result = Sizzle.attr(elem, name);

          if (result == null) {
            return operator === "!=";
          }

          if (!operator) {
            return true;
          }

          result += "";
          /* eslint-disable max-len */

          return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf(check) === 0 : operator === "*=" ? check && result.indexOf(check) > -1 : operator === "$=" ? check && result.slice(-check.length) === check : operator === "~=" ? (" " + result.replace(rwhitespace, " ") + " ").indexOf(check) > -1 : operator === "|=" ? result === check || result.slice(0, check.length + 1) === check + "-" : false;
          /* eslint-enable max-len */
        };
      },
      "CHILD": function (type, what, _argument, first, last) {
        var simple = type.slice(0, 3) !== "nth",
            forward = type.slice(-4) !== "last",
            ofType = what === "of-type";
        return first === 1 && last === 0 ? // Shortcut for :nth-*(n)
        function (elem) {
          return !!elem.parentNode;
        } : function (elem, _context, xml) {
          var cache,
              uniqueCache,
              outerCache,
              node,
              nodeIndex,
              start,
              dir = simple !== forward ? "nextSibling" : "previousSibling",
              parent = elem.parentNode,
              name = ofType && elem.nodeName.toLowerCase(),
              useCache = !xml && !ofType,
              diff = false;

          if (parent) {
            // :(first|last|only)-(child|of-type)
            if (simple) {
              while (dir) {
                node = elem;

                while (node = node[dir]) {
                  if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
                    return false;
                  }
                } // Reverse direction for :only-* (if we haven't yet done so)


                start = dir = type === "only" && !start && "nextSibling";
              }

              return true;
            }

            start = [forward ? parent.firstChild : parent.lastChild]; // non-xml :nth-child(...) stores cache data on `parent`

            if (forward && useCache) {
              // Seek `elem` from a previously-cached index
              // ...in a gzip-friendly way
              node = parent;
              outerCache = node[expando] || (node[expando] = {}); // Support: IE <9 only
              // Defend against cloned attroperties (jQuery gh-1709)

              uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});
              cache = uniqueCache[type] || [];
              nodeIndex = cache[0] === dirruns && cache[1];
              diff = nodeIndex && cache[2];
              node = nodeIndex && parent.childNodes[nodeIndex];

              while (node = ++nodeIndex && node && node[dir] || ( // Fallback to seeking `elem` from the start
              diff = nodeIndex = 0) || start.pop()) {
                // When found, cache indexes on `parent` and break
                if (node.nodeType === 1 && ++diff && node === elem) {
                  uniqueCache[type] = [dirruns, nodeIndex, diff];
                  break;
                }
              }
            } else {
              // Use previously-cached element index if available
              if (useCache) {
                // ...in a gzip-friendly way
                node = elem;
                outerCache = node[expando] || (node[expando] = {}); // Support: IE <9 only
                // Defend against cloned attroperties (jQuery gh-1709)

                uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});
                cache = uniqueCache[type] || [];
                nodeIndex = cache[0] === dirruns && cache[1];
                diff = nodeIndex;
              } // xml :nth-child(...)
              // or :nth-last-child(...) or :nth(-last)?-of-type(...)


              if (diff === false) {
                // Use the same loop as above to seek `elem` from the start
                while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
                  if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) && ++diff) {
                    // Cache the index of each encountered element
                    if (useCache) {
                      outerCache = node[expando] || (node[expando] = {}); // Support: IE <9 only
                      // Defend against cloned attroperties (jQuery gh-1709)

                      uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});
                      uniqueCache[type] = [dirruns, diff];
                    }

                    if (node === elem) {
                      break;
                    }
                  }
                }
              }
            } // Incorporate the offset, then check against cycle size


            diff -= last;
            return diff === first || diff % first === 0 && diff / first >= 0;
          }
        };
      },
      "PSEUDO": function (pseudo, argument) {
        // pseudo-class names are case-insensitive
        // http://www.w3.org/TR/selectors/#pseudo-classes
        // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
        // Remember that setFilters inherits from pseudos
        var args,
            fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error("unsupported pseudo: " + pseudo); // The user may use createPseudo to indicate that
        // arguments are needed to create the filter function
        // just as Sizzle does

        if (fn[expando]) {
          return fn(argument);
        } // But maintain support for old signatures


        if (fn.length > 1) {
          args = [pseudo, pseudo, "", argument];
          return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function (seed, matches) {
            var idx,
                matched = fn(seed, argument),
                i = matched.length;

            while (i--) {
              idx = indexOf(seed, matched[i]);
              seed[idx] = !(matches[idx] = matched[i]);
            }
          }) : function (elem) {
            return fn(elem, 0, args);
          };
        }

        return fn;
      }
    },
    pseudos: {
      // Potentially complex pseudos
      "not": markFunction(function (selector) {
        // Trim the selector passed to compile
        // to avoid treating leading and trailing
        // spaces as combinators
        var input = [],
            results = [],
            matcher = compile(selector.replace(rtrim, "$1"));
        return matcher[expando] ? markFunction(function (seed, matches, _context, xml) {
          var elem,
              unmatched = matcher(seed, null, xml, []),
              i = seed.length; // Match elements unmatched by `matcher`

          while (i--) {
            if (elem = unmatched[i]) {
              seed[i] = !(matches[i] = elem);
            }
          }
        }) : function (elem, _context, xml) {
          input[0] = elem;
          matcher(input, null, xml, results); // Don't keep the element (issue #299)

          input[0] = null;
          return !results.pop();
        };
      }),
      "has": markFunction(function (selector) {
        return function (elem) {
          return Sizzle(selector, elem).length > 0;
        };
      }),
      "contains": markFunction(function (text) {
        text = text.replace(runescape, funescape);
        return function (elem) {
          return (elem.textContent || getText(elem)).indexOf(text) > -1;
        };
      }),
      // "Whether an element is represented by a :lang() selector
      // is based solely on the element's language value
      // being equal to the identifier C,
      // or beginning with the identifier C immediately followed by "-".
      // The matching of C against the element's language value is performed case-insensitively.
      // The identifier C does not have to be a valid language name."
      // http://www.w3.org/TR/selectors/#lang-pseudo
      "lang": markFunction(function (lang) {
        // lang value must be a valid identifier
        if (!ridentifier.test(lang || "")) {
          Sizzle.error("unsupported lang: " + lang);
        }

        lang = lang.replace(runescape, funescape).toLowerCase();
        return function (elem) {
          var elemLang;

          do {
            if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) {
              elemLang = elemLang.toLowerCase();
              return elemLang === lang || elemLang.indexOf(lang + "-") === 0;
            }
          } while ((elem = elem.parentNode) && elem.nodeType === 1);

          return false;
        };
      }),
      // Miscellaneous
      "target": function (elem) {
        var hash = window.location && window.location.hash;
        return hash && hash.slice(1) === elem.id;
      },
      "root": function (elem) {
        return elem === docElem;
      },
      "focus": function (elem) {
        return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
      },
      // Boolean properties
      "enabled": createDisabledPseudo(false),
      "disabled": createDisabledPseudo(true),
      "checked": function (elem) {
        // In CSS3, :checked should return both checked and selected elements
        // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
        var nodeName = elem.nodeName.toLowerCase();
        return nodeName === "input" && !!elem.checked || nodeName === "option" && !!elem.selected;
      },
      "selected": function (elem) {
        // Accessing this property makes selected-by-default
        // options in Safari work properly
        if (elem.parentNode) {
          // eslint-disable-next-line no-unused-expressions
          elem.parentNode.selectedIndex;
        }

        return elem.selected === true;
      },
      // Contents
      "empty": function (elem) {
        // http://www.w3.org/TR/selectors/#empty-pseudo
        // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
        //   but not by others (comment: 8; processing instruction: 7; etc.)
        // nodeType < 6 works because attributes (2) do not appear as children
        for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
          if (elem.nodeType < 6) {
            return false;
          }
        }

        return true;
      },
      "parent": function (elem) {
        return !Expr.pseudos["empty"](elem);
      },
      // Element/input types
      "header": function (elem) {
        return rheader.test(elem.nodeName);
      },
      "input": function (elem) {
        return rinputs.test(elem.nodeName);
      },
      "button": function (elem) {
        var name = elem.nodeName.toLowerCase();
        return name === "input" && elem.type === "button" || name === "button";
      },
      "text": function (elem) {
        var attr;
        return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( // Support: IE<8
        // New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
        (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text");
      },
      // Position-in-collection
      "first": createPositionalPseudo(function () {
        return [0];
      }),
      "last": createPositionalPseudo(function (_matchIndexes, length) {
        return [length - 1];
      }),
      "eq": createPositionalPseudo(function (_matchIndexes, length, argument) {
        return [argument < 0 ? argument + length : argument];
      }),
      "even": createPositionalPseudo(function (matchIndexes, length) {
        var i = 0;

        for (; i < length; i += 2) {
          matchIndexes.push(i);
        }

        return matchIndexes;
      }),
      "odd": createPositionalPseudo(function (matchIndexes, length) {
        var i = 1;

        for (; i < length; i += 2) {
          matchIndexes.push(i);
        }

        return matchIndexes;
      }),
      "lt": createPositionalPseudo(function (matchIndexes, length, argument) {
        var i = argument < 0 ? argument + length : argument > length ? length : argument;

        for (; --i >= 0;) {
          matchIndexes.push(i);
        }

        return matchIndexes;
      }),
      "gt": createPositionalPseudo(function (matchIndexes, length, argument) {
        var i = argument < 0 ? argument + length : argument;

        for (; ++i < length;) {
          matchIndexes.push(i);
        }

        return matchIndexes;
      })
    }
  };
  Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos

  for (i in {
    radio: true,
    checkbox: true,
    file: true,
    password: true,
    image: true
  }) {
    Expr.pseudos[i] = createInputPseudo(i);
  }

  for (i in {
    submit: true,
    reset: true
  }) {
    Expr.pseudos[i] = createButtonPseudo(i);
  } // Easy API for creating new setFilters


  function setFilters() {}

  setFilters.prototype = Expr.filters = Expr.pseudos;
  Expr.setFilters = new setFilters();

  tokenize = Sizzle.tokenize = function (selector, parseOnly) {
    var matched,
        match,
        tokens,
        type,
        soFar,
        groups,
        preFilters,
        cached = tokenCache[selector + " "];

    if (cached) {
      return parseOnly ? 0 : cached.slice(0);
    }

    soFar = selector;
    groups = [];
    preFilters = Expr.preFilter;

    while (soFar) {
      // Comma and first run
      if (!matched || (match = rcomma.exec(soFar))) {
        if (match) {
          // Don't consume trailing commas as valid
          soFar = soFar.slice(match[0].length) || soFar;
        }

        groups.push(tokens = []);
      }

      matched = false; // Combinators

      if (match = rcombinators.exec(soFar)) {
        matched = match.shift();
        tokens.push({
          value: matched,
          // Cast descendant combinators to space
          type: match[0].replace(rtrim, " ")
        });
        soFar = soFar.slice(matched.length);
      } // Filters


      for (type in Expr.filter) {
        if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) {
          matched = match.shift();
          tokens.push({
            value: matched,
            type: type,
            matches: match
          });
          soFar = soFar.slice(matched.length);
        }
      }

      if (!matched) {
        break;
      }
    } // Return the length of the invalid excess
    // if we're just parsing
    // Otherwise, throw an error or return tokens


    return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : // Cache the tokens
    tokenCache(selector, groups).slice(0);
  };

  function toSelector(tokens) {
    var i = 0,
        len = tokens.length,
        selector = "";

    for (; i < len; i++) {
      selector += tokens[i].value;
    }

    return selector;
  }

  function addCombinator(matcher, combinator, base) {
    var dir = combinator.dir,
        skip = combinator.next,
        key = skip || dir,
        checkNonElements = base && key === "parentNode",
        doneName = done++;
    return combinator.first ? // Check against closest ancestor/preceding element
    function (elem, context, xml) {
      while (elem = elem[dir]) {
        if (elem.nodeType === 1 || checkNonElements) {
          return matcher(elem, context, xml);
        }
      }

      return false;
    } : // Check against all ancestor/preceding elements
    function (elem, context, xml) {
      var oldCache,
          uniqueCache,
          outerCache,
          newCache = [dirruns, doneName]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching

      if (xml) {
        while (elem = elem[dir]) {
          if (elem.nodeType === 1 || checkNonElements) {
            if (matcher(elem, context, xml)) {
              return true;
            }
          }
        }
      } else {
        while (elem = elem[dir]) {
          if (elem.nodeType === 1 || checkNonElements) {
            outerCache = elem[expando] || (elem[expando] = {}); // Support: IE <9 only
            // Defend against cloned attroperties (jQuery gh-1709)

            uniqueCache = outerCache[elem.uniqueID] || (outerCache[elem.uniqueID] = {});

            if (skip && skip === elem.nodeName.toLowerCase()) {
              elem = elem[dir] || elem;
            } else if ((oldCache = uniqueCache[key]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
              // Assign to newCache so results back-propagate to previous elements
              return newCache[2] = oldCache[2];
            } else {
              // Reuse newcache so results back-propagate to previous elements
              uniqueCache[key] = newCache; // A match means we're done; a fail means we have to keep checking

              if (newCache[2] = matcher(elem, context, xml)) {
                return true;
              }
            }
          }
        }
      }

      return false;
    };
  }

  function elementMatcher(matchers) {
    return matchers.length > 1 ? function (elem, context, xml) {
      var i = matchers.length;

      while (i--) {
        if (!matchers[i](elem, context, xml)) {
          return false;
        }
      }

      return true;
    } : matchers[0];
  }

  function multipleContexts(selector, contexts, results) {
    var i = 0,
        len = contexts.length;

    for (; i < len; i++) {
      Sizzle(selector, contexts[i], results);
    }

    return results;
  }

  function condense(unmatched, map, filter, context, xml) {
    var elem,
        newUnmatched = [],
        i = 0,
        len = unmatched.length,
        mapped = map != null;

    for (; i < len; i++) {
      if (elem = unmatched[i]) {
        if (!filter || filter(elem, context, xml)) {
          newUnmatched.push(elem);

          if (mapped) {
            map.push(i);
          }
        }
      }
    }

    return newUnmatched;
  }

  function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
    if (postFilter && !postFilter[expando]) {
      postFilter = setMatcher(postFilter);
    }

    if (postFinder && !postFinder[expando]) {
      postFinder = setMatcher(postFinder, postSelector);
    }

    return markFunction(function (seed, results, context, xml) {
      var temp,
          i,
          elem,
          preMap = [],
          postMap = [],
          preexisting = results.length,
          // Get initial elements from seed or context
      elems = seed || multipleContexts(selector || "*", context.nodeType ? [context] : context, []),
          // Prefilter to get matcher input, preserving a map for seed-results synchronization
      matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems,
          matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
      postFinder || (seed ? preFilter : preexisting || postFilter) ? // ...intermediate processing is necessary
      [] : // ...otherwise use results directly
      results : matcherIn; // Find primary matches

      if (matcher) {
        matcher(matcherIn, matcherOut, context, xml);
      } // Apply postFilter


      if (postFilter) {
        temp = condense(matcherOut, postMap);
        postFilter(temp, [], context, xml); // Un-match failing elements by moving them back to matcherIn

        i = temp.length;

        while (i--) {
          if (elem = temp[i]) {
            matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
          }
        }
      }

      if (seed) {
        if (postFinder || preFilter) {
          if (postFinder) {
            // Get the final matcherOut by condensing this intermediate into postFinder contexts
            temp = [];
            i = matcherOut.length;

            while (i--) {
              if (elem = matcherOut[i]) {
                // Restore matcherIn since elem is not yet a final match
                temp.push(matcherIn[i] = elem);
              }
            }

            postFinder(null, matcherOut = [], temp, xml);
          } // Move matched elements from seed to results to keep them synchronized


          i = matcherOut.length;

          while (i--) {
            if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf(seed, elem) : preMap[i]) > -1) {
              seed[temp] = !(results[temp] = elem);
            }
          }
        } // Add elements to results, through postFinder if defined

      } else {
        matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);

        if (postFinder) {
          postFinder(null, results, matcherOut, xml);
        } else {
          push.apply(results, matcherOut);
        }
      }
    });
  }

  function matcherFromTokens(tokens) {
    var checkContext,
        matcher,
        j,
        len = tokens.length,
        leadingRelative = Expr.relative[tokens[0].type],
        implicitRelative = leadingRelative || Expr.relative[" "],
        i = leadingRelative ? 1 : 0,
        // The foundational matcher ensures that elements are reachable from top-level context(s)
    matchContext = addCombinator(function (elem) {
      return elem === checkContext;
    }, implicitRelative, true),
        matchAnyContext = addCombinator(function (elem) {
      return indexOf(checkContext, elem) > -1;
    }, implicitRelative, true),
        matchers = [function (elem, context, xml) {
      var ret = !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml)); // Avoid hanging onto element (issue #299)

      checkContext = null;
      return ret;
    }];

    for (; i < len; i++) {
      if (matcher = Expr.relative[tokens[i].type]) {
        matchers = [addCombinator(elementMatcher(matchers), matcher)];
      } else {
        matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches); // Return special upon seeing a positional matcher

        if (matcher[expando]) {
          // Find the next relative operator (if any) for proper handling
          j = ++i;

          for (; j < len; j++) {
            if (Expr.relative[tokens[j].type]) {
              break;
            }
          }

          return setMatcher(i > 1 && elementMatcher(matchers), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*`
          tokens.slice(0, i - 1).concat({
            value: tokens[i - 2].type === " " ? "*" : ""
          })).replace(rtrim, "$1"), matcher, i < j && matcherFromTokens(tokens.slice(i, j)), j < len && matcherFromTokens(tokens = tokens.slice(j)), j < len && toSelector(tokens));
        }

        matchers.push(matcher);
      }
    }

    return elementMatcher(matchers);
  }

  function matcherFromGroupMatchers(elementMatchers, setMatchers) {
    var bySet = setMatchers.length > 0,
        byElement = elementMatchers.length > 0,
        superMatcher = function (seed, context, xml, results, outermost) {
      var elem,
          j,
          matcher,
          matchedCount = 0,
          i = "0",
          unmatched = seed && [],
          setMatched = [],
          contextBackup = outermostContext,
          // We must always have either seed elements or outermost context
      elems = seed || byElement && Expr.find["TAG"]("*", outermost),
          // Use integer dirruns iff this is the outermost matcher
      dirrunsUnique = dirruns += contextBackup == null ? 1 : Math.random() || 0.1,
          len = elems.length;

      if (outermost) {
        // Support: IE 11+, Edge 17 - 18+
        // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
        // two documents; shallow comparisons work.
        // eslint-disable-next-line eqeqeq
        outermostContext = context == document || context || outermost;
      } // Add elements passing elementMatchers directly to results
      // Support: IE<9, Safari
      // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id


      for (; i !== len && (elem = elems[i]) != null; i++) {
        if (byElement && elem) {
          j = 0; // Support: IE 11+, Edge 17 - 18+
          // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
          // two documents; shallow comparisons work.
          // eslint-disable-next-line eqeqeq

          if (!context && elem.ownerDocument != document) {
            setDocument(elem);
            xml = !documentIsHTML;
          }

          while (matcher = elementMatchers[j++]) {
            if (matcher(elem, context || document, xml)) {
              results.push(elem);
              break;
            }
          }

          if (outermost) {
            dirruns = dirrunsUnique;
          }
        } // Track unmatched elements for set filters


        if (bySet) {
          // They will have gone through all possible matchers
          if (elem = !matcher && elem) {
            matchedCount--;
          } // Lengthen the array for every element, matched or not


          if (seed) {
            unmatched.push(elem);
          }
        }
      } // `i` is now the count of elements visited above, and adding it to `matchedCount`
      // makes the latter nonnegative.


      matchedCount += i; // Apply set filters to unmatched elements
      // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
      // equals `i`), unless we didn't visit _any_ elements in the above loop because we have
      // no element matchers and no seed.
      // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
      // case, which will result in a "00" `matchedCount` that differs from `i` but is also
      // numerically zero.

      if (bySet && i !== matchedCount) {
        j = 0;

        while (matcher = setMatchers[j++]) {
          matcher(unmatched, setMatched, context, xml);
        }

        if (seed) {
          // Reintegrate element matches to eliminate the need for sorting
          if (matchedCount > 0) {
            while (i--) {
              if (!(unmatched[i] || setMatched[i])) {
                setMatched[i] = pop.call(results);
              }
            }
          } // Discard index placeholder values to get only actual matches


          setMatched = condense(setMatched);
        } // Add matches to results


        push.apply(results, setMatched); // Seedless set matches succeeding multiple successful matchers stipulate sorting

        if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
          Sizzle.uniqueSort(results);
        }
      } // Override manipulation of globals by nested matchers


      if (outermost) {
        dirruns = dirrunsUnique;
        outermostContext = contextBackup;
      }

      return unmatched;
    };

    return bySet ? markFunction(superMatcher) : superMatcher;
  }

  compile = Sizzle.compile = function (selector, match
  /* Internal Use Only */
  ) {
    var i,
        setMatchers = [],
        elementMatchers = [],
        cached = compilerCache[selector + " "];

    if (!cached) {
      // Generate a function of recursive functions that can be used to check each element
      if (!match) {
        match = tokenize(selector);
      }

      i = match.length;

      while (i--) {
        cached = matcherFromTokens(match[i]);

        if (cached[expando]) {
          setMatchers.push(cached);
        } else {
          elementMatchers.push(cached);
        }
      } // Cache the compiled function


      cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers)); // Save selector and tokenization

      cached.selector = selector;
    }

    return cached;
  };
  /**
   * A low-level selection function that works with Sizzle's compiled
   *  selector functions
   * @param {String|Function} selector A selector or a pre-compiled
   *  selector function built with Sizzle.compile
   * @param {Element} context
   * @param {Array} [results]
   * @param {Array} [seed] A set of elements to match against
   */


  select = Sizzle.select = function (selector, context, results, seed) {
    var i,
        tokens,
        token,
        type,
        find,
        compiled = typeof selector === "function" && selector,
        match = !seed && tokenize(selector = compiled.selector || selector);
    results = results || []; // Try to minimize operations if there is only one selector in the list and no seed
    // (the latter of which guarantees us context)

    if (match.length === 1) {
      // Reduce context if the leading compound selector is an ID
      tokens = match[0] = match[0].slice(0);

      if (tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
        context = (Expr.find["ID"](token.matches[0].replace(runescape, funescape), context) || [])[0];

        if (!context) {
          return results; // Precompiled matchers will still verify ancestry, so step up a level
        } else if (compiled) {
          context = context.parentNode;
        }

        selector = selector.slice(tokens.shift().value.length);
      } // Fetch a seed set for right-to-left matching


      i = matchExpr["needsContext"].test(selector) ? 0 : tokens.length;

      while (i--) {
        token = tokens[i]; // Abort if we hit a combinator

        if (Expr.relative[type = token.type]) {
          break;
        }

        if (find = Expr.find[type]) {
          // Search, expanding context for leading sibling combinators
          if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context)) {
            // If seed is empty or no tokens remain, we can return early
            tokens.splice(i, 1);
            selector = seed.length && toSelector(tokens);

            if (!selector) {
              push.apply(results, seed);
              return results;
            }

            break;
          }
        }
      }
    } // Compile and execute a filtering function if one is not provided
    // Provide `match` to avoid retokenization if we modified the selector above


    (compiled || compile(selector, match))(seed, context, !documentIsHTML, results, !context || rsibling.test(selector) && testContext(context.parentNode) || context);
    return results;
  }; // One-time assignments
  // Sort stability


  support.sortStable = expando.split("").sort(sortOrder).join("") === expando; // Support: Chrome 14-35+
  // Always assume duplicates if they aren't passed to the comparison function

  support.detectDuplicates = !!hasDuplicate; // Initialize against the default document

  setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
  // Detached nodes confoundingly follow *each other*

  support.sortDetached = assert(function (el) {
    // Should return 1, but returns 4 (following)
    return el.compareDocumentPosition(document.createElement("fieldset")) & 1;
  }); // Support: IE<8
  // Prevent attribute/property "interpolation"
  // https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx

  if (!assert(function (el) {
    el.innerHTML = "<a href='#'></a>";
    return el.firstChild.getAttribute("href") === "#";
  })) {
    addHandle("type|href|height|width", function (elem, name, isXML) {
      if (!isXML) {
        return elem.getAttribute(name, name.toLowerCase() === "type" ? 1 : 2);
      }
    });
  } // Support: IE<9
  // Use defaultValue in place of getAttribute("value")


  if (!support.attributes || !assert(function (el) {
    el.innerHTML = "<input/>";
    el.firstChild.setAttribute("value", "");
    return el.firstChild.getAttribute("value") === "";
  })) {
    addHandle("value", function (elem, _name, isXML) {
      if (!isXML && elem.nodeName.toLowerCase() === "input") {
        return elem.defaultValue;
      }
    });
  } // Support: IE<9
  // Use getAttributeNode to fetch booleans when getAttribute lies


  if (!assert(function (el) {
    return el.getAttribute("disabled") == null;
  })) {
    addHandle(booleans, function (elem, name, isXML) {
      var val;

      if (!isXML) {
        return elem[name] === true ? name.toLowerCase() : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
      }
    });
  } // EXPOSE


  var _sizzle = window.Sizzle;

  Sizzle.noConflict = function () {
    if (window.Sizzle === Sizzle) {
      window.Sizzle = _sizzle;
    }

    return Sizzle;
  };

  if (true) {
    !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
      return Sizzle;
    }).call(exports, __webpack_require__, exports, module),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); // Sizzle requires that there be a global window in Common-JS like environments
  } else {} // EXPOSE

})(window);

/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {

!function (t, e) {
   true ? module.exports = e() : undefined;
}(this, function () {
  "use strict";

  var t = "millisecond",
      e = "second",
      n = "minute",
      r = "hour",
      i = "day",
      s = "week",
      u = "month",
      o = "quarter",
      a = "year",
      h = /^(\d{4})-?(\d{1,2})-?(\d{0,2})[^0-9]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?.?(\d{1,3})?$/,
      f = /\[([^\]]+)]|Y{2,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,
      c = function (t, e, n) {
    var r = String(t);
    return !r || r.length >= e ? t : "" + Array(e + 1 - r.length).join(n) + t;
  },
      d = {
    s: c,
    z: function (t) {
      var e = -t.utcOffset(),
          n = Math.abs(e),
          r = Math.floor(n / 60),
          i = n % 60;
      return (e <= 0 ? "+" : "-") + c(r, 2, "0") + ":" + c(i, 2, "0");
    },
    m: function (t, e) {
      var n = 12 * (e.year() - t.year()) + (e.month() - t.month()),
          r = t.clone().add(n, u),
          i = e - r < 0,
          s = t.clone().add(n + (i ? -1 : 1), u);
      return Number(-(n + (e - r) / (i ? r - s : s - r)) || 0);
    },
    a: function (t) {
      return t < 0 ? Math.ceil(t) || 0 : Math.floor(t);
    },
    p: function (h) {
      return {
        M: u,
        y: a,
        w: s,
        d: i,
        D: "date",
        h: r,
        m: n,
        s: e,
        ms: t,
        Q: o
      }[h] || String(h || "").toLowerCase().replace(/s$/, "");
    },
    u: function (t) {
      return void 0 === t;
    }
  },
      $ = {
    name: "en",
    weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
    months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_")
  },
      l = "en",
      m = {};

  m[l] = $;

  var y = function (t) {
    return t instanceof v;
  },
      M = function (t, e, n) {
    var r;
    if (!t) return l;
    if ("string" == typeof t) m[t] && (r = t), e && (m[t] = e, r = t);else {
      var i = t.name;
      m[i] = t, r = i;
    }
    return !n && r && (l = r), r || !n && l;
  },
      g = function (t, e) {
    if (y(t)) return t.clone();
    var n = "object" == typeof e ? e : {};
    return n.date = t, n.args = arguments, new v(n);
  },
      D = d;

  D.l = M, D.i = y, D.w = function (t, e) {
    return g(t, {
      locale: e.$L,
      utc: e.$u,
      $offset: e.$offset
    });
  };

  var v = function () {
    function c(t) {
      this.$L = this.$L || M(t.locale, null, !0), this.parse(t);
    }

    var d = c.prototype;
    return d.parse = function (t) {
      this.$d = function (t) {
        var e = t.date,
            n = t.utc;
        if (null === e) return new Date(NaN);
        if (D.u(e)) return new Date();
        if (e instanceof Date) return new Date(e);

        if ("string" == typeof e && !/Z$/i.test(e)) {
          var r = e.match(h);
          if (r) return n ? new Date(Date.UTC(r[1], r[2] - 1, r[3] || 1, r[4] || 0, r[5] || 0, r[6] || 0, r[7] || 0)) : new Date(r[1], r[2] - 1, r[3] || 1, r[4] || 0, r[5] || 0, r[6] || 0, r[7] || 0);
        }

        return new Date(e);
      }(t), this.init();
    }, d.init = function () {
      var t = this.$d;
      this.$y = t.getFullYear(), this.$M = t.getMonth(), this.$D = t.getDate(), this.$W = t.getDay(), this.$H = t.getHours(), this.$m = t.getMinutes(), this.$s = t.getSeconds(), this.$ms = t.getMilliseconds();
    }, d.$utils = function () {
      return D;
    }, d.isValid = function () {
      return !("Invalid Date" === this.$d.toString());
    }, d.isSame = function (t, e) {
      var n = g(t);
      return this.startOf(e) <= n && n <= this.endOf(e);
    }, d.isAfter = function (t, e) {
      return g(t) < this.startOf(e);
    }, d.isBefore = function (t, e) {
      return this.endOf(e) < g(t);
    }, d.$g = function (t, e, n) {
      return D.u(t) ? this[e] : this.set(n, t);
    }, d.year = function (t) {
      return this.$g(t, "$y", a);
    }, d.month = function (t) {
      return this.$g(t, "$M", u);
    }, d.day = function (t) {
      return this.$g(t, "$W", i);
    }, d.date = function (t) {
      return this.$g(t, "$D", "date");
    }, d.hour = function (t) {
      return this.$g(t, "$H", r);
    }, d.minute = function (t) {
      return this.$g(t, "$m", n);
    }, d.second = function (t) {
      return this.$g(t, "$s", e);
    }, d.millisecond = function (e) {
      return this.$g(e, "$ms", t);
    }, d.unix = function () {
      return Math.floor(this.valueOf() / 1e3);
    }, d.valueOf = function () {
      return this.$d.getTime();
    }, d.startOf = function (t, o) {
      var h = this,
          f = !!D.u(o) || o,
          c = D.p(t),
          d = function (t, e) {
        var n = D.w(h.$u ? Date.UTC(h.$y, e, t) : new Date(h.$y, e, t), h);
        return f ? n : n.endOf(i);
      },
          $ = function (t, e) {
        return D.w(h.toDate()[t].apply(h.toDate("s"), (f ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(e)), h);
      },
          l = this.$W,
          m = this.$M,
          y = this.$D,
          M = "set" + (this.$u ? "UTC" : "");

      switch (c) {
        case a:
          return f ? d(1, 0) : d(31, 11);

        case u:
          return f ? d(1, m) : d(0, m + 1);

        case s:
          var g = this.$locale().weekStart || 0,
              v = (l < g ? l + 7 : l) - g;
          return d(f ? y - v : y + (6 - v), m);

        case i:
        case "date":
          return $(M + "Hours", 0);

        case r:
          return $(M + "Minutes", 1);

        case n:
          return $(M + "Seconds", 2);

        case e:
          return $(M + "Milliseconds", 3);

        default:
          return this.clone();
      }
    }, d.endOf = function (t) {
      return this.startOf(t, !1);
    }, d.$set = function (s, o) {
      var h,
          f = D.p(s),
          c = "set" + (this.$u ? "UTC" : ""),
          d = (h = {}, h[i] = c + "Date", h.date = c + "Date", h[u] = c + "Month", h[a] = c + "FullYear", h[r] = c + "Hours", h[n] = c + "Minutes", h[e] = c + "Seconds", h[t] = c + "Milliseconds", h)[f],
          $ = f === i ? this.$D + (o - this.$W) : o;

      if (f === u || f === a) {
        var l = this.clone().set("date", 1);
        l.$d[d]($), l.init(), this.$d = l.set("date", Math.min(this.$D, l.daysInMonth())).$d;
      } else d && this.$d[d]($);

      return this.init(), this;
    }, d.set = function (t, e) {
      return this.clone().$set(t, e);
    }, d.get = function (t) {
      return this[D.p(t)]();
    }, d.add = function (t, o) {
      var h,
          f = this;
      t = Number(t);

      var c = D.p(o),
          d = function (e) {
        var n = g(f);
        return D.w(n.date(n.date() + Math.round(e * t)), f);
      };

      if (c === u) return this.set(u, this.$M + t);
      if (c === a) return this.set(a, this.$y + t);
      if (c === i) return d(1);
      if (c === s) return d(7);
      var $ = (h = {}, h[n] = 6e4, h[r] = 36e5, h[e] = 1e3, h)[c] || 1,
          l = this.$d.getTime() + t * $;
      return D.w(l, this);
    }, d.subtract = function (t, e) {
      return this.add(-1 * t, e);
    }, d.format = function (t) {
      var e = this;
      if (!this.isValid()) return "Invalid Date";

      var n = t || "YYYY-MM-DDTHH:mm:ssZ",
          r = D.z(this),
          i = this.$locale(),
          s = this.$H,
          u = this.$m,
          o = this.$M,
          a = i.weekdays,
          h = i.months,
          c = function (t, r, i, s) {
        return t && (t[r] || t(e, n)) || i[r].substr(0, s);
      },
          d = function (t) {
        return D.s(s % 12 || 12, t, "0");
      },
          $ = i.meridiem || function (t, e, n) {
        var r = t < 12 ? "AM" : "PM";
        return n ? r.toLowerCase() : r;
      },
          l = {
        YY: String(this.$y).slice(-2),
        YYYY: this.$y,
        M: o + 1,
        MM: D.s(o + 1, 2, "0"),
        MMM: c(i.monthsShort, o, h, 3),
        MMMM: c(h, o),
        D: this.$D,
        DD: D.s(this.$D, 2, "0"),
        d: String(this.$W),
        dd: c(i.weekdaysMin, this.$W, a, 2),
        ddd: c(i.weekdaysShort, this.$W, a, 3),
        dddd: a[this.$W],
        H: String(s),
        HH: D.s(s, 2, "0"),
        h: d(1),
        hh: d(2),
        a: $(s, u, !0),
        A: $(s, u, !1),
        m: String(u),
        mm: D.s(u, 2, "0"),
        s: String(this.$s),
        ss: D.s(this.$s, 2, "0"),
        SSS: D.s(this.$ms, 3, "0"),
        Z: r
      };

      return n.replace(f, function (t, e) {
        return e || l[t] || r.replace(":", "");
      });
    }, d.utcOffset = function () {
      return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
    }, d.diff = function (t, h, f) {
      var c,
          d = D.p(h),
          $ = g(t),
          l = 6e4 * ($.utcOffset() - this.utcOffset()),
          m = this - $,
          y = D.m(this, $);
      return y = (c = {}, c[a] = y / 12, c[u] = y, c[o] = y / 3, c[s] = (m - l) / 6048e5, c[i] = (m - l) / 864e5, c[r] = m / 36e5, c[n] = m / 6e4, c[e] = m / 1e3, c)[d] || m, f ? y : D.a(y);
    }, d.daysInMonth = function () {
      return this.endOf(u).$D;
    }, d.$locale = function () {
      return m[this.$L];
    }, d.locale = function (t, e) {
      if (!t) return this.$L;
      var n = this.clone(),
          r = M(t, e, !0);
      return r && (n.$L = r), n;
    }, d.clone = function () {
      return D.w(this.$d, this);
    }, d.toDate = function () {
      return new Date(this.valueOf());
    }, d.toJSON = function () {
      return this.isValid() ? this.toISOString() : null;
    }, d.toISOString = function () {
      return this.$d.toISOString();
    }, d.toString = function () {
      return this.$d.toUTCString();
    }, c;
  }();

  return g.prototype = v.prototype, g.extend = function (t, e) {
    return t(e, v, g), g;
  }, g.locale = M, g.isDayjs = y, g.unix = function (t) {
    return g(1e3 * t);
  }, g.en = m[l], g.Ls = m, g;
});

/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _freeGlobal_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(59);

/** Detect free variable `self`. */

var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */

var root = _freeGlobal_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"] || freeSelf || Function('return this')();
/* harmony default export */ __webpack_exports__["a"] = (root);

/***/ }),
/* 5 */,
/* 6 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return SHA1; });
/*
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
 * in FIPS PUB 180-1
 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for details.
 */

/* global define */

/* Some functions and variables have been stripped for use with Strophe */

/*
 * Calculate the SHA-1 of an array of big-endian words, and a bit length
 */
function core_sha1(x, len) {
  /* append padding */
  x[len >> 5] |= 0x80 << 24 - len % 32;
  x[(len + 64 >> 9 << 4) + 15] = len;
  var w = new Array(80);
  var a = 1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d = 271733878;
  var e = -1009589776;
  var i, j, t, olda, oldb, oldc, oldd, olde;

  for (i = 0; i < x.length; i += 16) {
    olda = a;
    oldb = b;
    oldc = c;
    oldd = d;
    olde = e;

    for (j = 0; j < 80; j++) {
      if (j < 16) {
        w[j] = x[i + j];
      } else {
        w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
      }

      t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
      e = d;
      d = c;
      c = rol(b, 30);
      b = a;
      a = t;
    }

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
    e = safe_add(e, olde);
  }

  return [a, b, c, d, e];
}
/*
 * Perform the appropriate triplet combination function for the current
 * iteration
 */


function sha1_ft(t, b, c, d) {
  if (t < 20) {
    return b & c | ~b & d;
  }

  if (t < 40) {
    return b ^ c ^ d;
  }

  if (t < 60) {
    return b & c | b & d | c & d;
  }

  return b ^ c ^ d;
}
/*
 * Determine the appropriate additive constant for the current iteration
 */


function sha1_kt(t) {
  return t < 20 ? 1518500249 : t < 40 ? 1859775393 : t < 60 ? -1894007588 : -899497514;
}
/*
 * Calculate the HMAC-SHA1 of a key and some data
 */


function core_hmac_sha1(key, data) {
  var bkey = str2binb(key);

  if (bkey.length > 16) {
    bkey = core_sha1(bkey, key.length * 8);
  }

  var ipad = new Array(16),
      opad = new Array(16);

  for (var i = 0; i < 16; i++) {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * 8);
  return core_sha1(opad.concat(hash), 512 + 160);
}
/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */


function safe_add(x, y) {
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return msw << 16 | lsw & 0xFFFF;
}
/*
 * Bitwise rotate a 32-bit number to the left.
 */


function rol(num, cnt) {
  return num << cnt | num >>> 32 - cnt;
}
/*
 * Convert an 8-bit or 16-bit string to an array of big-endian words
 * In 8-bit function, characters >255 have their hi-byte silently ignored.
 */


function str2binb(str) {
  var bin = [];
  var mask = 255;

  for (var i = 0; i < str.length * 8; i += 8) {
    bin[i >> 5] |= (str.charCodeAt(i / 8) & mask) << 24 - i % 32;
  }

  return bin;
}
/*
 * Convert an array of big-endian words to a base-64 string
 */


function binb2b64(binarray) {
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  var triplet, j;

  for (var i = 0; i < binarray.length * 4; i += 3) {
    triplet = (binarray[i >> 2] >> 8 * (3 - i % 4) & 0xFF) << 16 | (binarray[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4) & 0xFF) << 8 | binarray[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4) & 0xFF;

    for (j = 0; j < 4; j++) {
      if (i * 8 + j * 6 > binarray.length * 32) {
        str += "=";
      } else {
        str += tab.charAt(triplet >> 6 * (3 - j) & 0x3F);
      }
    }
  }

  return str;
}
/*
 * Convert an array of big-endian words to a string
 */


function binb2str(bin) {
  var str = "";
  var mask = 255;

  for (var i = 0; i < bin.length * 32; i += 8) {
    str += String.fromCharCode(bin[i >> 5] >>> 24 - i % 32 & mask);
  }

  return str;
}
/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */


const SHA1 = {
  b64_hmac_sha1: function (key, data) {
    return binb2b64(core_hmac_sha1(key, data));
  },
  b64_sha1: function (s) {
    return binb2b64(core_sha1(str2binb(s), s.length * 8));
  },
  binb2str: binb2str,
  core_hmac_sha1: core_hmac_sha1,
  str_hmac_sha1: function (key, data) {
    return binb2str(core_hmac_sha1(key, data));
  },
  str_sha1: function (s) {
    return binb2str(core_sha1(str2binb(s), s.length * 8));
  }
};


/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {

var escapeHtmlChar = __webpack_require__(494),
    toString = __webpack_require__(135);
/** Used to match HTML entities and HTML characters. */


var reUnescapedHtml = /[&<>"']/g,
    reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
/**
 * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
 * corresponding HTML entities.
 *
 * **Note:** No other characters are escaped. To escape additional
 * characters use a third-party library like [_he_](https://mths.be/he).
 *
 * Though the ">" character is escaped for symmetry, characters like
 * ">" and "/" don't need escaping in HTML and have no special meaning
 * unless they're part of a tag or unquoted attribute value. See
 * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
 * (under "semi-related fun fact") for more details.
 *
 * When working with HTML you should always
 * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
 * XSS vectors.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category String
 * @param {string} [string=''] The string to escape.
 * @returns {string} Returns the escaped string.
 * @example
 *
 * _.escape('fred, barney, & pebbles');
 * // => 'fred, barney, &amp; pebbles'
 */

function escape(string) {
  string = toString(string);
  return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string;
}

module.exports = escape;

/***/ }),
/* 8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return WebSocket; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DOMParser; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getDummyXMLDOMDocument; });
/*
 * This module provides uniform
 * Shims APIs and globals that are not present in all JS environments,
 * the most common example for Strophe being browser APIs like WebSocket
 * and DOM that don't exist under nodejs.
 *
 * Usually these will be supplied in nodejs by conditionally requiring a
 * NPM module that provides a compatible implementation.
 */

/* global global */

/**
 * WHATWG WebSockets API
 * https://www.w3.org/TR/websockets/
 *
 * Interface to use the web socket protocol
 *
 * Used implementations:
 * - supported browsers: built-in in WebSocket global
 *   https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#Browser_compatibility
 * - nodejs: use standard-compliant 'ws' module
 *   https://www.npmjs.com/package/ws
 */
function getWebSocketImplementation() {
  let WebSocketImplementation = global.WebSocket;

  if (typeof WebSocketImplementation === 'undefined') {
    try {
      WebSocketImplementation = __webpack_require__(323);
    } catch (err) {
      throw new Error('You must install the "ws" package to use Strophe in nodejs.');
    }
  }

  return WebSocketImplementation;
}

const WebSocket = getWebSocketImplementation();
/**
 * DOMParser
 * https://w3c.github.io/DOM-Parsing/#the-domparser-interface
 *
 * Interface to parse XML strings into Document objects
 *
 * Used implementations:
 * - supported browsers: built-in in DOMParser global
 *   https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#Browser_compatibility
 * - nodejs: use 'xmldom' module
 *   https://www.npmjs.com/package/xmldom
 */

function getDOMParserImplementation() {
  let DOMParserImplementation = global.DOMParser;

  if (typeof DOMParserImplementation === 'undefined') {
    try {
      DOMParserImplementation = __webpack_require__(92).DOMParser;
    } catch (err) {
      throw new Error('You must install the "xmldom" package to use Strophe in nodejs.');
    }
  }

  return DOMParserImplementation;
}

const DOMParser = getDOMParserImplementation();
/**
 *  Gets IE xml doc object. Used by getDummyXMLDocument shim.
 *
 *  Returns:
 *    A Microsoft XML DOM Object
 *  See Also:
 *    http://msdn.microsoft.com/en-us/library/ms757837%28VS.85%29.aspx
 */

function _getIEXmlDom() {
  const docStrings = ["Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"];

  for (let d = 0; d < docStrings.length; d++) {
    try {
      // eslint-disable-next-line no-undef
      const doc = new ActiveXObject(docStrings[d]);
      return doc;
    } catch (e) {// Try next one
    }
  }
}
/**
 * Creates a dummy XML DOM document to serve as an element and text node generator.
 *
 * Used implementations:
 *  - IE < 10: avoid using createDocument() due to a memory leak, use ie-specific
 *    workaround
 *  - other supported browsers: use document's createDocument
 *  - nodejs: use 'xmldom'
 */


function getDummyXMLDOMDocument() {
  // nodejs
  if (typeof document === 'undefined') {
    try {
      const DOMImplementation = __webpack_require__(92).DOMImplementation;

      return new DOMImplementation().createDocument('jabber:client', 'strophe', null);
    } catch (err) {
      throw new Error('You must install the "xmldom" package to use Strophe in nodejs.');
    }
  } // IE < 10


  if (document.implementation.createDocument === undefined || document.implementation.createDocument && document.documentMode && document.documentMode < 10) {
    const doc = _getIEXmlDom();

    doc.appendChild(doc.createElement('strophe'));
    return doc;
  } // All other supported browsers


  return document.implementation.createDocument('jabber:client', 'strophe', null);
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(18)))

/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {

var freeGlobal = __webpack_require__(94);
/** Detect free variable `self`. */


var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */

var root = freeGlobal || freeSelf || Function('return this')();
module.exports = root;

/***/ }),
/* 10 */
/***/ (function(module, exports) {

// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self // eslint-disable-next-line no-new-func
: Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef

/***/ }),
/* 11 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(module) {/* harmony import */ var _freeGlobal_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(59);

/** Detect free variable `exports`. */

var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */

var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */

var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */

var freeProcess = moduleExports && _freeGlobal_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].process;
/** Used to access faster Node.js helpers. */

var nodeUtil = function () {
  try {
    // Use `util.types` for Node.js 10+.
    var types = freeModule && freeModule.require && freeModule.require('util').types;

    if (types) {
      return types;
    } // Legacy `process.binding('util')` for Node.js < 10.


    return freeProcess && freeProcess.binding && freeProcess.binding('util');
  } catch (e) {}
}();

/* harmony default export */ __webpack_exports__["a"] = (nodeUtil);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(66)(module)))

/***/ }),
/* 12 */
/***/ (function(module, exports) {

/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
 * @example
 *
 * _.isArray([1, 2, 3]);
 * // => true
 *
 * _.isArray(document.body.children);
 * // => false
 *
 * _.isArray('abc');
 * // => false
 *
 * _.isArray(_.noop);
 * // => false
 */
var isArray = Array.isArray;
module.exports = isArray;

/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {

var store = __webpack_require__(142)('wks');

var uid = __webpack_require__(143);

var Symbol = __webpack_require__(10).Symbol;

var USE_SYMBOL = typeof Symbol == 'function';

var $exports = module.exports = function (name) {
  return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};

$exports.store = store;

/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {

var require;var require;(function () {
  function r(e, n, t) {
    function o(i, f) {
      if (!n[i]) {
        if (!e[i]) {
          var c = "function" == typeof require && require;
          if (!f && c) return require(i, !0);
          if (u) return u(i, !0);
          var a = new Error("Cannot find module '" + i + "'");
          throw a.code = "MODULE_NOT_FOUND", a;
        }

        var p = n[i] = {
          exports: {}
        };
        e[i][0].call(p.exports, function (r) {
          var n = e[i][1][r];
          return o(n || r);
        }, p, p.exports, r, e, n, t);
      }

      return n[i].exports;
    }

    for (var u = "function" == typeof require && require, i = 0; i < t.length; i++) o(t[i]);

    return o;
  }

  return r;
})()({
  1: [function (require, module, exports) {
    /**
     * default settings
     *
     * @author Zongmin Lei<leizongmin@gmail.com>
     */
    var FilterCSS = require("cssfilter").FilterCSS;

    var getDefaultCSSWhiteList = require("cssfilter").getDefaultWhiteList;

    var _ = require("./util");

    function getDefaultWhiteList() {
      return {
        a: ["target", "href", "title"],
        abbr: ["title"],
        address: [],
        area: ["shape", "coords", "href", "alt"],
        article: [],
        aside: [],
        audio: ["autoplay", "controls", "loop", "preload", "src"],
        b: [],
        bdi: ["dir"],
        bdo: ["dir"],
        big: [],
        blockquote: ["cite"],
        br: [],
        caption: [],
        center: [],
        cite: [],
        code: [],
        col: ["align", "valign", "span", "width"],
        colgroup: ["align", "valign", "span", "width"],
        dd: [],
        del: ["datetime"],
        details: ["open"],
        div: [],
        dl: [],
        dt: [],
        em: [],
        font: ["color", "size", "face"],
        footer: [],
        h1: [],
        h2: [],
        h3: [],
        h4: [],
        h5: [],
        h6: [],
        header: [],
        hr: [],
        i: [],
        img: ["src", "alt", "title", "width", "height"],
        ins: ["datetime"],
        li: [],
        mark: [],
        nav: [],
        ol: [],
        p: [],
        pre: [],
        s: [],
        section: [],
        small: [],
        span: [],
        sub: [],
        sup: [],
        strong: [],
        table: ["width", "border", "align", "valign"],
        tbody: ["align", "valign"],
        td: ["width", "rowspan", "colspan", "align", "valign"],
        tfoot: ["align", "valign"],
        th: ["width", "rowspan", "colspan", "align", "valign"],
        thead: ["align", "valign"],
        tr: ["rowspan", "align", "valign"],
        tt: [],
        u: [],
        ul: [],
        video: ["autoplay", "controls", "loop", "preload", "src", "height", "width"]
      };
    }

    var defaultCSSFilter = new FilterCSS();
    /**
     * default onTag function
     *
     * @param {String} tag
     * @param {String} html
     * @param {Object} options
     * @return {String}
     */

    function onTag(tag, html, options) {// do nothing
    }
    /**
     * default onIgnoreTag function
     *
     * @param {String} tag
     * @param {String} html
     * @param {Object} options
     * @return {String}
     */


    function onIgnoreTag(tag, html, options) {// do nothing
    }
    /**
     * default onTagAttr function
     *
     * @param {String} tag
     * @param {String} name
     * @param {String} value
     * @return {String}
     */


    function onTagAttr(tag, name, value) {// do nothing
    }
    /**
     * default onIgnoreTagAttr function
     *
     * @param {String} tag
     * @param {String} name
     * @param {String} value
     * @return {String}
     */


    function onIgnoreTagAttr(tag, name, value) {// do nothing
    }
    /**
     * default escapeHtml function
     *
     * @param {String} html
     */


    function escapeHtml(html) {
      return html.replace(REGEXP_LT, "&lt;").replace(REGEXP_GT, "&gt;");
    }
    /**
     * default safeAttrValue function
     *
     * @param {String} tag
     * @param {String} name
     * @param {String} value
     * @param {Object} cssFilter
     * @return {String}
     */


    function safeAttrValue(tag, name, value, cssFilter) {
      // unescape attribute value firstly
      value = friendlyAttrValue(value);

      if (name === "href" || name === "src") {
        // filter `href` and `src` attribute
        // only allow the value that starts with `http://` | `https://` | `mailto:` | `/` | `#`
        value = _.trim(value);
        if (value === "#") return "#";

        if (!(value.substr(0, 7) === "http://" || value.substr(0, 8) === "https://" || value.substr(0, 7) === "mailto:" || value.substr(0, 4) === "tel:" || value.substr(0, 11) === "data:image/" || value.substr(0, 6) === "ftp://" || value.substr(0, 2) === "./" || value.substr(0, 3) === "../" || value[0] === "#" || value[0] === "/")) {
          return "";
        }
      } else if (name === "background") {
        // filter `background` attribute (maybe no use)
        // `javascript:`
        REGEXP_DEFAULT_ON_TAG_ATTR_4.lastIndex = 0;

        if (REGEXP_DEFAULT_ON_TAG_ATTR_4.test(value)) {
          return "";
        }
      } else if (name === "style") {
        // `expression()`
        REGEXP_DEFAULT_ON_TAG_ATTR_7.lastIndex = 0;

        if (REGEXP_DEFAULT_ON_TAG_ATTR_7.test(value)) {
          return "";
        } // `url()`


        REGEXP_DEFAULT_ON_TAG_ATTR_8.lastIndex = 0;

        if (REGEXP_DEFAULT_ON_TAG_ATTR_8.test(value)) {
          REGEXP_DEFAULT_ON_TAG_ATTR_4.lastIndex = 0;

          if (REGEXP_DEFAULT_ON_TAG_ATTR_4.test(value)) {
            return "";
          }
        }

        if (cssFilter !== false) {
          cssFilter = cssFilter || defaultCSSFilter;
          value = cssFilter.process(value);
        }
      } // escape `<>"` before returns


      value = escapeAttrValue(value);
      return value;
    } // RegExp list


    var REGEXP_LT = /</g;
    var REGEXP_GT = />/g;
    var REGEXP_QUOTE = /"/g;
    var REGEXP_QUOTE_2 = /&quot;/g;
    var REGEXP_ATTR_VALUE_1 = /&#([a-zA-Z0-9]*);?/gim;
    var REGEXP_ATTR_VALUE_COLON = /&colon;?/gim;
    var REGEXP_ATTR_VALUE_NEWLINE = /&newline;?/gim;
    var REGEXP_DEFAULT_ON_TAG_ATTR_3 = /\/\*|\*\//gm;
    var REGEXP_DEFAULT_ON_TAG_ATTR_4 = /((j\s*a\s*v\s*a|v\s*b|l\s*i\s*v\s*e)\s*s\s*c\s*r\s*i\s*p\s*t\s*|m\s*o\s*c\s*h\s*a)\:/gi;
    var REGEXP_DEFAULT_ON_TAG_ATTR_5 = /^[\s"'`]*(d\s*a\s*t\s*a\s*)\:/gi;
    var REGEXP_DEFAULT_ON_TAG_ATTR_6 = /^[\s"'`]*(d\s*a\s*t\s*a\s*)\:\s*image\//gi;
    var REGEXP_DEFAULT_ON_TAG_ATTR_7 = /e\s*x\s*p\s*r\s*e\s*s\s*s\s*i\s*o\s*n\s*\(.*/gi;
    var REGEXP_DEFAULT_ON_TAG_ATTR_8 = /u\s*r\s*l\s*\(.*/gi;
    /**
     * escape doube quote
     *
     * @param {String} str
     * @return {String} str
     */

    function escapeQuote(str) {
      return str.replace(REGEXP_QUOTE, "&quot;");
    }
    /**
     * unescape double quote
     *
     * @param {String} str
     * @return {String} str
     */


    function unescapeQuote(str) {
      return str.replace(REGEXP_QUOTE_2, '"');
    }
    /**
     * escape html entities
     *
     * @param {String} str
     * @return {String}
     */


    function escapeHtmlEntities(str) {
      return str.replace(REGEXP_ATTR_VALUE_1, function replaceUnicode(str, code) {
        return code[0] === "x" || code[0] === "X" ? String.fromCharCode(parseInt(code.substr(1), 16)) : String.fromCharCode(parseInt(code, 10));
      });
    }
    /**
     * escape html5 new danger entities
     *
     * @param {String} str
     * @return {String}
     */


    function escapeDangerHtml5Entities(str) {
      return str.replace(REGEXP_ATTR_VALUE_COLON, ":").replace(REGEXP_ATTR_VALUE_NEWLINE, " ");
    }
    /**
     * clear nonprintable characters
     *
     * @param {String} str
     * @return {String}
     */


    function clearNonPrintableCharacter(str) {
      var str2 = "";

      for (var i = 0, len = str.length; i < len; i++) {
        str2 += str.charCodeAt(i) < 32 ? " " : str.charAt(i);
      }

      return _.trim(str2);
    }
    /**
     * get friendly attribute value
     *
     * @param {String} str
     * @return {String}
     */


    function friendlyAttrValue(str) {
      str = unescapeQuote(str);
      str = escapeHtmlEntities(str);
      str = escapeDangerHtml5Entities(str);
      str = clearNonPrintableCharacter(str);
      return str;
    }
    /**
     * unescape attribute value
     *
     * @param {String} str
     * @return {String}
     */


    function escapeAttrValue(str) {
      str = escapeQuote(str);
      str = escapeHtml(str);
      return str;
    }
    /**
     * `onIgnoreTag` function for removing all the tags that are not in whitelist
     */


    function onIgnoreTagStripAll() {
      return "";
    }
    /**
     * remove tag body
     * specify a `tags` list, if the tag is not in the `tags` list then process by the specify function (optional)
     *
     * @param {array} tags
     * @param {function} next
     */


    function StripTagBody(tags, next) {
      if (typeof next !== "function") {
        next = function () {};
      }

      var isRemoveAllTag = !Array.isArray(tags);

      function isRemoveTag(tag) {
        if (isRemoveAllTag) return true;
        return _.indexOf(tags, tag) !== -1;
      }

      var removeList = [];
      var posStart = false;
      return {
        onIgnoreTag: function (tag, html, options) {
          if (isRemoveTag(tag)) {
            if (options.isClosing) {
              var ret = "[/removed]";
              var end = options.position + ret.length;
              removeList.push([posStart !== false ? posStart : options.position, end]);
              posStart = false;
              return ret;
            } else {
              if (!posStart) {
                posStart = options.position;
              }

              return "[removed]";
            }
          } else {
            return next(tag, html, options);
          }
        },
        remove: function (html) {
          var rethtml = "";
          var lastPos = 0;

          _.forEach(removeList, function (pos) {
            rethtml += html.slice(lastPos, pos[0]);
            lastPos = pos[1];
          });

          rethtml += html.slice(lastPos);
          return rethtml;
        }
      };
    }
    /**
     * remove html comments
     *
     * @param {String} html
     * @return {String}
     */


    function stripCommentTag(html) {
      return html.replace(STRIP_COMMENT_TAG_REGEXP, "");
    }

    var STRIP_COMMENT_TAG_REGEXP = /<!--[\s\S]*?-->/g;
    /**
     * remove invisible characters
     *
     * @param {String} html
     * @return {String}
     */

    function stripBlankChar(html) {
      var chars = html.split("");
      chars = chars.filter(function (char) {
        var c = char.charCodeAt(0);
        if (c === 127) return false;

        if (c <= 31) {
          if (c === 10 || c === 13) return true;
          return false;
        }

        return true;
      });
      return chars.join("");
    }

    exports.whiteList = getDefaultWhiteList();
    exports.getDefaultWhiteList = getDefaultWhiteList;
    exports.onTag = onTag;
    exports.onIgnoreTag = onIgnoreTag;
    exports.onTagAttr = onTagAttr;
    exports.onIgnoreTagAttr = onIgnoreTagAttr;
    exports.safeAttrValue = safeAttrValue;
    exports.escapeHtml = escapeHtml;
    exports.escapeQuote = escapeQuote;
    exports.unescapeQuote = unescapeQuote;
    exports.escapeHtmlEntities = escapeHtmlEntities;
    exports.escapeDangerHtml5Entities = escapeDangerHtml5Entities;
    exports.clearNonPrintableCharacter = clearNonPrintableCharacter;
    exports.friendlyAttrValue = friendlyAttrValue;
    exports.escapeAttrValue = escapeAttrValue;
    exports.onIgnoreTagStripAll = onIgnoreTagStripAll;
    exports.StripTagBody = StripTagBody;
    exports.stripCommentTag = stripCommentTag;
    exports.stripBlankChar = stripBlankChar;
    exports.cssFilter = defaultCSSFilter;
    exports.getDefaultCSSWhiteList = getDefaultCSSWhiteList;
  }, {
    "./util": 4,
    "cssfilter": 8
  }],
  2: [function (require, module, exports) {
    /**
     * xss
     *
     * @author Zongmin Lei<leizongmin@gmail.com>
     */
    var DEFAULT = require("./default");

    var parser = require("./parser");

    var FilterXSS = require("./xss");
    /**
     * filter xss function
     *
     * @param {String} html
     * @param {Object} options { whiteList, onTag, onTagAttr, onIgnoreTag, onIgnoreTagAttr, safeAttrValue, escapeHtml }
     * @return {String}
     */


    function filterXSS(html, options) {
      var xss = new FilterXSS(options);
      return xss.process(html);
    }

    exports = module.exports = filterXSS;
    exports.filterXSS = filterXSS;
    exports.FilterXSS = FilterXSS;

    for (var i in DEFAULT) exports[i] = DEFAULT[i];

    for (var i in parser) exports[i] = parser[i]; // using `xss` on the browser, output `filterXSS` to the globals


    if (typeof window !== "undefined") {
      window.filterXSS = module.exports;
    } // using `xss` on the WebWorker, output `filterXSS` to the globals


    function isWorkerEnv() {
      return typeof self !== 'undefined' && typeof DedicatedWorkerGlobalScope !== 'undefined' && self instanceof DedicatedWorkerGlobalScope;
    }

    if (isWorkerEnv()) {
      self.filterXSS = module.exports;
    }
  }, {
    "./default": 1,
    "./parser": 3,
    "./xss": 5
  }],
  3: [function (require, module, exports) {
    /**
     * Simple HTML Parser
     *
     * @author Zongmin Lei<leizongmin@gmail.com>
     */
    var _ = require("./util");
    /**
     * get tag name
     *
     * @param {String} html e.g. '<a hef="#">'
     * @return {String}
     */


    function getTagName(html) {
      var i = _.spaceIndex(html);

      if (i === -1) {
        var tagName = html.slice(1, -1);
      } else {
        var tagName = html.slice(1, i + 1);
      }

      tagName = _.trim(tagName).toLowerCase();
      if (tagName.slice(0, 1) === "/") tagName = tagName.slice(1);
      if (tagName.slice(-1) === "/") tagName = tagName.slice(0, -1);
      return tagName;
    }
    /**
     * is close tag?
     *
     * @param {String} html 如：'<a hef="#">'
     * @return {Boolean}
     */


    function isClosing(html) {
      return html.slice(0, 2) === "</";
    }
    /**
     * parse input html and returns processed html
     *
     * @param {String} html
     * @param {Function} onTag e.g. function (sourcePosition, position, tag, html, isClosing)
     * @param {Function} escapeHtml
     * @return {String}
     */


    function parseTag(html, onTag, escapeHtml) {
      "use strict";

      var rethtml = "";
      var lastPos = 0;
      var tagStart = false;
      var quoteStart = false;
      var currentPos = 0;
      var len = html.length;
      var currentTagName = "";
      var currentHtml = "";

      chariterator: for (currentPos = 0; currentPos < len; currentPos++) {
        var c = html.charAt(currentPos);

        if (tagStart === false) {
          if (c === "<") {
            tagStart = currentPos;
            continue;
          }
        } else {
          if (quoteStart === false) {
            if (c === "<") {
              rethtml += escapeHtml(html.slice(lastPos, currentPos));
              tagStart = currentPos;
              lastPos = currentPos;
              continue;
            }

            if (c === ">") {
              rethtml += escapeHtml(html.slice(lastPos, tagStart));
              currentHtml = html.slice(tagStart, currentPos + 1);
              currentTagName = getTagName(currentHtml);
              rethtml += onTag(tagStart, rethtml.length, currentTagName, currentHtml, isClosing(currentHtml));
              lastPos = currentPos + 1;
              tagStart = false;
              continue;
            }

            if (c === '"' || c === "'") {
              var i = 1;
              var ic = html.charAt(currentPos - i);

              while (ic === " " || ic === "=") {
                if (ic === "=") {
                  quoteStart = c;
                  continue chariterator;
                }

                ic = html.charAt(currentPos - ++i);
              }
            }
          } else {
            if (c === quoteStart) {
              quoteStart = false;
              continue;
            }
          }
        }
      }

      if (lastPos < html.length) {
        rethtml += escapeHtml(html.substr(lastPos));
      }

      return rethtml;
    }

    var REGEXP_ILLEGAL_ATTR_NAME = /[^a-zA-Z0-9_:\.\-]/gim;
    /**
     * parse input attributes and returns processed attributes
     *
     * @param {String} html e.g. `href="#" target="_blank"`
     * @param {Function} onAttr e.g. `function (name, value)`
     * @return {String}
     */

    function parseAttr(html, onAttr) {
      "use strict";

      var lastPos = 0;
      var retAttrs = [];
      var tmpName = false;
      var len = html.length;

      function addAttr(name, value) {
        name = _.trim(name);
        name = name.replace(REGEXP_ILLEGAL_ATTR_NAME, "").toLowerCase();
        if (name.length < 1) return;
        var ret = onAttr(name, value || "");
        if (ret) retAttrs.push(ret);
      } // 逐个分析字符


      for (var i = 0; i < len; i++) {
        var c = html.charAt(i);
        var v, j;

        if (tmpName === false && c === "=") {
          tmpName = html.slice(lastPos, i);
          lastPos = i + 1;
          continue;
        }

        if (tmpName !== false) {
          if (i === lastPos && (c === '"' || c === "'") && html.charAt(i - 1) === "=") {
            j = html.indexOf(c, i + 1);

            if (j === -1) {
              break;
            } else {
              v = _.trim(html.slice(lastPos + 1, j));
              addAttr(tmpName, v);
              tmpName = false;
              i = j;
              lastPos = i + 1;
              continue;
            }
          }
        }

        if (/\s|\n|\t/.test(c)) {
          html = html.replace(/\s|\n|\t/g, " ");

          if (tmpName === false) {
            j = findNextEqual(html, i);

            if (j === -1) {
              v = _.trim(html.slice(lastPos, i));
              addAttr(v);
              tmpName = false;
              lastPos = i + 1;
              continue;
            } else {
              i = j - 1;
              continue;
            }
          } else {
            j = findBeforeEqual(html, i - 1);

            if (j === -1) {
              v = _.trim(html.slice(lastPos, i));
              v = stripQuoteWrap(v);
              addAttr(tmpName, v);
              tmpName = false;
              lastPos = i + 1;
              continue;
            } else {
              continue;
            }
          }
        }
      }

      if (lastPos < html.length) {
        if (tmpName === false) {
          addAttr(html.slice(lastPos));
        } else {
          addAttr(tmpName, stripQuoteWrap(_.trim(html.slice(lastPos))));
        }
      }

      return _.trim(retAttrs.join(" "));
    }

    function findNextEqual(str, i) {
      for (; i < str.length; i++) {
        var c = str[i];
        if (c === " ") continue;
        if (c === "=") return i;
        return -1;
      }
    }

    function findBeforeEqual(str, i) {
      for (; i > 0; i--) {
        var c = str[i];
        if (c === " ") continue;
        if (c === "=") return i;
        return -1;
      }
    }

    function isQuoteWrapString(text) {
      if (text[0] === '"' && text[text.length - 1] === '"' || text[0] === "'" && text[text.length - 1] === "'") {
        return true;
      } else {
        return false;
      }
    }

    function stripQuoteWrap(text) {
      if (isQuoteWrapString(text)) {
        return text.substr(1, text.length - 2);
      } else {
        return text;
      }
    }

    exports.parseTag = parseTag;
    exports.parseAttr = parseAttr;
  }, {
    "./util": 4
  }],
  4: [function (require, module, exports) {
    module.exports = {
      indexOf: function (arr, item) {
        var i, j;

        if (Array.prototype.indexOf) {
          return arr.indexOf(item);
        }

        for (i = 0, j = arr.length; i < j; i++) {
          if (arr[i] === item) {
            return i;
          }
        }

        return -1;
      },
      forEach: function (arr, fn, scope) {
        var i, j;

        if (Array.prototype.forEach) {
          return arr.forEach(fn, scope);
        }

        for (i = 0, j = arr.length; i < j; i++) {
          fn.call(scope, arr[i], i, arr);
        }
      },
      trim: function (str) {
        if (String.prototype.trim) {
          return str.trim();
        }

        return str.replace(/(^\s*)|(\s*$)/g, "");
      },
      spaceIndex: function (str) {
        var reg = /\s|\n|\t/;
        var match = reg.exec(str);
        return match ? match.index : -1;
      }
    };
  }, {}],
  5: [function (require, module, exports) {
    /**
     * filter xss
     *
     * @author Zongmin Lei<leizongmin@gmail.com>
     */
    var FilterCSS = require("cssfilter").FilterCSS;

    var DEFAULT = require("./default");

    var parser = require("./parser");

    var parseTag = parser.parseTag;
    var parseAttr = parser.parseAttr;

    var _ = require("./util");
    /**
     * returns `true` if the input value is `undefined` or `null`
     *
     * @param {Object} obj
     * @return {Boolean}
     */


    function isNull(obj) {
      return obj === undefined || obj === null;
    }
    /**
     * get attributes for a tag
     *
     * @param {String} html
     * @return {Object}
     *   - {String} html
     *   - {Boolean} closing
     */


    function getAttrs(html) {
      var i = _.spaceIndex(html);

      if (i === -1) {
        return {
          html: "",
          closing: html[html.length - 2] === "/"
        };
      }

      html = _.trim(html.slice(i + 1, -1));
      var isClosing = html[html.length - 1] === "/";
      if (isClosing) html = _.trim(html.slice(0, -1));
      return {
        html: html,
        closing: isClosing
      };
    }
    /**
     * shallow copy
     *
     * @param {Object} obj
     * @return {Object}
     */


    function shallowCopyObject(obj) {
      var ret = {};

      for (var i in obj) {
        ret[i] = obj[i];
      }

      return ret;
    }
    /**
     * FilterXSS class
     *
     * @param {Object} options
     *        whiteList, onTag, onTagAttr, onIgnoreTag,
     *        onIgnoreTagAttr, safeAttrValue, escapeHtml
     *        stripIgnoreTagBody, allowCommentTag, stripBlankChar
     *        css{whiteList, onAttr, onIgnoreAttr} `css=false` means don't use `cssfilter`
     */


    function FilterXSS(options) {
      options = shallowCopyObject(options || {});

      if (options.stripIgnoreTag) {
        if (options.onIgnoreTag) {
          console.error('Notes: cannot use these two options "stripIgnoreTag" and "onIgnoreTag" at the same time');
        }

        options.onIgnoreTag = DEFAULT.onIgnoreTagStripAll;
      }

      options.whiteList = options.whiteList || DEFAULT.whiteList;
      options.onTag = options.onTag || DEFAULT.onTag;
      options.onTagAttr = options.onTagAttr || DEFAULT.onTagAttr;
      options.onIgnoreTag = options.onIgnoreTag || DEFAULT.onIgnoreTag;
      options.onIgnoreTagAttr = options.onIgnoreTagAttr || DEFAULT.onIgnoreTagAttr;
      options.safeAttrValue = options.safeAttrValue || DEFAULT.safeAttrValue;
      options.escapeHtml = options.escapeHtml || DEFAULT.escapeHtml;
      this.options = options;

      if (options.css === false) {
        this.cssFilter = false;
      } else {
        options.css = options.css || {};
        this.cssFilter = new FilterCSS(options.css);
      }
    }
    /**
     * start process and returns result
     *
     * @param {String} html
     * @return {String}
     */


    FilterXSS.prototype.process = function (html) {
      // compatible with the input
      html = html || "";
      html = html.toString();
      if (!html) return "";
      var me = this;
      var options = me.options;
      var whiteList = options.whiteList;
      var onTag = options.onTag;
      var onIgnoreTag = options.onIgnoreTag;
      var onTagAttr = options.onTagAttr;
      var onIgnoreTagAttr = options.onIgnoreTagAttr;
      var safeAttrValue = options.safeAttrValue;
      var escapeHtml = options.escapeHtml;
      var cssFilter = me.cssFilter; // remove invisible characters

      if (options.stripBlankChar) {
        html = DEFAULT.stripBlankChar(html);
      } // remove html comments


      if (!options.allowCommentTag) {
        html = DEFAULT.stripCommentTag(html);
      } // if enable stripIgnoreTagBody


      var stripIgnoreTagBody = false;

      if (options.stripIgnoreTagBody) {
        var stripIgnoreTagBody = DEFAULT.StripTagBody(options.stripIgnoreTagBody, onIgnoreTag);
        onIgnoreTag = stripIgnoreTagBody.onIgnoreTag;
      }

      var retHtml = parseTag(html, function (sourcePosition, position, tag, html, isClosing) {
        var info = {
          sourcePosition: sourcePosition,
          position: position,
          isClosing: isClosing,
          isWhite: whiteList.hasOwnProperty(tag)
        }; // call `onTag()`

        var ret = onTag(tag, html, info);
        if (!isNull(ret)) return ret;

        if (info.isWhite) {
          if (info.isClosing) {
            return "</" + tag + ">";
          }

          var attrs = getAttrs(html);
          var whiteAttrList = whiteList[tag];
          var attrsHtml = parseAttr(attrs.html, function (name, value) {
            // call `onTagAttr()`
            var isWhiteAttr = _.indexOf(whiteAttrList, name) !== -1;
            var ret = onTagAttr(tag, name, value, isWhiteAttr);
            if (!isNull(ret)) return ret;

            if (isWhiteAttr) {
              // call `safeAttrValue()`
              value = safeAttrValue(tag, name, value, cssFilter);

              if (value) {
                return name + '="' + value + '"';
              } else {
                return name;
              }
            } else {
              // call `onIgnoreTagAttr()`
              var ret = onIgnoreTagAttr(tag, name, value, isWhiteAttr);
              if (!isNull(ret)) return ret;
              return;
            }
          }); // build new tag html

          var html = "<" + tag;
          if (attrsHtml) html += " " + attrsHtml;
          if (attrs.closing) html += " /";
          html += ">";
          return html;
        } else {
          // call `onIgnoreTag()`
          var ret = onIgnoreTag(tag, html, info);
          if (!isNull(ret)) return ret;
          return escapeHtml(html);
        }
      }, escapeHtml); // if enable stripIgnoreTagBody

      if (stripIgnoreTagBody) {
        retHtml = stripIgnoreTagBody.remove(retHtml);
      }

      return retHtml;
    };

    module.exports = FilterXSS;
  }, {
    "./default": 1,
    "./parser": 3,
    "./util": 4,
    "cssfilter": 8
  }],
  6: [function (require, module, exports) {
    /**
     * cssfilter
     *
     * @author 老雷<leizongmin@gmail.com>
     */
    var DEFAULT = require('./default');

    var parseStyle = require('./parser');

    var _ = require('./util');
    /**
     * 返回值是否为空
     *
     * @param {Object} obj
     * @return {Boolean}
     */


    function isNull(obj) {
      return obj === undefined || obj === null;
    }
    /**
     * 浅拷贝对象
     *
     * @param {Object} obj
     * @return {Object}
     */


    function shallowCopyObject(obj) {
      var ret = {};

      for (var i in obj) {
        ret[i] = obj[i];
      }

      return ret;
    }
    /**
     * 创建CSS过滤器
     *
     * @param {Object} options
     *   - {Object} whiteList
     *   - {Function} onAttr
     *   - {Function} onIgnoreAttr
     *   - {Function} safeAttrValue
     */


    function FilterCSS(options) {
      options = shallowCopyObject(options || {});
      options.whiteList = options.whiteList || DEFAULT.whiteList;
      options.onAttr = options.onAttr || DEFAULT.onAttr;
      options.onIgnoreAttr = options.onIgnoreAttr || DEFAULT.onIgnoreAttr;
      options.safeAttrValue = options.safeAttrValue || DEFAULT.safeAttrValue;
      this.options = options;
    }

    FilterCSS.prototype.process = function (css) {
      // 兼容各种奇葩输入
      css = css || '';
      css = css.toString();
      if (!css) return '';
      var me = this;
      var options = me.options;
      var whiteList = options.whiteList;
      var onAttr = options.onAttr;
      var onIgnoreAttr = options.onIgnoreAttr;
      var safeAttrValue = options.safeAttrValue;
      var retCSS = parseStyle(css, function (sourcePosition, position, name, value, source) {
        var check = whiteList[name];
        var isWhite = false;
        if (check === true) isWhite = check;else if (typeof check === 'function') isWhite = check(value);else if (check instanceof RegExp) isWhite = check.test(value);
        if (isWhite !== true) isWhite = false; // 如果过滤后 value 为空则直接忽略

        value = safeAttrValue(name, value);
        if (!value) return;
        var opts = {
          position: position,
          sourcePosition: sourcePosition,
          source: source,
          isWhite: isWhite
        };

        if (isWhite) {
          var ret = onAttr(name, value, opts);

          if (isNull(ret)) {
            return name + ':' + value;
          } else {
            return ret;
          }
        } else {
          var ret = onIgnoreAttr(name, value, opts);

          if (!isNull(ret)) {
            return ret;
          }
        }
      });
      return retCSS;
    };

    module.exports = FilterCSS;
  }, {
    "./default": 7,
    "./parser": 9,
    "./util": 10
  }],
  7: [function (require, module, exports) {
    /**
     * cssfilter
     *
     * @author 老雷<leizongmin@gmail.com>
     */
    function getDefaultWhiteList() {
      // 白名单值说明：
      // true: 允许该属性
      // Function: function (val) { } 返回true表示允许该属性，其他值均表示不允许
      // RegExp: regexp.test(val) 返回true表示允许该属性，其他值均表示不允许
      // 除上面列出的值外均表示不允许
      var whiteList = {};
      whiteList['align-content'] = false; // default: auto

      whiteList['align-items'] = false; // default: auto

      whiteList['align-self'] = false; // default: auto

      whiteList['alignment-adjust'] = false; // default: auto

      whiteList['alignment-baseline'] = false; // default: baseline

      whiteList['all'] = false; // default: depending on individual properties

      whiteList['anchor-point'] = false; // default: none

      whiteList['animation'] = false; // default: depending on individual properties

      whiteList['animation-delay'] = false; // default: 0

      whiteList['animation-direction'] = false; // default: normal

      whiteList['animation-duration'] = false; // default: 0

      whiteList['animation-fill-mode'] = false; // default: none

      whiteList['animation-iteration-count'] = false; // default: 1

      whiteList['animation-name'] = false; // default: none

      whiteList['animation-play-state'] = false; // default: running

      whiteList['animation-timing-function'] = false; // default: ease

      whiteList['azimuth'] = false; // default: center

      whiteList['backface-visibility'] = false; // default: visible

      whiteList['background'] = true; // default: depending on individual properties

      whiteList['background-attachment'] = true; // default: scroll

      whiteList['background-clip'] = true; // default: border-box

      whiteList['background-color'] = true; // default: transparent

      whiteList['background-image'] = true; // default: none

      whiteList['background-origin'] = true; // default: padding-box

      whiteList['background-position'] = true; // default: 0% 0%

      whiteList['background-repeat'] = true; // default: repeat

      whiteList['background-size'] = true; // default: auto

      whiteList['baseline-shift'] = false; // default: baseline

      whiteList['binding'] = false; // default: none

      whiteList['bleed'] = false; // default: 6pt

      whiteList['bookmark-label'] = false; // default: content()

      whiteList['bookmark-level'] = false; // default: none

      whiteList['bookmark-state'] = false; // default: open

      whiteList['border'] = true; // default: depending on individual properties

      whiteList['border-bottom'] = true; // default: depending on individual properties

      whiteList['border-bottom-color'] = true; // default: current color

      whiteList['border-bottom-left-radius'] = true; // default: 0

      whiteList['border-bottom-right-radius'] = true; // default: 0

      whiteList['border-bottom-style'] = true; // default: none

      whiteList['border-bottom-width'] = true; // default: medium

      whiteList['border-collapse'] = true; // default: separate

      whiteList['border-color'] = true; // default: depending on individual properties

      whiteList['border-image'] = true; // default: none

      whiteList['border-image-outset'] = true; // default: 0

      whiteList['border-image-repeat'] = true; // default: stretch

      whiteList['border-image-slice'] = true; // default: 100%

      whiteList['border-image-source'] = true; // default: none

      whiteList['border-image-width'] = true; // default: 1

      whiteList['border-left'] = true; // default: depending on individual properties

      whiteList['border-left-color'] = true; // default: current color

      whiteList['border-left-style'] = true; // default: none

      whiteList['border-left-width'] = true; // default: medium

      whiteList['border-radius'] = true; // default: 0

      whiteList['border-right'] = true; // default: depending on individual properties

      whiteList['border-right-color'] = true; // default: current color

      whiteList['border-right-style'] = true; // default: none

      whiteList['border-right-width'] = true; // default: medium

      whiteList['border-spacing'] = true; // default: 0

      whiteList['border-style'] = true; // default: depending on individual properties

      whiteList['border-top'] = true; // default: depending on individual properties

      whiteList['border-top-color'] = true; // default: current color

      whiteList['border-top-left-radius'] = true; // default: 0

      whiteList['border-top-right-radius'] = true; // default: 0

      whiteList['border-top-style'] = true; // default: none

      whiteList['border-top-width'] = true; // default: medium

      whiteList['border-width'] = true; // default: depending on individual properties

      whiteList['bottom'] = false; // default: auto

      whiteList['box-decoration-break'] = true; // default: slice

      whiteList['box-shadow'] = true; // default: none

      whiteList['box-sizing'] = true; // default: content-box

      whiteList['box-snap'] = true; // default: none

      whiteList['box-suppress'] = true; // default: show

      whiteList['break-after'] = true; // default: auto

      whiteList['break-before'] = true; // default: auto

      whiteList['break-inside'] = true; // default: auto

      whiteList['caption-side'] = false; // default: top

      whiteList['chains'] = false; // default: none

      whiteList['clear'] = true; // default: none

      whiteList['clip'] = false; // default: auto

      whiteList['clip-path'] = false; // default: none

      whiteList['clip-rule'] = false; // default: nonzero

      whiteList['color'] = true; // default: implementation dependent

      whiteList['color-interpolation-filters'] = true; // default: auto

      whiteList['column-count'] = false; // default: auto

      whiteList['column-fill'] = false; // default: balance

      whiteList['column-gap'] = false; // default: normal

      whiteList['column-rule'] = false; // default: depending on individual properties

      whiteList['column-rule-color'] = false; // default: current color

      whiteList['column-rule-style'] = false; // default: medium

      whiteList['column-rule-width'] = false; // default: medium

      whiteList['column-span'] = false; // default: none

      whiteList['column-width'] = false; // default: auto

      whiteList['columns'] = false; // default: depending on individual properties

      whiteList['contain'] = false; // default: none

      whiteList['content'] = false; // default: normal

      whiteList['counter-increment'] = false; // default: none

      whiteList['counter-reset'] = false; // default: none

      whiteList['counter-set'] = false; // default: none

      whiteList['crop'] = false; // default: auto

      whiteList['cue'] = false; // default: depending on individual properties

      whiteList['cue-after'] = false; // default: none

      whiteList['cue-before'] = false; // default: none

      whiteList['cursor'] = false; // default: auto

      whiteList['direction'] = false; // default: ltr

      whiteList['display'] = true; // default: depending on individual properties

      whiteList['display-inside'] = true; // default: auto

      whiteList['display-list'] = true; // default: none

      whiteList['display-outside'] = true; // default: inline-level

      whiteList['dominant-baseline'] = false; // default: auto

      whiteList['elevation'] = false; // default: level

      whiteList['empty-cells'] = false; // default: show

      whiteList['filter'] = false; // default: none

      whiteList['flex'] = false; // default: depending on individual properties

      whiteList['flex-basis'] = false; // default: auto

      whiteList['flex-direction'] = false; // default: row

      whiteList['flex-flow'] = false; // default: depending on individual properties

      whiteList['flex-grow'] = false; // default: 0

      whiteList['flex-shrink'] = false; // default: 1

      whiteList['flex-wrap'] = false; // default: nowrap

      whiteList['float'] = false; // default: none

      whiteList['float-offset'] = false; // default: 0 0

      whiteList['flood-color'] = false; // default: black

      whiteList['flood-opacity'] = false; // default: 1

      whiteList['flow-from'] = false; // default: none

      whiteList['flow-into'] = false; // default: none

      whiteList['font'] = true; // default: depending on individual properties

      whiteList['font-family'] = true; // default: implementation dependent

      whiteList['font-feature-settings'] = true; // default: normal

      whiteList['font-kerning'] = true; // default: auto

      whiteList['font-language-override'] = true; // default: normal

      whiteList['font-size'] = true; // default: medium

      whiteList['font-size-adjust'] = true; // default: none

      whiteList['font-stretch'] = true; // default: normal

      whiteList['font-style'] = true; // default: normal

      whiteList['font-synthesis'] = true; // default: weight style

      whiteList['font-variant'] = true; // default: normal

      whiteList['font-variant-alternates'] = true; // default: normal

      whiteList['font-variant-caps'] = true; // default: normal

      whiteList['font-variant-east-asian'] = true; // default: normal

      whiteList['font-variant-ligatures'] = true; // default: normal

      whiteList['font-variant-numeric'] = true; // default: normal

      whiteList['font-variant-position'] = true; // default: normal

      whiteList['font-weight'] = true; // default: normal

      whiteList['grid'] = false; // default: depending on individual properties

      whiteList['grid-area'] = false; // default: depending on individual properties

      whiteList['grid-auto-columns'] = false; // default: auto

      whiteList['grid-auto-flow'] = false; // default: none

      whiteList['grid-auto-rows'] = false; // default: auto

      whiteList['grid-column'] = false; // default: depending on individual properties

      whiteList['grid-column-end'] = false; // default: auto

      whiteList['grid-column-start'] = false; // default: auto

      whiteList['grid-row'] = false; // default: depending on individual properties

      whiteList['grid-row-end'] = false; // default: auto

      whiteList['grid-row-start'] = false; // default: auto

      whiteList['grid-template'] = false; // default: depending on individual properties

      whiteList['grid-template-areas'] = false; // default: none

      whiteList['grid-template-columns'] = false; // default: none

      whiteList['grid-template-rows'] = false; // default: none

      whiteList['hanging-punctuation'] = false; // default: none

      whiteList['height'] = true; // default: auto

      whiteList['hyphens'] = false; // default: manual

      whiteList['icon'] = false; // default: auto

      whiteList['image-orientation'] = false; // default: auto

      whiteList['image-resolution'] = false; // default: normal

      whiteList['ime-mode'] = false; // default: auto

      whiteList['initial-letters'] = false; // default: normal

      whiteList['inline-box-align'] = false; // default: last

      whiteList['justify-content'] = false; // default: auto

      whiteList['justify-items'] = false; // default: auto

      whiteList['justify-self'] = false; // default: auto

      whiteList['left'] = false; // default: auto

      whiteList['letter-spacing'] = true; // default: normal

      whiteList['lighting-color'] = true; // default: white

      whiteList['line-box-contain'] = false; // default: block inline replaced

      whiteList['line-break'] = false; // default: auto

      whiteList['line-grid'] = false; // default: match-parent

      whiteList['line-height'] = false; // default: normal

      whiteList['line-snap'] = false; // default: none

      whiteList['line-stacking'] = false; // default: depending on individual properties

      whiteList['line-stacking-ruby'] = false; // default: exclude-ruby

      whiteList['line-stacking-shift'] = false; // default: consider-shifts

      whiteList['line-stacking-strategy'] = false; // default: inline-line-height

      whiteList['list-style'] = true; // default: depending on individual properties

      whiteList['list-style-image'] = true; // default: none

      whiteList['list-style-position'] = true; // default: outside

      whiteList['list-style-type'] = true; // default: disc

      whiteList['margin'] = true; // default: depending on individual properties

      whiteList['margin-bottom'] = true; // default: 0

      whiteList['margin-left'] = true; // default: 0

      whiteList['margin-right'] = true; // default: 0

      whiteList['margin-top'] = true; // default: 0

      whiteList['marker-offset'] = false; // default: auto

      whiteList['marker-side'] = false; // default: list-item

      whiteList['marks'] = false; // default: none

      whiteList['mask'] = false; // default: border-box

      whiteList['mask-box'] = false; // default: see individual properties

      whiteList['mask-box-outset'] = false; // default: 0

      whiteList['mask-box-repeat'] = false; // default: stretch

      whiteList['mask-box-slice'] = false; // default: 0 fill

      whiteList['mask-box-source'] = false; // default: none

      whiteList['mask-box-width'] = false; // default: auto

      whiteList['mask-clip'] = false; // default: border-box

      whiteList['mask-image'] = false; // default: none

      whiteList['mask-origin'] = false; // default: border-box

      whiteList['mask-position'] = false; // default: center

      whiteList['mask-repeat'] = false; // default: no-repeat

      whiteList['mask-size'] = false; // default: border-box

      whiteList['mask-source-type'] = false; // default: auto

      whiteList['mask-type'] = false; // default: luminance

      whiteList['max-height'] = true; // default: none

      whiteList['max-lines'] = false; // default: none

      whiteList['max-width'] = true; // default: none

      whiteList['min-height'] = true; // default: 0

      whiteList['min-width'] = true; // default: 0

      whiteList['move-to'] = false; // default: normal

      whiteList['nav-down'] = false; // default: auto

      whiteList['nav-index'] = false; // default: auto

      whiteList['nav-left'] = false; // default: auto

      whiteList['nav-right'] = false; // default: auto

      whiteList['nav-up'] = false; // default: auto

      whiteList['object-fit'] = false; // default: fill

      whiteList['object-position'] = false; // default: 50% 50%

      whiteList['opacity'] = false; // default: 1

      whiteList['order'] = false; // default: 0

      whiteList['orphans'] = false; // default: 2

      whiteList['outline'] = false; // default: depending on individual properties

      whiteList['outline-color'] = false; // default: invert

      whiteList['outline-offset'] = false; // default: 0

      whiteList['outline-style'] = false; // default: none

      whiteList['outline-width'] = false; // default: medium

      whiteList['overflow'] = false; // default: depending on individual properties

      whiteList['overflow-wrap'] = false; // default: normal

      whiteList['overflow-x'] = false; // default: visible

      whiteList['overflow-y'] = false; // default: visible

      whiteList['padding'] = true; // default: depending on individual properties

      whiteList['padding-bottom'] = true; // default: 0

      whiteList['padding-left'] = true; // default: 0

      whiteList['padding-right'] = true; // default: 0

      whiteList['padding-top'] = true; // default: 0

      whiteList['page'] = false; // default: auto

      whiteList['page-break-after'] = false; // default: auto

      whiteList['page-break-before'] = false; // default: auto

      whiteList['page-break-inside'] = false; // default: auto

      whiteList['page-policy'] = false; // default: start

      whiteList['pause'] = false; // default: implementation dependent

      whiteList['pause-after'] = false; // default: implementation dependent

      whiteList['pause-before'] = false; // default: implementation dependent

      whiteList['perspective'] = false; // default: none

      whiteList['perspective-origin'] = false; // default: 50% 50%

      whiteList['pitch'] = false; // default: medium

      whiteList['pitch-range'] = false; // default: 50

      whiteList['play-during'] = false; // default: auto

      whiteList['position'] = false; // default: static

      whiteList['presentation-level'] = false; // default: 0

      whiteList['quotes'] = false; // default: text

      whiteList['region-fragment'] = false; // default: auto

      whiteList['resize'] = false; // default: none

      whiteList['rest'] = false; // default: depending on individual properties

      whiteList['rest-after'] = false; // default: none

      whiteList['rest-before'] = false; // default: none

      whiteList['richness'] = false; // default: 50

      whiteList['right'] = false; // default: auto

      whiteList['rotation'] = false; // default: 0

      whiteList['rotation-point'] = false; // default: 50% 50%

      whiteList['ruby-align'] = false; // default: auto

      whiteList['ruby-merge'] = false; // default: separate

      whiteList['ruby-position'] = false; // default: before

      whiteList['shape-image-threshold'] = false; // default: 0.0

      whiteList['shape-outside'] = false; // default: none

      whiteList['shape-margin'] = false; // default: 0

      whiteList['size'] = false; // default: auto

      whiteList['speak'] = false; // default: auto

      whiteList['speak-as'] = false; // default: normal

      whiteList['speak-header'] = false; // default: once

      whiteList['speak-numeral'] = false; // default: continuous

      whiteList['speak-punctuation'] = false; // default: none

      whiteList['speech-rate'] = false; // default: medium

      whiteList['stress'] = false; // default: 50

      whiteList['string-set'] = false; // default: none

      whiteList['tab-size'] = false; // default: 8

      whiteList['table-layout'] = false; // default: auto

      whiteList['text-align'] = true; // default: start

      whiteList['text-align-last'] = true; // default: auto

      whiteList['text-combine-upright'] = true; // default: none

      whiteList['text-decoration'] = true; // default: none

      whiteList['text-decoration-color'] = true; // default: currentColor

      whiteList['text-decoration-line'] = true; // default: none

      whiteList['text-decoration-skip'] = true; // default: objects

      whiteList['text-decoration-style'] = true; // default: solid

      whiteList['text-emphasis'] = true; // default: depending on individual properties

      whiteList['text-emphasis-color'] = true; // default: currentColor

      whiteList['text-emphasis-position'] = true; // default: over right

      whiteList['text-emphasis-style'] = true; // default: none

      whiteList['text-height'] = true; // default: auto

      whiteList['text-indent'] = true; // default: 0

      whiteList['text-justify'] = true; // default: auto

      whiteList['text-orientation'] = true; // default: mixed

      whiteList['text-overflow'] = true; // default: clip

      whiteList['text-shadow'] = true; // default: none

      whiteList['text-space-collapse'] = true; // default: collapse

      whiteList['text-transform'] = true; // default: none

      whiteList['text-underline-position'] = true; // default: auto

      whiteList['text-wrap'] = true; // default: normal

      whiteList['top'] = false; // default: auto

      whiteList['transform'] = false; // default: none

      whiteList['transform-origin'] = false; // default: 50% 50% 0

      whiteList['transform-style'] = false; // default: flat

      whiteList['transition'] = false; // default: depending on individual properties

      whiteList['transition-delay'] = false; // default: 0s

      whiteList['transition-duration'] = false; // default: 0s

      whiteList['transition-property'] = false; // default: all

      whiteList['transition-timing-function'] = false; // default: ease

      whiteList['unicode-bidi'] = false; // default: normal

      whiteList['vertical-align'] = false; // default: baseline

      whiteList['visibility'] = false; // default: visible

      whiteList['voice-balance'] = false; // default: center

      whiteList['voice-duration'] = false; // default: auto

      whiteList['voice-family'] = false; // default: implementation dependent

      whiteList['voice-pitch'] = false; // default: medium

      whiteList['voice-range'] = false; // default: medium

      whiteList['voice-rate'] = false; // default: normal

      whiteList['voice-stress'] = false; // default: normal

      whiteList['voice-volume'] = false; // default: medium

      whiteList['volume'] = false; // default: medium

      whiteList['white-space'] = false; // default: normal

      whiteList['widows'] = false; // default: 2

      whiteList['width'] = true; // default: auto

      whiteList['will-change'] = false; // default: auto

      whiteList['word-break'] = true; // default: normal

      whiteList['word-spacing'] = true; // default: normal

      whiteList['word-wrap'] = true; // default: normal

      whiteList['wrap-flow'] = false; // default: auto

      whiteList['wrap-through'] = false; // default: wrap

      whiteList['writing-mode'] = false; // default: horizontal-tb

      whiteList['z-index'] = false; // default: auto

      return whiteList;
    }
    /**
     * 匹配到白名单上的一个属性时
     *
     * @param {String} name
     * @param {String} value
     * @param {Object} options
     * @return {String}
     */


    function onAttr(name, value, options) {// do nothing
    }
    /**
     * 匹配到不在白名单上的一个属性时
     *
     * @param {String} name
     * @param {String} value
     * @param {Object} options
     * @return {String}
     */


    function onIgnoreAttr(name, value, options) {// do nothing
    }

    var REGEXP_URL_JAVASCRIPT = /javascript\s*\:/img;
    /**
     * 过滤属性值
     *
     * @param {String} name
     * @param {String} value
     * @return {String}
     */

    function safeAttrValue(name, value) {
      if (REGEXP_URL_JAVASCRIPT.test(value)) return '';
      return value;
    }

    exports.whiteList = getDefaultWhiteList();
    exports.getDefaultWhiteList = getDefaultWhiteList;
    exports.onAttr = onAttr;
    exports.onIgnoreAttr = onIgnoreAttr;
    exports.safeAttrValue = safeAttrValue;
  }, {}],
  8: [function (require, module, exports) {
    /**
     * cssfilter
     *
     * @author 老雷<leizongmin@gmail.com>
     */
    var DEFAULT = require('./default');

    var FilterCSS = require('./css');
    /**
     * XSS过滤
     *
     * @param {String} css 要过滤的CSS代码
     * @param {Object} options 选项：whiteList, onAttr, onIgnoreAttr
     * @return {String}
     */


    function filterCSS(html, options) {
      var xss = new FilterCSS(options);
      return xss.process(html);
    } // 输出


    exports = module.exports = filterCSS;
    exports.FilterCSS = FilterCSS;

    for (var i in DEFAULT) exports[i] = DEFAULT[i]; // 在浏览器端使用


    if (typeof window !== 'undefined') {
      window.filterCSS = module.exports;
    }
  }, {
    "./css": 6,
    "./default": 7
  }],
  9: [function (require, module, exports) {
    /**
     * cssfilter
     *
     * @author 老雷<leizongmin@gmail.com>
     */
    var _ = require('./util');
    /**
     * 解析style
     *
     * @param {String} css
     * @param {Function} onAttr 处理属性的函数
     *   参数格式： function (sourcePosition, position, name, value, source)
     * @return {String}
     */


    function parseStyle(css, onAttr) {
      css = _.trimRight(css);
      if (css[css.length - 1] !== ';') css += ';';
      var cssLength = css.length;
      var isParenthesisOpen = false;
      var lastPos = 0;
      var i = 0;
      var retCSS = '';

      function addNewAttr() {
        // 如果没有正常的闭合圆括号，则直接忽略当前属性
        if (!isParenthesisOpen) {
          var source = _.trim(css.slice(lastPos, i));

          var j = source.indexOf(':');

          if (j !== -1) {
            var name = _.trim(source.slice(0, j));

            var value = _.trim(source.slice(j + 1)); // 必须有属性名称


            if (name) {
              var ret = onAttr(lastPos, retCSS.length, name, value, source);
              if (ret) retCSS += ret + '; ';
            }
          }
        }

        lastPos = i + 1;
      }

      for (; i < cssLength; i++) {
        var c = css[i];

        if (c === '/' && css[i + 1] === '*') {
          // 备注开始
          var j = css.indexOf('*/', i + 2); // 如果没有正常的备注结束，则后面的部分全部跳过

          if (j === -1) break; // 直接将当前位置调到备注结尾，并且初始化状态

          i = j + 1;
          lastPos = i + 1;
          isParenthesisOpen = false;
        } else if (c === '(') {
          isParenthesisOpen = true;
        } else if (c === ')') {
          isParenthesisOpen = false;
        } else if (c === ';') {
          if (isParenthesisOpen) {// 在圆括号里面，忽略
          } else {
            addNewAttr();
          }
        } else if (c === '\n') {
          addNewAttr();
        }
      }

      return _.trim(retCSS);
    }

    module.exports = parseStyle;
  }, {
    "./util": 10
  }],
  10: [function (require, module, exports) {
    module.exports = {
      indexOf: function (arr, item) {
        var i, j;

        if (Array.prototype.indexOf) {
          return arr.indexOf(item);
        }

        for (i = 0, j = arr.length; i < j; i++) {
          if (arr[i] === item) {
            return i;
          }
        }

        return -1;
      },
      forEach: function (arr, fn, scope) {
        var i, j;

        if (Array.prototype.forEach) {
          return arr.forEach(fn, scope);
        }

        for (i = 0, j = arr.length; i < j; i++) {
          fn.call(scope, arr[i], i, arr);
        }
      },
      trim: function (str) {
        if (String.prototype.trim) {
          return str.trim();
        }

        return str.replace(/(^\s*)|(\s*$)/g, '');
      },
      trimRight: function (str) {
        if (String.prototype.trimRight) {
          return str.trimRight();
        }

        return str.replace(/(\s*$)/g, '');
      }
    };
  }, {}]
}, {}, [2]);

/*** EXPORTS FROM exports-loader ***/
exports["filterXSS"] = (filterXSS);
exports["filterCSS"] = (filterCSS);

/***/ }),
/* 15 */
/***/ (function(module, exports) {

var core = module.exports = {
  version: '2.6.12'
};
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef

/***/ }),
/* 16 */
/***/ (function(module, exports) {

/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function isObject(value) {
  var type = typeof value;
  return value != null && (type == 'object' || type == 'function');
}

module.exports = isObject;

/***/ }),
/* 17 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(module) {/* harmony import */ var _root_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4);
/* harmony import */ var _stubFalse_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(156);


/** Detect free variable `exports`. */

var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */

var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */

var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */

var Buffer = moduleExports ? _root_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */

var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
 * Checks if `value` is a buffer.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
 * @example
 *
 * _.isBuffer(new Buffer(2));
 * // => true
 *
 * _.isBuffer(new Uint8Array(2));
 * // => false
 */

var isBuffer = nativeIsBuffer || _stubFalse_js__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"];
/* harmony default export */ __webpack_exports__["a"] = (isBuffer);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(66)(module)))

/***/ }),
/* 18 */
/***/ (function(module, exports) {

var g; // This works in non-strict mode

g = function () {
  return this;
}();

try {
  // This works if eval is allowed (see CSP)
  g = g || new Function("return this")();
} catch (e) {
  // This works if the window reference is available
  if (typeof window === "object") g = window;
} // g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}


module.exports = g;

/***/ }),
/* 19 */
/***/ (function(module, exports) {

/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return value != null && typeof value == 'object';
}

module.exports = isObjectLike;

/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {

var Symbol = __webpack_require__(45),
    getRawTag = __webpack_require__(333),
    objectToString = __webpack_require__(334);
/** `Object#toString` result references. */


var nullTag = '[object Null]',
    undefinedTag = '[object Undefined]';
/** Built-in value references. */

var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
 * The base implementation of `getTag` without fallbacks for buggy environments.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */

function baseGetTag(value) {
  if (value == null) {
    return value === undefined ? undefinedTag : nullTag;
  }

  return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
}

module.exports = baseGetTag;

/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {

var baseIsNative = __webpack_require__(351),
    getValue = __webpack_require__(354);
/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */


function getNative(object, key) {
  var value = getValue(object, key);
  return baseIsNative(value) ? value : undefined;
}

module.exports = getNative;

/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(37);

module.exports = function (it) {
  if (!isObject(it)) throw TypeError(it + ' is not an object!');
  return it;
};

/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {var require;var require;/*!
    localForage -- Offline Storage, Improved
    Version 1.9.0
    https://localforage.github.io/localForage
    (c) 2013-2017 Mozilla, Apache License 2.0
*/
(function (f) {
  if (true) {
    module.exports = f();
  } else { var g; }
})(function () {
  var define, module, exports;
  return function e(t, n, r) {
    function s(o, u) {
      if (!n[o]) {
        if (!t[o]) {
          var a = typeof require == "function" && require;
          if (!u && a) return require(o, !0);
          if (i) return i(o, !0);
          var f = new Error("Cannot find module '" + o + "'");
          throw f.code = "MODULE_NOT_FOUND", f;
        }

        var l = n[o] = {
          exports: {}
        };
        t[o][0].call(l.exports, function (e) {
          var n = t[o][1][e];
          return s(n ? n : e);
        }, l, l.exports, e, t, n, r);
      }

      return n[o].exports;
    }

    var i = typeof require == "function" && require;

    for (var o = 0; o < r.length; o++) s(r[o]);

    return s;
  }({
    1: [function (_dereq_, module, exports) {
      (function (global) {
        'use strict';

        var Mutation = global.MutationObserver || global.WebKitMutationObserver;
        var scheduleDrain;
        {
          if (Mutation) {
            var called = 0;
            var observer = new Mutation(nextTick);
            var element = global.document.createTextNode('');
            observer.observe(element, {
              characterData: true
            });

            scheduleDrain = function () {
              element.data = called = ++called % 2;
            };
          } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
            var channel = new global.MessageChannel();
            channel.port1.onmessage = nextTick;

            scheduleDrain = function () {
              channel.port2.postMessage(0);
            };
          } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
            scheduleDrain = function () {
              // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
              // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
              var scriptEl = global.document.createElement('script');

              scriptEl.onreadystatechange = function () {
                nextTick();
                scriptEl.onreadystatechange = null;
                scriptEl.parentNode.removeChild(scriptEl);
                scriptEl = null;
              };

              global.document.documentElement.appendChild(scriptEl);
            };
          } else {
            scheduleDrain = function () {
              setTimeout(nextTick, 0);
            };
          }
        }
        var draining;
        var queue = []; //named nextTick for less confusing stack traces

        function nextTick() {
          draining = true;
          var i, oldQueue;
          var len = queue.length;

          while (len) {
            oldQueue = queue;
            queue = [];
            i = -1;

            while (++i < len) {
              oldQueue[i]();
            }

            len = queue.length;
          }

          draining = false;
        }

        module.exports = immediate;

        function immediate(task) {
          if (queue.push(task) === 1 && !draining) {
            scheduleDrain();
          }
        }
      }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
    }, {}],
    2: [function (_dereq_, module, exports) {
      'use strict';

      var immediate = _dereq_(1);
      /* istanbul ignore next */


      function INTERNAL() {}

      var handlers = {};
      var REJECTED = ['REJECTED'];
      var FULFILLED = ['FULFILLED'];
      var PENDING = ['PENDING'];
      module.exports = Promise;

      function Promise(resolver) {
        if (typeof resolver !== 'function') {
          throw new TypeError('resolver must be a function');
        }

        this.state = PENDING;
        this.queue = [];
        this.outcome = void 0;

        if (resolver !== INTERNAL) {
          safelyResolveThenable(this, resolver);
        }
      }

      Promise.prototype["catch"] = function (onRejected) {
        return this.then(null, onRejected);
      };

      Promise.prototype.then = function (onFulfilled, onRejected) {
        if (typeof onFulfilled !== 'function' && this.state === FULFILLED || typeof onRejected !== 'function' && this.state === REJECTED) {
          return this;
        }

        var promise = new this.constructor(INTERNAL);

        if (this.state !== PENDING) {
          var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
          unwrap(promise, resolver, this.outcome);
        } else {
          this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
        }

        return promise;
      };

      function QueueItem(promise, onFulfilled, onRejected) {
        this.promise = promise;

        if (typeof onFulfilled === 'function') {
          this.onFulfilled = onFulfilled;
          this.callFulfilled = this.otherCallFulfilled;
        }

        if (typeof onRejected === 'function') {
          this.onRejected = onRejected;
          this.callRejected = this.otherCallRejected;
        }
      }

      QueueItem.prototype.callFulfilled = function (value) {
        handlers.resolve(this.promise, value);
      };

      QueueItem.prototype.otherCallFulfilled = function (value) {
        unwrap(this.promise, this.onFulfilled, value);
      };

      QueueItem.prototype.callRejected = function (value) {
        handlers.reject(this.promise, value);
      };

      QueueItem.prototype.otherCallRejected = function (value) {
        unwrap(this.promise, this.onRejected, value);
      };

      function unwrap(promise, func, value) {
        immediate(function () {
          var returnValue;

          try {
            returnValue = func(value);
          } catch (e) {
            return handlers.reject(promise, e);
          }

          if (returnValue === promise) {
            handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
          } else {
            handlers.resolve(promise, returnValue);
          }
        });
      }

      handlers.resolve = function (self, value) {
        var result = tryCatch(getThen, value);

        if (result.status === 'error') {
          return handlers.reject(self, result.value);
        }

        var thenable = result.value;

        if (thenable) {
          safelyResolveThenable(self, thenable);
        } else {
          self.state = FULFILLED;
          self.outcome = value;
          var i = -1;
          var len = self.queue.length;

          while (++i < len) {
            self.queue[i].callFulfilled(value);
          }
        }

        return self;
      };

      handlers.reject = function (self, error) {
        self.state = REJECTED;
        self.outcome = error;
        var i = -1;
        var len = self.queue.length;

        while (++i < len) {
          self.queue[i].callRejected(error);
        }

        return self;
      };

      function getThen(obj) {
        // Make sure we only access the accessor once as required by the spec
        var then = obj && obj.then;

        if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
          return function appyThen() {
            then.apply(obj, arguments);
          };
        }
      }

      function safelyResolveThenable(self, thenable) {
        // Either fulfill, reject or reject with error
        var called = false;

        function onError(value) {
          if (called) {
            return;
          }

          called = true;
          handlers.reject(self, value);
        }

        function onSuccess(value) {
          if (called) {
            return;
          }

          called = true;
          handlers.resolve(self, value);
        }

        function tryToUnwrap() {
          thenable(onSuccess, onError);
        }

        var result = tryCatch(tryToUnwrap);

        if (result.status === 'error') {
          onError(result.value);
        }
      }

      function tryCatch(func, value) {
        var out = {};

        try {
          out.value = func(value);
          out.status = 'success';
        } catch (e) {
          out.status = 'error';
          out.value = e;
        }

        return out;
      }

      Promise.resolve = resolve;

      function resolve(value) {
        if (value instanceof this) {
          return value;
        }

        return handlers.resolve(new this(INTERNAL), value);
      }

      Promise.reject = reject;

      function reject(reason) {
        var promise = new this(INTERNAL);
        return handlers.reject(promise, reason);
      }

      Promise.all = all;

      function all(iterable) {
        var self = this;

        if (Object.prototype.toString.call(iterable) !== '[object Array]') {
          return this.reject(new TypeError('must be an array'));
        }

        var len = iterable.length;
        var called = false;

        if (!len) {
          return this.resolve([]);
        }

        var values = new Array(len);
        var resolved = 0;
        var i = -1;
        var promise = new this(INTERNAL);

        while (++i < len) {
          allResolver(iterable[i], i);
        }

        return promise;

        function allResolver(value, i) {
          self.resolve(value).then(resolveFromAll, function (error) {
            if (!called) {
              called = true;
              handlers.reject(promise, error);
            }
          });

          function resolveFromAll(outValue) {
            values[i] = outValue;

            if (++resolved === len && !called) {
              called = true;
              handlers.resolve(promise, values);
            }
          }
        }
      }

      Promise.race = race;

      function race(iterable) {
        var self = this;

        if (Object.prototype.toString.call(iterable) !== '[object Array]') {
          return this.reject(new TypeError('must be an array'));
        }

        var len = iterable.length;
        var called = false;

        if (!len) {
          return this.resolve([]);
        }

        var i = -1;
        var promise = new this(INTERNAL);

        while (++i < len) {
          resolver(iterable[i]);
        }

        return promise;

        function resolver(value) {
          self.resolve(value).then(function (response) {
            if (!called) {
              called = true;
              handlers.resolve(promise, response);
            }
          }, function (error) {
            if (!called) {
              called = true;
              handlers.reject(promise, error);
            }
          });
        }
      }
    }, {
      "1": 1
    }],
    3: [function (_dereq_, module, exports) {
      (function (global) {
        'use strict';

        if (typeof global.Promise !== 'function') {
          global.Promise = _dereq_(2);
        }
      }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
    }, {
      "2": 2
    }],
    4: [function (_dereq_, module, exports) {
      'use strict';

      var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
        return typeof obj;
      } : function (obj) {
        return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
      };

      function _classCallCheck(instance, Constructor) {
        if (!(instance instanceof Constructor)) {
          throw new TypeError("Cannot call a class as a function");
        }
      }

      function getIDB() {
        /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */
        try {
          if (typeof indexedDB !== 'undefined') {
            return indexedDB;
          }

          if (typeof webkitIndexedDB !== 'undefined') {
            return webkitIndexedDB;
          }

          if (typeof mozIndexedDB !== 'undefined') {
            return mozIndexedDB;
          }

          if (typeof OIndexedDB !== 'undefined') {
            return OIndexedDB;
          }

          if (typeof msIndexedDB !== 'undefined') {
            return msIndexedDB;
          }
        } catch (e) {
          return;
        }
      }

      var idb = getIDB();

      function isIndexedDBValid() {
        try {
          // Initialize IndexedDB; fall back to vendor-prefixed versions
          // if needed.
          if (!idb || !idb.open) {
            return false;
          } // We mimic PouchDB here;
          //
          // We test for openDatabase because IE Mobile identifies itself
          // as Safari. Oh the lulz...


          var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
          var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1; // Safari <10.1 does not meet our requirements for IDB support
          // (see: https://github.com/pouchdb/pouchdb/issues/5572).
          // Safari 10.1 shipped with fetch, we can use that to detect it.
          // Note: this creates issues with `window.fetch` polyfills and
          // overrides; see:
          // https://github.com/localForage/localForage/issues/856

          return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' && // some outdated implementations of IDB that appear on Samsung
          // and HTC Android devices <4.4 are missing IDBKeyRange
          // See: https://github.com/mozilla/localForage/issues/128
          // See: https://github.com/mozilla/localForage/issues/272
          typeof IDBKeyRange !== 'undefined';
        } catch (e) {
          return false;
        }
      } // Abstracts constructing a Blob object, so it also works in older
      // browsers that don't support the native Blob constructor. (i.e.
      // old QtWebKit versions, at least).
      // Abstracts constructing a Blob object, so it also works in older
      // browsers that don't support the native Blob constructor. (i.e.
      // old QtWebKit versions, at least).


      function createBlob(parts, properties) {
        /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
        parts = parts || [];
        properties = properties || {};

        try {
          return new Blob(parts, properties);
        } catch (e) {
          if (e.name !== 'TypeError') {
            throw e;
          }

          var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
          var builder = new Builder();

          for (var i = 0; i < parts.length; i += 1) {
            builder.append(parts[i]);
          }

          return builder.getBlob(properties.type);
        }
      } // This is CommonJS because lie is an external dependency, so Rollup
      // can just ignore it.


      if (typeof Promise === 'undefined') {
        // In the "nopromises" build this will just throw if you don't have
        // a global promise object, but it would throw anyway later.
        _dereq_(3);
      }

      var Promise$1 = Promise;

      function executeCallback(promise, callback) {
        if (callback) {
          promise.then(function (result) {
            callback(null, result);
          }, function (error) {
            callback(error);
          });
        }
      }

      function executeTwoCallbacks(promise, callback, errorCallback) {
        if (typeof callback === 'function') {
          promise.then(callback);
        }

        if (typeof errorCallback === 'function') {
          promise["catch"](errorCallback);
        }
      }

      function normalizeKey(key) {
        // Cast the key to a string, as that's all we can set as a key.
        if (typeof key !== 'string') {
          console.warn(key + ' used as a key, but it is not a string.');
          key = String(key);
        }

        return key;
      }

      function getCallback() {
        if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
          return arguments[arguments.length - 1];
        }
      } // Some code originally from async_storage.js in
      // [Gaia](https://github.com/mozilla-b2g/gaia).


      var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
      var supportsBlobs = void 0;
      var dbContexts = {};
      var toString = Object.prototype.toString; // Transaction Modes

      var READ_ONLY = 'readonly';
      var READ_WRITE = 'readwrite'; // Transform a binary string to an array buffer, because otherwise
      // weird stuff happens when you try to work with the binary string directly.
      // It is known.
      // From http://stackoverflow.com/questions/14967647/ (continues on next line)
      // encode-decode-image-with-base64-breaks-image (2013-04-21)

      function _binStringToArrayBuffer(bin) {
        var length = bin.length;
        var buf = new ArrayBuffer(length);
        var arr = new Uint8Array(buf);

        for (var i = 0; i < length; i++) {
          arr[i] = bin.charCodeAt(i);
        }

        return buf;
      } //
      // Blobs are not supported in all versions of IndexedDB, notably
      // Chrome <37 and Android <5. In those versions, storing a blob will throw.
      //
      // Various other blob bugs exist in Chrome v37-42 (inclusive).
      // Detecting them is expensive and confusing to users, and Chrome 37-42
      // is at very low usage worldwide, so we do a hacky userAgent check instead.
      //
      // content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
      // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
      // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
      //
      // Code borrowed from PouchDB. See:
      // https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js
      //


      function _checkBlobSupportWithoutCaching(idb) {
        return new Promise$1(function (resolve) {
          var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
          var blob = createBlob(['']);
          txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');

          txn.onabort = function (e) {
            // If the transaction aborts now its due to not being able to
            // write to the database, likely due to the disk being full
            e.preventDefault();
            e.stopPropagation();
            resolve(false);
          };

          txn.oncomplete = function () {
            var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
            var matchedEdge = navigator.userAgent.match(/Edge\//); // MS Edge pretends to be Chrome 42:
            // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx

            resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
          };
        })["catch"](function () {
          return false; // error, so assume unsupported
        });
      }

      function _checkBlobSupport(idb) {
        if (typeof supportsBlobs === 'boolean') {
          return Promise$1.resolve(supportsBlobs);
        }

        return _checkBlobSupportWithoutCaching(idb).then(function (value) {
          supportsBlobs = value;
          return supportsBlobs;
        });
      }

      function _deferReadiness(dbInfo) {
        var dbContext = dbContexts[dbInfo.name]; // Create a deferred object representing the current database operation.

        var deferredOperation = {};
        deferredOperation.promise = new Promise$1(function (resolve, reject) {
          deferredOperation.resolve = resolve;
          deferredOperation.reject = reject;
        }); // Enqueue the deferred operation.

        dbContext.deferredOperations.push(deferredOperation); // Chain its promise to the database readiness.

        if (!dbContext.dbReady) {
          dbContext.dbReady = deferredOperation.promise;
        } else {
          dbContext.dbReady = dbContext.dbReady.then(function () {
            return deferredOperation.promise;
          });
        }
      }

      function _advanceReadiness(dbInfo) {
        var dbContext = dbContexts[dbInfo.name]; // Dequeue a deferred operation.

        var deferredOperation = dbContext.deferredOperations.pop(); // Resolve its promise (which is part of the database readiness
        // chain of promises).

        if (deferredOperation) {
          deferredOperation.resolve();
          return deferredOperation.promise;
        }
      }

      function _rejectReadiness(dbInfo, err) {
        var dbContext = dbContexts[dbInfo.name]; // Dequeue a deferred operation.

        var deferredOperation = dbContext.deferredOperations.pop(); // Reject its promise (which is part of the database readiness
        // chain of promises).

        if (deferredOperation) {
          deferredOperation.reject(err);
          return deferredOperation.promise;
        }
      }

      function _getConnection(dbInfo, upgradeNeeded) {
        return new Promise$1(function (resolve, reject) {
          dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();

          if (dbInfo.db) {
            if (upgradeNeeded) {
              _deferReadiness(dbInfo);

              dbInfo.db.close();
            } else {
              return resolve(dbInfo.db);
            }
          }

          var dbArgs = [dbInfo.name];

          if (upgradeNeeded) {
            dbArgs.push(dbInfo.version);
          }

          var openreq = idb.open.apply(idb, dbArgs);

          if (upgradeNeeded) {
            openreq.onupgradeneeded = function (e) {
              var db = openreq.result;

              try {
                db.createObjectStore(dbInfo.storeName);

                if (e.oldVersion <= 1) {
                  // Added when support for blob shims was added
                  db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
                }
              } catch (ex) {
                if (ex.name === 'ConstraintError') {
                  console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
                } else {
                  throw ex;
                }
              }
            };
          }

          openreq.onerror = function (e) {
            e.preventDefault();
            reject(openreq.error);
          };

          openreq.onsuccess = function () {
            resolve(openreq.result);

            _advanceReadiness(dbInfo);
          };
        });
      }

      function _getOriginalConnection(dbInfo) {
        return _getConnection(dbInfo, false);
      }

      function _getUpgradedConnection(dbInfo) {
        return _getConnection(dbInfo, true);
      }

      function _isUpgradeNeeded(dbInfo, defaultVersion) {
        if (!dbInfo.db) {
          return true;
        }

        var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
        var isDowngrade = dbInfo.version < dbInfo.db.version;
        var isUpgrade = dbInfo.version > dbInfo.db.version;

        if (isDowngrade) {
          // If the version is not the default one
          // then warn for impossible downgrade.
          if (dbInfo.version !== defaultVersion) {
            console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
          } // Align the versions to prevent errors.


          dbInfo.version = dbInfo.db.version;
        }

        if (isUpgrade || isNewStore) {
          // If the store is new then increment the version (if needed).
          // This will trigger an "upgradeneeded" event which is required
          // for creating a store.
          if (isNewStore) {
            var incVersion = dbInfo.db.version + 1;

            if (incVersion > dbInfo.version) {
              dbInfo.version = incVersion;
            }
          }

          return true;
        }

        return false;
      } // encode a blob for indexeddb engines that don't support blobs


      function _encodeBlob(blob) {
        return new Promise$1(function (resolve, reject) {
          var reader = new FileReader();
          reader.onerror = reject;

          reader.onloadend = function (e) {
            var base64 = btoa(e.target.result || '');
            resolve({
              __local_forage_encoded_blob: true,
              data: base64,
              type: blob.type
            });
          };

          reader.readAsBinaryString(blob);
        });
      } // decode an encoded blob


      function _decodeBlob(encodedBlob) {
        var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));

        return createBlob([arrayBuff], {
          type: encodedBlob.type
        });
      } // is this one of our fancy encoded blobs?


      function _isEncodedBlob(value) {
        return value && value.__local_forage_encoded_blob;
      } // Specialize the default `ready()` function by making it dependent
      // on the current database operations. Thus, the driver will be actually
      // ready when it's been initialized (default) *and* there are no pending
      // operations on the database (initiated by some other instances).


      function _fullyReady(callback) {
        var self = this;

        var promise = self._initReady().then(function () {
          var dbContext = dbContexts[self._dbInfo.name];

          if (dbContext && dbContext.dbReady) {
            return dbContext.dbReady;
          }
        });

        executeTwoCallbacks(promise, callback, callback);
        return promise;
      } // Try to establish a new db connection to replace the
      // current one which is broken (i.e. experiencing
      // InvalidStateError while creating a transaction).


      function _tryReconnect(dbInfo) {
        _deferReadiness(dbInfo);

        var dbContext = dbContexts[dbInfo.name];
        var forages = dbContext.forages;

        for (var i = 0; i < forages.length; i++) {
          var forage = forages[i];

          if (forage._dbInfo.db) {
            forage._dbInfo.db.close();

            forage._dbInfo.db = null;
          }
        }

        dbInfo.db = null;
        return _getOriginalConnection(dbInfo).then(function (db) {
          dbInfo.db = db;

          if (_isUpgradeNeeded(dbInfo)) {
            // Reopen the database for upgrading.
            return _getUpgradedConnection(dbInfo);
          }

          return db;
        }).then(function (db) {
          // store the latest db reference
          // in case the db was upgraded
          dbInfo.db = dbContext.db = db;

          for (var i = 0; i < forages.length; i++) {
            forages[i]._dbInfo.db = db;
          }
        })["catch"](function (err) {
          _rejectReadiness(dbInfo, err);

          throw err;
        });
      } // FF doesn't like Promises (micro-tasks) and IDDB store operations,
      // so we have to do it with callbacks


      function createTransaction(dbInfo, mode, callback, retries) {
        if (retries === undefined) {
          retries = 1;
        }

        try {
          var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
          callback(null, tx);
        } catch (err) {
          if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {
            return Promise$1.resolve().then(function () {
              if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
                // increase the db version, to create the new ObjectStore
                if (dbInfo.db) {
                  dbInfo.version = dbInfo.db.version + 1;
                } // Reopen the database for upgrading.


                return _getUpgradedConnection(dbInfo);
              }
            }).then(function () {
              return _tryReconnect(dbInfo).then(function () {
                createTransaction(dbInfo, mode, callback, retries - 1);
              });
            })["catch"](callback);
          }

          callback(err);
        }
      }

      function createDbContext() {
        return {
          // Running localForages sharing a database.
          forages: [],
          // Shared database.
          db: null,
          // Database readiness (promise).
          dbReady: null,
          // Deferred operations on the database.
          deferredOperations: []
        };
      } // Open the IndexedDB database (automatically creates one if one didn't
      // previously exist), using any options set in the config.


      function _initStorage(options) {
        var self = this;
        var dbInfo = {
          db: null
        };

        if (options) {
          for (var i in options) {
            dbInfo[i] = options[i];
          }
        } // Get the current context of the database;


        var dbContext = dbContexts[dbInfo.name]; // ...or create a new context.

        if (!dbContext) {
          dbContext = createDbContext(); // Register the new context in the global container.

          dbContexts[dbInfo.name] = dbContext;
        } // Register itself as a running localForage in the current context.


        dbContext.forages.push(self); // Replace the default `ready()` function with the specialized one.

        if (!self._initReady) {
          self._initReady = self.ready;
          self.ready = _fullyReady;
        } // Create an array of initialization states of the related localForages.


        var initPromises = [];

        function ignoreErrors() {
          // Don't handle errors here,
          // just makes sure related localForages aren't pending.
          return Promise$1.resolve();
        }

        for (var j = 0; j < dbContext.forages.length; j++) {
          var forage = dbContext.forages[j];

          if (forage !== self) {
            // Don't wait for itself...
            initPromises.push(forage._initReady()["catch"](ignoreErrors));
          }
        } // Take a snapshot of the related localForages.


        var forages = dbContext.forages.slice(0); // Initialize the connection process only when
        // all the related localForages aren't pending.

        return Promise$1.all(initPromises).then(function () {
          dbInfo.db = dbContext.db; // Get the connection or open a new one without upgrade.

          return _getOriginalConnection(dbInfo);
        }).then(function (db) {
          dbInfo.db = db;

          if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
            // Reopen the database for upgrading.
            return _getUpgradedConnection(dbInfo);
          }

          return db;
        }).then(function (db) {
          dbInfo.db = dbContext.db = db;
          self._dbInfo = dbInfo; // Share the final connection amongst related localForages.

          for (var k = 0; k < forages.length; k++) {
            var forage = forages[k];

            if (forage !== self) {
              // Self is already up-to-date.
              forage._dbInfo.db = dbInfo.db;
              forage._dbInfo.version = dbInfo.version;
            }
          }
        });
      }

      function getItem(key, callback) {
        var self = this;
        key = normalizeKey(key);
        var promise = new Promise$1(function (resolve, reject) {
          self.ready().then(function () {
            createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
              if (err) {
                return reject(err);
              }

              try {
                var store = transaction.objectStore(self._dbInfo.storeName);
                var req = store.get(key);

                req.onsuccess = function () {
                  var value = req.result;

                  if (value === undefined) {
                    value = null;
                  }

                  if (_isEncodedBlob(value)) {
                    value = _decodeBlob(value);
                  }

                  resolve(value);
                };

                req.onerror = function () {
                  reject(req.error);
                };
              } catch (e) {
                reject(e);
              }
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      } // Iterate over all items stored in database.


      function iterate(iterator, callback) {
        var self = this;
        var promise = new Promise$1(function (resolve, reject) {
          self.ready().then(function () {
            createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
              if (err) {
                return reject(err);
              }

              try {
                var store = transaction.objectStore(self._dbInfo.storeName);
                var req = store.openCursor();
                var iterationNumber = 1;

                req.onsuccess = function () {
                  var cursor = req.result;

                  if (cursor) {
                    var value = cursor.value;

                    if (_isEncodedBlob(value)) {
                      value = _decodeBlob(value);
                    }

                    var result = iterator(value, cursor.key, iterationNumber++); // when the iterator callback returns any
                    // (non-`undefined`) value, then we stop
                    // the iteration immediately

                    if (result !== void 0) {
                      resolve(result);
                    } else {
                      cursor["continue"]();
                    }
                  } else {
                    resolve();
                  }
                };

                req.onerror = function () {
                  reject(req.error);
                };
              } catch (e) {
                reject(e);
              }
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      }

      function setItem(key, value, callback) {
        var self = this;
        key = normalizeKey(key);
        var promise = new Promise$1(function (resolve, reject) {
          var dbInfo;
          self.ready().then(function () {
            dbInfo = self._dbInfo;

            if (toString.call(value) === '[object Blob]') {
              return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
                if (blobSupport) {
                  return value;
                }

                return _encodeBlob(value);
              });
            }

            return value;
          }).then(function (value) {
            createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
              if (err) {
                return reject(err);
              }

              try {
                var store = transaction.objectStore(self._dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does
                // not support saving the `null` type in IndexedDB. How
                // ironic, given the bug below!
                // See: https://github.com/mozilla/localForage/issues/161

                if (value === null) {
                  value = undefined;
                }

                var req = store.put(value, key);

                transaction.oncomplete = function () {
                  // Cast to undefined so the value passed to
                  // callback/promise is the same as what one would get out
                  // of `getItem()` later. This leads to some weirdness
                  // (setItem('foo', undefined) will return `null`), but
                  // it's not my fault localStorage is our baseline and that
                  // it's weird.
                  if (value === undefined) {
                    value = null;
                  }

                  resolve(value);
                };

                transaction.onabort = transaction.onerror = function () {
                  var err = req.error ? req.error : req.transaction.error;
                  reject(err);
                };
              } catch (e) {
                reject(e);
              }
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      }

      function removeItem(key, callback) {
        var self = this;
        key = normalizeKey(key);
        var promise = new Promise$1(function (resolve, reject) {
          self.ready().then(function () {
            createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
              if (err) {
                return reject(err);
              }

              try {
                var store = transaction.objectStore(self._dbInfo.storeName); // We use a Grunt task to make this safe for IE and some
                // versions of Android (including those used by Cordova).
                // Normally IE won't like `.delete()` and will insist on
                // using `['delete']()`, but we have a build step that
                // fixes this for us now.

                var req = store["delete"](key);

                transaction.oncomplete = function () {
                  resolve();
                };

                transaction.onerror = function () {
                  reject(req.error);
                }; // The request will be also be aborted if we've exceeded our storage
                // space.


                transaction.onabort = function () {
                  var err = req.error ? req.error : req.transaction.error;
                  reject(err);
                };
              } catch (e) {
                reject(e);
              }
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      }

      function clear(callback) {
        var self = this;
        var promise = new Promise$1(function (resolve, reject) {
          self.ready().then(function () {
            createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
              if (err) {
                return reject(err);
              }

              try {
                var store = transaction.objectStore(self._dbInfo.storeName);
                var req = store.clear();

                transaction.oncomplete = function () {
                  resolve();
                };

                transaction.onabort = transaction.onerror = function () {
                  var err = req.error ? req.error : req.transaction.error;
                  reject(err);
                };
              } catch (e) {
                reject(e);
              }
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      }

      function length(callback) {
        var self = this;
        var promise = new Promise$1(function (resolve, reject) {
          self.ready().then(function () {
            createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
              if (err) {
                return reject(err);
              }

              try {
                var store = transaction.objectStore(self._dbInfo.storeName);
                var req = store.count();

                req.onsuccess = function () {
                  resolve(req.result);
                };

                req.onerror = function () {
                  reject(req.error);
                };
              } catch (e) {
                reject(e);
              }
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      }

      function key(n, callback) {
        var self = this;
        var promise = new Promise$1(function (resolve, reject) {
          if (n < 0) {
            resolve(null);
            return;
          }

          self.ready().then(function () {
            createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
              if (err) {
                return reject(err);
              }

              try {
                var store = transaction.objectStore(self._dbInfo.storeName);
                var advanced = false;
                var req = store.openKeyCursor();

                req.onsuccess = function () {
                  var cursor = req.result;

                  if (!cursor) {
                    // this means there weren't enough keys
                    resolve(null);
                    return;
                  }

                  if (n === 0) {
                    // We have the first key, return it if that's what they
                    // wanted.
                    resolve(cursor.key);
                  } else {
                    if (!advanced) {
                      // Otherwise, ask the cursor to skip ahead n
                      // records.
                      advanced = true;
                      cursor.advance(n);
                    } else {
                      // When we get here, we've got the nth key.
                      resolve(cursor.key);
                    }
                  }
                };

                req.onerror = function () {
                  reject(req.error);
                };
              } catch (e) {
                reject(e);
              }
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      }

      function keys(callback) {
        var self = this;
        var promise = new Promise$1(function (resolve, reject) {
          self.ready().then(function () {
            createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
              if (err) {
                return reject(err);
              }

              try {
                var store = transaction.objectStore(self._dbInfo.storeName);
                var req = store.openKeyCursor();
                var keys = [];

                req.onsuccess = function () {
                  var cursor = req.result;

                  if (!cursor) {
                    resolve(keys);
                    return;
                  }

                  keys.push(cursor.key);
                  cursor["continue"]();
                };

                req.onerror = function () {
                  reject(req.error);
                };
              } catch (e) {
                reject(e);
              }
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      }

      function dropInstance(options, callback) {
        callback = getCallback.apply(this, arguments);
        var currentConfig = this.config();
        options = typeof options !== 'function' && options || {};

        if (!options.name) {
          options.name = options.name || currentConfig.name;
          options.storeName = options.storeName || currentConfig.storeName;
        }

        var self = this;
        var promise;

        if (!options.name) {
          promise = Promise$1.reject('Invalid arguments');
        } else {
          var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;
          var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {
            var dbContext = dbContexts[options.name];
            var forages = dbContext.forages;
            dbContext.db = db;

            for (var i = 0; i < forages.length; i++) {
              forages[i]._dbInfo.db = db;
            }

            return db;
          });

          if (!options.storeName) {
            promise = dbPromise.then(function (db) {
              _deferReadiness(options);

              var dbContext = dbContexts[options.name];
              var forages = dbContext.forages;
              db.close();

              for (var i = 0; i < forages.length; i++) {
                var forage = forages[i];
                forage._dbInfo.db = null;
              }

              var dropDBPromise = new Promise$1(function (resolve, reject) {
                var req = idb.deleteDatabase(options.name);

                req.onerror = req.onblocked = function (err) {
                  var db = req.result;

                  if (db) {
                    db.close();
                  }

                  reject(err);
                };

                req.onsuccess = function () {
                  var db = req.result;

                  if (db) {
                    db.close();
                  }

                  resolve(db);
                };
              });
              return dropDBPromise.then(function (db) {
                dbContext.db = db;

                for (var i = 0; i < forages.length; i++) {
                  var _forage = forages[i];

                  _advanceReadiness(_forage._dbInfo);
                }
              })["catch"](function (err) {
                (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
                throw err;
              });
            });
          } else {
            promise = dbPromise.then(function (db) {
              if (!db.objectStoreNames.contains(options.storeName)) {
                return;
              }

              var newVersion = db.version + 1;

              _deferReadiness(options);

              var dbContext = dbContexts[options.name];
              var forages = dbContext.forages;
              db.close();

              for (var i = 0; i < forages.length; i++) {
                var forage = forages[i];
                forage._dbInfo.db = null;
                forage._dbInfo.version = newVersion;
              }

              var dropObjectPromise = new Promise$1(function (resolve, reject) {
                var req = idb.open(options.name, newVersion);

                req.onerror = function (err) {
                  var db = req.result;
                  db.close();
                  reject(err);
                };

                req.onupgradeneeded = function () {
                  var db = req.result;
                  db.deleteObjectStore(options.storeName);
                };

                req.onsuccess = function () {
                  var db = req.result;
                  db.close();
                  resolve(db);
                };
              });
              return dropObjectPromise.then(function (db) {
                dbContext.db = db;

                for (var j = 0; j < forages.length; j++) {
                  var _forage2 = forages[j];
                  _forage2._dbInfo.db = db;

                  _advanceReadiness(_forage2._dbInfo);
                }
              })["catch"](function (err) {
                (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
                throw err;
              });
            });
          }
        }

        executeCallback(promise, callback);
        return promise;
      }

      var asyncStorage = {
        _driver: 'asyncStorage',
        _initStorage: _initStorage,
        _support: isIndexedDBValid(),
        iterate: iterate,
        getItem: getItem,
        setItem: setItem,
        removeItem: removeItem,
        clear: clear,
        length: length,
        key: key,
        keys: keys,
        dropInstance: dropInstance
      };

      function isWebSQLValid() {
        return typeof openDatabase === 'function';
      } // Sadly, the best way to save binary data in WebSQL/localStorage is serializing
      // it to Base64, so this is how we store it to prevent very strange errors with less
      // verbose ways of binary <-> string data storage.


      var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
      var BLOB_TYPE_PREFIX = '~~local_forage_type~';
      var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
      var SERIALIZED_MARKER = '__lfsc__:';
      var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations!

      var TYPE_ARRAYBUFFER = 'arbf';
      var TYPE_BLOB = 'blob';
      var TYPE_INT8ARRAY = 'si08';
      var TYPE_UINT8ARRAY = 'ui08';
      var TYPE_UINT8CLAMPEDARRAY = 'uic8';
      var TYPE_INT16ARRAY = 'si16';
      var TYPE_INT32ARRAY = 'si32';
      var TYPE_UINT16ARRAY = 'ur16';
      var TYPE_UINT32ARRAY = 'ui32';
      var TYPE_FLOAT32ARRAY = 'fl32';
      var TYPE_FLOAT64ARRAY = 'fl64';
      var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
      var toString$1 = Object.prototype.toString;

      function stringToBuffer(serializedString) {
        // Fill the string into a ArrayBuffer.
        var bufferLength = serializedString.length * 0.75;
        var len = serializedString.length;
        var i;
        var p = 0;
        var encoded1, encoded2, encoded3, encoded4;

        if (serializedString[serializedString.length - 1] === '=') {
          bufferLength--;

          if (serializedString[serializedString.length - 2] === '=') {
            bufferLength--;
          }
        }

        var buffer = new ArrayBuffer(bufferLength);
        var bytes = new Uint8Array(buffer);

        for (i = 0; i < len; i += 4) {
          encoded1 = BASE_CHARS.indexOf(serializedString[i]);
          encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
          encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
          encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
          /*jslint bitwise: true */

          bytes[p++] = encoded1 << 2 | encoded2 >> 4;
          bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
          bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
        }

        return buffer;
      } // Converts a buffer to a string to store, serialized, in the backend
      // storage library.


      function bufferToString(buffer) {
        // base64-arraybuffer
        var bytes = new Uint8Array(buffer);
        var base64String = '';
        var i;

        for (i = 0; i < bytes.length; i += 3) {
          /*jslint bitwise: true */
          base64String += BASE_CHARS[bytes[i] >> 2];
          base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
          base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
          base64String += BASE_CHARS[bytes[i + 2] & 63];
        }

        if (bytes.length % 3 === 2) {
          base64String = base64String.substring(0, base64String.length - 1) + '=';
        } else if (bytes.length % 3 === 1) {
          base64String = base64String.substring(0, base64String.length - 2) + '==';
        }

        return base64String;
      } // Serialize a value, afterwards executing a callback (which usually
      // instructs the `setItem()` callback/promise to be executed). This is how
      // we store binary data with localStorage.


      function serialize(value, callback) {
        var valueType = '';

        if (value) {
          valueType = toString$1.call(value);
        } // Cannot use `value instanceof ArrayBuffer` or such here, as these
        // checks fail when running the tests using casper.js...
        //
        // TODO: See why those tests fail and use a better solution.


        if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {
          // Convert binary arrays to a string and prefix the string with
          // a special marker.
          var buffer;
          var marker = SERIALIZED_MARKER;

          if (value instanceof ArrayBuffer) {
            buffer = value;
            marker += TYPE_ARRAYBUFFER;
          } else {
            buffer = value.buffer;

            if (valueType === '[object Int8Array]') {
              marker += TYPE_INT8ARRAY;
            } else if (valueType === '[object Uint8Array]') {
              marker += TYPE_UINT8ARRAY;
            } else if (valueType === '[object Uint8ClampedArray]') {
              marker += TYPE_UINT8CLAMPEDARRAY;
            } else if (valueType === '[object Int16Array]') {
              marker += TYPE_INT16ARRAY;
            } else if (valueType === '[object Uint16Array]') {
              marker += TYPE_UINT16ARRAY;
            } else if (valueType === '[object Int32Array]') {
              marker += TYPE_INT32ARRAY;
            } else if (valueType === '[object Uint32Array]') {
              marker += TYPE_UINT32ARRAY;
            } else if (valueType === '[object Float32Array]') {
              marker += TYPE_FLOAT32ARRAY;
            } else if (valueType === '[object Float64Array]') {
              marker += TYPE_FLOAT64ARRAY;
            } else {
              callback(new Error('Failed to get type for BinaryArray'));
            }
          }

          callback(marker + bufferToString(buffer));
        } else if (valueType === '[object Blob]') {
          // Conver the blob to a binaryArray and then to a string.
          var fileReader = new FileReader();

          fileReader.onload = function () {
            // Backwards-compatible prefix for the blob type.
            var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
            callback(SERIALIZED_MARKER + TYPE_BLOB + str);
          };

          fileReader.readAsArrayBuffer(value);
        } else {
          try {
            callback(JSON.stringify(value));
          } catch (e) {
            console.error("Couldn't convert value into a JSON string: ", value);
            callback(null, e);
          }
        }
      } // Deserialize data we've inserted into a value column/field. We place
      // special markers into our strings to mark them as encoded; this isn't
      // as nice as a meta field, but it's the only sane thing we can do whilst
      // keeping localStorage support intact.
      //
      // Oftentimes this will just deserialize JSON content, but if we have a
      // special marker (SERIALIZED_MARKER, defined above), we will extract
      // some kind of arraybuffer/binary data/typed array out of the string.


      function deserialize(value) {
        // If we haven't marked this string as being specially serialized (i.e.
        // something other than serialized JSON), we can just return it and be
        // done with it.
        if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
          return JSON.parse(value);
        } // The following code deals with deserializing some kind of Blob or
        // TypedArray. First we separate out the type of data we're dealing
        // with from the data itself.


        var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
        var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
        var blobType; // Backwards-compatible blob type serialization strategy.
        // DBs created with older versions of localForage will simply not have the blob type.

        if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
          var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
          blobType = matcher[1];
          serializedString = serializedString.substring(matcher[0].length);
        }

        var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during
        // serialization.

        switch (type) {
          case TYPE_ARRAYBUFFER:
            return buffer;

          case TYPE_BLOB:
            return createBlob([buffer], {
              type: blobType
            });

          case TYPE_INT8ARRAY:
            return new Int8Array(buffer);

          case TYPE_UINT8ARRAY:
            return new Uint8Array(buffer);

          case TYPE_UINT8CLAMPEDARRAY:
            return new Uint8ClampedArray(buffer);

          case TYPE_INT16ARRAY:
            return new Int16Array(buffer);

          case TYPE_UINT16ARRAY:
            return new Uint16Array(buffer);

          case TYPE_INT32ARRAY:
            return new Int32Array(buffer);

          case TYPE_UINT32ARRAY:
            return new Uint32Array(buffer);

          case TYPE_FLOAT32ARRAY:
            return new Float32Array(buffer);

          case TYPE_FLOAT64ARRAY:
            return new Float64Array(buffer);

          default:
            throw new Error('Unkown type: ' + type);
        }
      }

      var localforageSerializer = {
        serialize: serialize,
        deserialize: deserialize,
        stringToBuffer: stringToBuffer,
        bufferToString: bufferToString
      };
      /*
       * Includes code from:
       *
       * base64-arraybuffer
       * https://github.com/niklasvh/base64-arraybuffer
       *
       * Copyright (c) 2012 Niklas von Hertzen
       * Licensed under the MIT license.
       */

      function createDbTable(t, dbInfo, callback, errorCallback) {
        t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);
      } // Open the WebSQL database (automatically creates one if one didn't
      // previously exist), using any options set in the config.


      function _initStorage$1(options) {
        var self = this;
        var dbInfo = {
          db: null
        };

        if (options) {
          for (var i in options) {
            dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
          }
        }

        var dbInfoPromise = new Promise$1(function (resolve, reject) {
          // Open the database; the openDatabase API will automatically
          // create it for us if it doesn't exist.
          try {
            dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
          } catch (e) {
            return reject(e);
          } // Create our key/value table if it doesn't exist.


          dbInfo.db.transaction(function (t) {
            createDbTable(t, dbInfo, function () {
              self._dbInfo = dbInfo;
              resolve();
            }, function (t, error) {
              reject(error);
            });
          }, reject);
        });
        dbInfo.serializer = localforageSerializer;
        return dbInfoPromise;
      }

      function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {
        t.executeSql(sqlStatement, args, callback, function (t, error) {
          if (error.code === error.SYNTAX_ERR) {
            t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [dbInfo.storeName], function (t, results) {
              if (!results.rows.length) {
                // if the table is missing (was deleted)
                // re-create it table and retry
                createDbTable(t, dbInfo, function () {
                  t.executeSql(sqlStatement, args, callback, errorCallback);
                }, errorCallback);
              } else {
                errorCallback(t, error);
              }
            }, errorCallback);
          } else {
            errorCallback(t, error);
          }
        }, errorCallback);
      }

      function getItem$1(key, callback) {
        var self = this;
        key = normalizeKey(key);
        var promise = new Promise$1(function (resolve, reject) {
          self.ready().then(function () {
            var dbInfo = self._dbInfo;
            dbInfo.db.transaction(function (t) {
              tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
                var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to
                // unpack.

                if (result) {
                  result = dbInfo.serializer.deserialize(result);
                }

                resolve(result);
              }, function (t, error) {
                reject(error);
              });
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      }

      function iterate$1(iterator, callback) {
        var self = this;
        var promise = new Promise$1(function (resolve, reject) {
          self.ready().then(function () {
            var dbInfo = self._dbInfo;
            dbInfo.db.transaction(function (t) {
              tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
                var rows = results.rows;
                var length = rows.length;

                for (var i = 0; i < length; i++) {
                  var item = rows.item(i);
                  var result = item.value; // Check to see if this is serialized content
                  // we need to unpack.

                  if (result) {
                    result = dbInfo.serializer.deserialize(result);
                  }

                  result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition
                  // of `undefined`.

                  if (result !== void 0) {
                    resolve(result);
                    return;
                  }
                }

                resolve();
              }, function (t, error) {
                reject(error);
              });
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      }

      function _setItem(key, value, callback, retriesLeft) {
        var self = this;
        key = normalizeKey(key);
        var promise = new Promise$1(function (resolve, reject) {
          self.ready().then(function () {
            // The localStorage API doesn't return undefined values in an
            // "expected" way, so undefined is always cast to null in all
            // drivers. See: https://github.com/mozilla/localForage/pull/42
            if (value === undefined) {
              value = null;
            } // Save the original value to pass to the callback.


            var originalValue = value;
            var dbInfo = self._dbInfo;
            dbInfo.serializer.serialize(value, function (value, error) {
              if (error) {
                reject(error);
              } else {
                dbInfo.db.transaction(function (t) {
                  tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {
                    resolve(originalValue);
                  }, function (t, error) {
                    reject(error);
                  });
                }, function (sqlError) {
                  // The transaction failed; check
                  // to see if it's a quota error.
                  if (sqlError.code === sqlError.QUOTA_ERR) {
                    // We reject the callback outright for now, but
                    // it's worth trying to re-run the transaction.
                    // Even if the user accepts the prompt to use
                    // more storage on Safari, this error will
                    // be called.
                    //
                    // Try to re-run the transaction.
                    if (retriesLeft > 0) {
                      resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));
                      return;
                    }

                    reject(sqlError);
                  }
                });
              }
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      }

      function setItem$1(key, value, callback) {
        return _setItem.apply(this, [key, value, callback, 1]);
      }

      function removeItem$1(key, callback) {
        var self = this;
        key = normalizeKey(key);
        var promise = new Promise$1(function (resolve, reject) {
          self.ready().then(function () {
            var dbInfo = self._dbInfo;
            dbInfo.db.transaction(function (t) {
              tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
                resolve();
              }, function (t, error) {
                reject(error);
              });
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      } // Deletes every item in the table.
      // TODO: Find out if this resets the AUTO_INCREMENT number.


      function clear$1(callback) {
        var self = this;
        var promise = new Promise$1(function (resolve, reject) {
          self.ready().then(function () {
            var dbInfo = self._dbInfo;
            dbInfo.db.transaction(function (t) {
              tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {
                resolve();
              }, function (t, error) {
                reject(error);
              });
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      } // Does a simple `COUNT(key)` to get the number of items stored in
      // localForage.


      function length$1(callback) {
        var self = this;
        var promise = new Promise$1(function (resolve, reject) {
          self.ready().then(function () {
            var dbInfo = self._dbInfo;
            dbInfo.db.transaction(function (t) {
              // Ahhh, SQL makes this one soooooo easy.
              tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
                var result = results.rows.item(0).c;
                resolve(result);
              }, function (t, error) {
                reject(error);
              });
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      } // Return the key located at key index X; essentially gets the key from a
      // `WHERE id = ?`. This is the most efficient way I can think to implement
      // this rarely-used (in my experience) part of the API, but it can seem
      // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
      // the ID of each key will change every time it's updated. Perhaps a stored
      // procedure for the `setItem()` SQL would solve this problem?
      // TODO: Don't change ID on `setItem()`.


      function key$1(n, callback) {
        var self = this;
        var promise = new Promise$1(function (resolve, reject) {
          self.ready().then(function () {
            var dbInfo = self._dbInfo;
            dbInfo.db.transaction(function (t) {
              tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
                var result = results.rows.length ? results.rows.item(0).key : null;
                resolve(result);
              }, function (t, error) {
                reject(error);
              });
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      }

      function keys$1(callback) {
        var self = this;
        var promise = new Promise$1(function (resolve, reject) {
          self.ready().then(function () {
            var dbInfo = self._dbInfo;
            dbInfo.db.transaction(function (t) {
              tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
                var keys = [];

                for (var i = 0; i < results.rows.length; i++) {
                  keys.push(results.rows.item(i).key);
                }

                resolve(keys);
              }, function (t, error) {
                reject(error);
              });
            });
          })["catch"](reject);
        });
        executeCallback(promise, callback);
        return promise;
      } // https://www.w3.org/TR/webdatabase/#databases
      // > There is no way to enumerate or delete the databases available for an origin from this API.


      function getAllStoreNames(db) {
        return new Promise$1(function (resolve, reject) {
          db.transaction(function (t) {
            t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) {
              var storeNames = [];

              for (var i = 0; i < results.rows.length; i++) {
                storeNames.push(results.rows.item(i).name);
              }

              resolve({
                db: db,
                storeNames: storeNames
              });
            }, function (t, error) {
              reject(error);
            });
          }, function (sqlError) {
            reject(sqlError);
          });
        });
      }

      function dropInstance$1(options, callback) {
        callback = getCallback.apply(this, arguments);
        var currentConfig = this.config();
        options = typeof options !== 'function' && options || {};

        if (!options.name) {
          options.name = options.name || currentConfig.name;
          options.storeName = options.storeName || currentConfig.storeName;
        }

        var self = this;
        var promise;

        if (!options.name) {
          promise = Promise$1.reject('Invalid arguments');
        } else {
          promise = new Promise$1(function (resolve) {
            var db;

            if (options.name === currentConfig.name) {
              // use the db reference of the current instance
              db = self._dbInfo.db;
            } else {
              db = openDatabase(options.name, '', '', 0);
            }

            if (!options.storeName) {
              // drop all database tables
              resolve(getAllStoreNames(db));
            } else {
              resolve({
                db: db,
                storeNames: [options.storeName]
              });
            }
          }).then(function (operationInfo) {
            return new Promise$1(function (resolve, reject) {
              operationInfo.db.transaction(function (t) {
                function dropTable(storeName) {
                  return new Promise$1(function (resolve, reject) {
                    t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {
                      resolve();
                    }, function (t, error) {
                      reject(error);
                    });
                  });
                }

                var operations = [];

                for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {
                  operations.push(dropTable(operationInfo.storeNames[i]));
                }

                Promise$1.all(operations).then(function () {
                  resolve();
                })["catch"](function (e) {
                  reject(e);
                });
              }, function (sqlError) {
                reject(sqlError);
              });
            });
          });
        }

        executeCallback(promise, callback);
        return promise;
      }

      var webSQLStorage = {
        _driver: 'webSQLStorage',
        _initStorage: _initStorage$1,
        _support: isWebSQLValid(),
        iterate: iterate$1,
        getItem: getItem$1,
        setItem: setItem$1,
        removeItem: removeItem$1,
        clear: clear$1,
        length: length$1,
        key: key$1,
        keys: keys$1,
        dropInstance: dropInstance$1
      };

      function isLocalStorageValid() {
        try {
          return typeof localStorage !== 'undefined' && 'setItem' in localStorage && // in IE8 typeof localStorage.setItem === 'object'
          !!localStorage.setItem;
        } catch (e) {
          return false;
        }
      }

      function _getKeyPrefix(options, defaultConfig) {
        var keyPrefix = options.name + '/';

        if (options.storeName !== defaultConfig.storeName) {
          keyPrefix += options.storeName + '/';
        }

        return keyPrefix;
      } // Check if localStorage throws when saving an item


      function checkIfLocalStorageThrows() {
        var localStorageTestKey = '_localforage_support_test';

        try {
          localStorage.setItem(localStorageTestKey, true);
          localStorage.removeItem(localStorageTestKey);
          return false;
        } catch (e) {
          return true;
        }
      } // Check if localStorage is usable and allows to save an item
      // This method checks if localStorage is usable in Safari Private Browsing
      // mode, or in any other case where the available quota for localStorage
      // is 0 and there wasn't any saved items yet.


      function _isLocalStorageUsable() {
        return !checkIfLocalStorageThrows() || localStorage.length > 0;
      } // Config the localStorage backend, using options set in the config.


      function _initStorage$2(options) {
        var self = this;
        var dbInfo = {};

        if (options) {
          for (var i in options) {
            dbInfo[i] = options[i];
          }
        }

        dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);

        if (!_isLocalStorageUsable()) {
          return Promise$1.reject();
        }

        self._dbInfo = dbInfo;
        dbInfo.serializer = localforageSerializer;
        return Promise$1.resolve();
      } // Remove all keys from the datastore, effectively destroying all data in
      // the app's key/value store!


      function clear$2(callback) {
        var self = this;
        var promise = self.ready().then(function () {
          var keyPrefix = self._dbInfo.keyPrefix;

          for (var i = localStorage.length - 1; i >= 0; i--) {
            var key = localStorage.key(i);

            if (key.indexOf(keyPrefix) === 0) {
              localStorage.removeItem(key);
            }
          }
        });
        executeCallback(promise, callback);
        return promise;
      } // Retrieve an item from the store. Unlike the original async_storage
      // library in Gaia, we don't modify return values at all. If a key's value
      // is `undefined`, we pass that value to the callback function.


      function getItem$2(key, callback) {
        var self = this;
        key = normalizeKey(key);
        var promise = self.ready().then(function () {
          var dbInfo = self._dbInfo;
          var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized
          // string into a JS object. If result isn't truthy, the key
          // is likely undefined and we'll pass it straight to the
          // callback.

          if (result) {
            result = dbInfo.serializer.deserialize(result);
          }

          return result;
        });
        executeCallback(promise, callback);
        return promise;
      } // Iterate over all items in the store.


      function iterate$2(iterator, callback) {
        var self = this;
        var promise = self.ready().then(function () {
          var dbInfo = self._dbInfo;
          var keyPrefix = dbInfo.keyPrefix;
          var keyPrefixLength = keyPrefix.length;
          var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below
          // so other keys we fetch in localStorage aren't counted in
          // the `iterationNumber` argument passed to the `iterate()`
          // callback.
          //
          // See: github.com/mozilla/localForage/pull/435#discussion_r38061530

          var iterationNumber = 1;

          for (var i = 0; i < length; i++) {
            var key = localStorage.key(i);

            if (key.indexOf(keyPrefix) !== 0) {
              continue;
            }

            var value = localStorage.getItem(key); // If a result was found, parse it from the serialized
            // string into a JS object. If result isn't truthy, the
            // key is likely undefined and we'll pass it straight
            // to the iterator.

            if (value) {
              value = dbInfo.serializer.deserialize(value);
            }

            value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);

            if (value !== void 0) {
              return value;
            }
          }
        });
        executeCallback(promise, callback);
        return promise;
      } // Same as localStorage's key() method, except takes a callback.


      function key$2(n, callback) {
        var self = this;
        var promise = self.ready().then(function () {
          var dbInfo = self._dbInfo;
          var result;

          try {
            result = localStorage.key(n);
          } catch (error) {
            result = null;
          } // Remove the prefix from the key, if a key is found.


          if (result) {
            result = result.substring(dbInfo.keyPrefix.length);
          }

          return result;
        });
        executeCallback(promise, callback);
        return promise;
      }

      function keys$2(callback) {
        var self = this;
        var promise = self.ready().then(function () {
          var dbInfo = self._dbInfo;
          var length = localStorage.length;
          var keys = [];

          for (var i = 0; i < length; i++) {
            var itemKey = localStorage.key(i);

            if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
              keys.push(itemKey.substring(dbInfo.keyPrefix.length));
            }
          }

          return keys;
        });
        executeCallback(promise, callback);
        return promise;
      } // Supply the number of keys in the datastore to the callback function.


      function length$2(callback) {
        var self = this;
        var promise = self.keys().then(function (keys) {
          return keys.length;
        });
        executeCallback(promise, callback);
        return promise;
      } // Remove an item from the store, nice and simple.


      function removeItem$2(key, callback) {
        var self = this;
        key = normalizeKey(key);
        var promise = self.ready().then(function () {
          var dbInfo = self._dbInfo;
          localStorage.removeItem(dbInfo.keyPrefix + key);
        });
        executeCallback(promise, callback);
        return promise;
      } // Set a key's value and run an optional callback once the value is set.
      // Unlike Gaia's implementation, the callback function is passed the value,
      // in case you want to operate on that value only after you're sure it
      // saved, or something like that.


      function setItem$2(key, value, callback) {
        var self = this;
        key = normalizeKey(key);
        var promise = self.ready().then(function () {
          // Convert undefined values to null.
          // https://github.com/mozilla/localForage/pull/42
          if (value === undefined) {
            value = null;
          } // Save the original value to pass to the callback.


          var originalValue = value;
          return new Promise$1(function (resolve, reject) {
            var dbInfo = self._dbInfo;
            dbInfo.serializer.serialize(value, function (value, error) {
              if (error) {
                reject(error);
              } else {
                try {
                  localStorage.setItem(dbInfo.keyPrefix + key, value);
                  resolve(originalValue);
                } catch (e) {
                  // localStorage capacity exceeded.
                  // TODO: Make this a specific error/event.
                  if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
                    reject(e);
                  }

                  reject(e);
                }
              }
            });
          });
        });
        executeCallback(promise, callback);
        return promise;
      }

      function dropInstance$2(options, callback) {
        callback = getCallback.apply(this, arguments);
        options = typeof options !== 'function' && options || {};

        if (!options.name) {
          var currentConfig = this.config();
          options.name = options.name || currentConfig.name;
          options.storeName = options.storeName || currentConfig.storeName;
        }

        var self = this;
        var promise;

        if (!options.name) {
          promise = Promise$1.reject('Invalid arguments');
        } else {
          promise = new Promise$1(function (resolve) {
            if (!options.storeName) {
              resolve(options.name + '/');
            } else {
              resolve(_getKeyPrefix(options, self._defaultConfig));
            }
          }).then(function (keyPrefix) {
            for (var i = localStorage.length - 1; i >= 0; i--) {
              var key = localStorage.key(i);

              if (key.indexOf(keyPrefix) === 0) {
                localStorage.removeItem(key);
              }
            }
          });
        }

        executeCallback(promise, callback);
        return promise;
      }

      var localStorageWrapper = {
        _driver: 'localStorageWrapper',
        _initStorage: _initStorage$2,
        _support: isLocalStorageValid(),
        iterate: iterate$2,
        getItem: getItem$2,
        setItem: setItem$2,
        removeItem: removeItem$2,
        clear: clear$2,
        length: length$2,
        key: key$2,
        keys: keys$2,
        dropInstance: dropInstance$2
      };

      var sameValue = function sameValue(x, y) {
        return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);
      };

      var includes = function includes(array, searchElement) {
        var len = array.length;
        var i = 0;

        while (i < len) {
          if (sameValue(array[i], searchElement)) {
            return true;
          }

          i++;
        }

        return false;
      };

      var isArray = Array.isArray || function (arg) {
        return Object.prototype.toString.call(arg) === '[object Array]';
      }; // Drivers are stored here when `defineDriver()` is called.
      // They are shared across all instances of localForage.


      var DefinedDrivers = {};
      var DriverSupport = {};
      var DefaultDrivers = {
        INDEXEDDB: asyncStorage,
        WEBSQL: webSQLStorage,
        LOCALSTORAGE: localStorageWrapper
      };
      var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];
      var OptionalDriverMethods = ['dropInstance'];
      var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);
      var DefaultConfig = {
        description: '',
        driver: DefaultDriverOrder.slice(),
        name: 'localforage',
        // Default DB size is _JUST UNDER_ 5MB, as it's the highest size
        // we can use without a prompt.
        size: 4980736,
        storeName: 'keyvaluepairs',
        version: 1.0
      };

      function callWhenReady(localForageInstance, libraryMethod) {
        localForageInstance[libraryMethod] = function () {
          var _args = arguments;
          return localForageInstance.ready().then(function () {
            return localForageInstance[libraryMethod].apply(localForageInstance, _args);
          });
        };
      }

      function extend() {
        for (var i = 1; i < arguments.length; i++) {
          var arg = arguments[i];

          if (arg) {
            for (var _key in arg) {
              if (arg.hasOwnProperty(_key)) {
                if (isArray(arg[_key])) {
                  arguments[0][_key] = arg[_key].slice();
                } else {
                  arguments[0][_key] = arg[_key];
                }
              }
            }
          }
        }

        return arguments[0];
      }

      var LocalForage = function () {
        function LocalForage(options) {
          _classCallCheck(this, LocalForage);

          for (var driverTypeKey in DefaultDrivers) {
            if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
              var driver = DefaultDrivers[driverTypeKey];
              var driverName = driver._driver;
              this[driverTypeKey] = driverName;

              if (!DefinedDrivers[driverName]) {
                // we don't need to wait for the promise,
                // since the default drivers can be defined
                // in a blocking manner
                this.defineDriver(driver);
              }
            }
          }

          this._defaultConfig = extend({}, DefaultConfig);
          this._config = extend({}, this._defaultConfig, options);
          this._driverSet = null;
          this._initDriver = null;
          this._ready = false;
          this._dbInfo = null;

          this._wrapLibraryMethodsWithReady();

          this.setDriver(this._config.driver)["catch"](function () {});
        } // Set any config values for localForage; can be called anytime before
        // the first API call (e.g. `getItem`, `setItem`).
        // We loop through options so we don't overwrite existing config
        // values.


        LocalForage.prototype.config = function config(options) {
          // If the options argument is an object, we use it to set values.
          // Otherwise, we return either a specified config value or all
          // config values.
          if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
            // If localforage is ready and fully initialized, we can't set
            // any new configuration values. Instead, we return an error.
            if (this._ready) {
              return new Error("Can't call config() after localforage " + 'has been used.');
            }

            for (var i in options) {
              if (i === 'storeName') {
                options[i] = options[i].replace(/\W/g, '_');
              }

              if (i === 'version' && typeof options[i] !== 'number') {
                return new Error('Database version must be a number.');
              }

              this._config[i] = options[i];
            } // after all config options are set and
            // the driver option is used, try setting it


            if ('driver' in options && options.driver) {
              return this.setDriver(this._config.driver);
            }

            return true;
          } else if (typeof options === 'string') {
            return this._config[options];
          } else {
            return this._config;
          }
        }; // Used to define a custom driver, shared across all instances of
        // localForage.


        LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
          var promise = new Promise$1(function (resolve, reject) {
            try {
              var driverName = driverObject._driver;
              var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); // A driver name should be defined and not overlap with the
              // library-defined, default drivers.

              if (!driverObject._driver) {
                reject(complianceError);
                return;
              }

              var driverMethods = LibraryMethods.concat('_initStorage');

              for (var i = 0, len = driverMethods.length; i < len; i++) {
                var driverMethodName = driverMethods[i]; // when the property is there,
                // it should be a method even when optional

                var isRequired = !includes(OptionalDriverMethods, driverMethodName);

                if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {
                  reject(complianceError);
                  return;
                }
              }

              var configureMissingMethods = function configureMissingMethods() {
                var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {
                  return function () {
                    var error = new Error('Method ' + methodName + ' is not implemented by the current driver');
                    var promise = Promise$1.reject(error);
                    executeCallback(promise, arguments[arguments.length - 1]);
                    return promise;
                  };
                };

                for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
                  var optionalDriverMethod = OptionalDriverMethods[_i];

                  if (!driverObject[optionalDriverMethod]) {
                    driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
                  }
                }
              };

              configureMissingMethods();

              var setDriverSupport = function setDriverSupport(support) {
                if (DefinedDrivers[driverName]) {
                  console.info('Redefining LocalForage driver: ' + driverName);
                }

                DefinedDrivers[driverName] = driverObject;
                DriverSupport[driverName] = support; // don't use a then, so that we can define
                // drivers that have simple _support methods
                // in a blocking manner

                resolve();
              };

              if ('_support' in driverObject) {
                if (driverObject._support && typeof driverObject._support === 'function') {
                  driverObject._support().then(setDriverSupport, reject);
                } else {
                  setDriverSupport(!!driverObject._support);
                }
              } else {
                setDriverSupport(true);
              }
            } catch (e) {
              reject(e);
            }
          });
          executeTwoCallbacks(promise, callback, errorCallback);
          return promise;
        };

        LocalForage.prototype.driver = function driver() {
          return this._driver || null;
        };

        LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
          var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));
          executeTwoCallbacks(getDriverPromise, callback, errorCallback);
          return getDriverPromise;
        };

        LocalForage.prototype.getSerializer = function getSerializer(callback) {
          var serializerPromise = Promise$1.resolve(localforageSerializer);
          executeTwoCallbacks(serializerPromise, callback);
          return serializerPromise;
        };

        LocalForage.prototype.ready = function ready(callback) {
          var self = this;

          var promise = self._driverSet.then(function () {
            if (self._ready === null) {
              self._ready = self._initDriver();
            }

            return self._ready;
          });

          executeTwoCallbacks(promise, callback, callback);
          return promise;
        };

        LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
          var self = this;

          if (!isArray(drivers)) {
            drivers = [drivers];
          }

          var supportedDrivers = this._getSupportedDrivers(drivers);

          function setDriverToConfig() {
            self._config.driver = self.driver();
          }

          function extendSelfWithDriver(driver) {
            self._extend(driver);

            setDriverToConfig();
            self._ready = self._initStorage(self._config);
            return self._ready;
          }

          function initDriver(supportedDrivers) {
            return function () {
              var currentDriverIndex = 0;

              function driverPromiseLoop() {
                while (currentDriverIndex < supportedDrivers.length) {
                  var driverName = supportedDrivers[currentDriverIndex];
                  currentDriverIndex++;
                  self._dbInfo = null;
                  self._ready = null;
                  return self.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop);
                }

                setDriverToConfig();
                var error = new Error('No available storage method found.');
                self._driverSet = Promise$1.reject(error);
                return self._driverSet;
              }

              return driverPromiseLoop();
            };
          } // There might be a driver initialization in progress
          // so wait for it to finish in order to avoid a possible
          // race condition to set _dbInfo


          var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () {
            return Promise$1.resolve();
          }) : Promise$1.resolve();
          this._driverSet = oldDriverSetDone.then(function () {
            var driverName = supportedDrivers[0];
            self._dbInfo = null;
            self._ready = null;
            return self.getDriver(driverName).then(function (driver) {
              self._driver = driver._driver;
              setDriverToConfig();

              self._wrapLibraryMethodsWithReady();

              self._initDriver = initDriver(supportedDrivers);
            });
          })["catch"](function () {
            setDriverToConfig();
            var error = new Error('No available storage method found.');
            self._driverSet = Promise$1.reject(error);
            return self._driverSet;
          });
          executeTwoCallbacks(this._driverSet, callback, errorCallback);
          return this._driverSet;
        };

        LocalForage.prototype.supports = function supports(driverName) {
          return !!DriverSupport[driverName];
        };

        LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
          extend(this, libraryMethodsAndProperties);
        };

        LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
          var supportedDrivers = [];

          for (var i = 0, len = drivers.length; i < len; i++) {
            var driverName = drivers[i];

            if (this.supports(driverName)) {
              supportedDrivers.push(driverName);
            }
          }

          return supportedDrivers;
        };

        LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
          // Add a stub for each driver API method that delays the call to the
          // corresponding driver method until localForage is ready. These stubs
          // will be replaced by the driver methods as soon as the driver is
          // loaded, so there is no performance impact.
          for (var i = 0, len = LibraryMethods.length; i < len; i++) {
            callWhenReady(this, LibraryMethods[i]);
          }
        };

        LocalForage.prototype.createInstance = function createInstance(options) {
          return new LocalForage(options);
        };

        return LocalForage;
      }(); // The actual localForage object that we expose as a module or via a
      // global. It's extended by pulling in one of our other libraries.


      var localforage_js = new LocalForage();
      module.exports = localforage_js;
    }, {
      "3": 3
    }]
  }, {}, [4])(4);
});
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(18)))

/***/ }),
/* 24 */,
/* 25 */
/***/ (function(module, exports, __webpack_require__) {

var isFunction = __webpack_require__(58),
    isLength = __webpack_require__(68);
/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */


function isArrayLike(value) {
  return value != null && isLength(value.length) && !isFunction(value);
}

module.exports = isArrayLike;

/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {

var global = __webpack_require__(10);

var core = __webpack_require__(15);

var ctx = __webpack_require__(54);

var hide = __webpack_require__(27);

var has = __webpack_require__(56);

var PROTOTYPE = 'prototype';

var $export = function (type, name, source) {
  var IS_FORCED = type & $export.F;
  var IS_GLOBAL = type & $export.G;
  var IS_STATIC = type & $export.S;
  var IS_PROTO = type & $export.P;
  var IS_BIND = type & $export.B;
  var IS_WRAP = type & $export.W;
  var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
  var expProto = exports[PROTOTYPE];
  var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
  var key, own, out;
  if (IS_GLOBAL) source = name;

  for (key in source) {
    // contains in native
    own = !IS_FORCED && target && target[key] !== undefined;
    if (own && has(exports, key)) continue; // export native or passed

    out = own ? target[key] : source[key]; // prevent global pollution for namespaces

    exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context
    : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library
    : IS_WRAP && target[key] == out ? function (C) {
      var F = function (a, b, c) {
        if (this instanceof C) {
          switch (arguments.length) {
            case 0:
              return new C();

            case 1:
              return new C(a);

            case 2:
              return new C(a, b);
          }

          return new C(a, b, c);
        }

        return C.apply(this, arguments);
      };

      F[PROTOTYPE] = C[PROTOTYPE];
      return F; // make static versions for prototype methods
    }(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%

    if (IS_PROTO) {
      (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%

      if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out);
    }
  }
}; // type bitmap


$export.F = 1; // forced

$export.G = 2; // global

$export.S = 4; // static

$export.P = 8; // proto

$export.B = 16; // bind

$export.W = 32; // wrap

$export.U = 64; // safe

$export.R = 128; // real proto method for `library`

module.exports = $export;

/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {

var dP = __webpack_require__(36);

var createDesc = __webpack_require__(138);

module.exports = __webpack_require__(28) ? function (object, key, value) {
  return dP.f(object, key, createDesc(1, value));
} : function (object, key, value) {
  object[key] = value;
  return object;
};

/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {

// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(79)(function () {
  return Object.defineProperty({}, 'a', {
    get: function () {
      return 7;
    }
  }).a != 7;
});

/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {

var arrayLikeKeys = __webpack_require__(96),
    baseKeys = __webpack_require__(100),
    isArrayLike = __webpack_require__(25);
/**
 * Creates an array of the own enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects. See the
 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * for more details.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keys(new Foo);
 * // => ['a', 'b'] (iteration order is not guaranteed)
 *
 * _.keys('hi');
 * // => ['0', '1']
 */


function keys(object) {
  return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}

module.exports = keys;

/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Native Javascript for Bootstrap 4 v2.0.27 | © dnp_theme | MIT-License
(function (root, factory) {
  if (true) {
    // AMD support:
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  } else { var bsn; }
})(this, function () {
  /* Native Javascript for Bootstrap 4 | Internal Utility Functions
  ----------------------------------------------------------------*/
  "use strict"; // globals

  var globalObject = typeof global !== 'undefined' ? global : this || window,
      DOC = document,
      HTML = DOC.documentElement,
      body = 'body',
      // allow the library to be used in <head>
  // Native Javascript for Bootstrap Global Object
  BSN = globalObject.BSN = {},
      supports = BSN.supports = [],
      // function toggle attributes
  dataToggle = 'data-toggle',
      dataDismiss = 'data-dismiss',
      dataSpy = 'data-spy',
      dataRide = 'data-ride',
      // components
  stringAlert = 'Alert',
      stringButton = 'Button',
      stringCarousel = 'Carousel',
      stringCollapse = 'Collapse',
      stringDropdown = 'Dropdown',
      stringModal = 'Modal',
      stringPopover = 'Popover',
      stringScrollSpy = 'ScrollSpy',
      stringTab = 'Tab',
      stringTooltip = 'Tooltip',
      stringToast = 'Toast',
      // options DATA API
  dataAutohide = 'data-autohide',
      databackdrop = 'data-backdrop',
      dataKeyboard = 'data-keyboard',
      dataTarget = 'data-target',
      dataInterval = 'data-interval',
      dataHeight = 'data-height',
      dataPause = 'data-pause',
      dataTitle = 'data-title',
      dataOriginalTitle = 'data-original-title',
      dataDismissible = 'data-dismissible',
      dataTrigger = 'data-trigger',
      dataAnimation = 'data-animation',
      dataContainer = 'data-container',
      dataPlacement = 'data-placement',
      dataDelay = 'data-delay',
      // option keys
  backdrop = 'backdrop',
      keyboard = 'keyboard',
      delay = 'delay',
      content = 'content',
      target = 'target',
      currentTarget = 'currentTarget',
      interval = 'interval',
      pause = 'pause',
      animation = 'animation',
      placement = 'placement',
      container = 'container',
      // box model
  offsetTop = 'offsetTop',
      offsetBottom = 'offsetBottom',
      offsetLeft = 'offsetLeft',
      scrollTop = 'scrollTop',
      scrollLeft = 'scrollLeft',
      clientWidth = 'clientWidth',
      clientHeight = 'clientHeight',
      offsetWidth = 'offsetWidth',
      offsetHeight = 'offsetHeight',
      innerWidth = 'innerWidth',
      innerHeight = 'innerHeight',
      scrollHeight = 'scrollHeight',
      scrollWidth = 'scrollWidth',
      height = 'height',
      // aria
  ariaExpanded = 'aria-expanded',
      ariaHidden = 'aria-hidden',
      ariaSelected = 'aria-selected',
      // event names
  clickEvent = 'click',
      focusEvent = 'focus',
      hoverEvent = 'hover',
      keydownEvent = 'keydown',
      keyupEvent = 'keyup',
      resizeEvent = 'resize',
      // passive
  scrollEvent = 'scroll',
      // passive
  mouseHover = 'onmouseleave' in DOC ? ['mouseenter', 'mouseleave'] : ['mouseover', 'mouseout'],
      // touch since 2.0.26
  touchEvents = {
    start: 'touchstart',
    end: 'touchend',
    move: 'touchmove'
  },
      // passive
  // originalEvents
  showEvent = 'show',
      shownEvent = 'shown',
      hideEvent = 'hide',
      hiddenEvent = 'hidden',
      closeEvent = 'close',
      closedEvent = 'closed',
      slidEvent = 'slid',
      slideEvent = 'slide',
      changeEvent = 'change',
      // other
  getAttribute = 'getAttribute',
      setAttribute = 'setAttribute',
      hasAttribute = 'hasAttribute',
      createElement = 'createElement',
      appendChild = 'appendChild',
      innerHTML = 'innerHTML',
      getElementsByTagName = 'getElementsByTagName',
      preventDefault = 'preventDefault',
      getBoundingClientRect = 'getBoundingClientRect',
      querySelectorAll = 'querySelectorAll',
      getElementsByCLASSNAME = 'getElementsByClassName',
      getComputedStyle = 'getComputedStyle',
      indexOf = 'indexOf',
      parentNode = 'parentNode',
      length = 'length',
      toLowerCase = 'toLowerCase',
      Transition = 'Transition',
      Duration = 'Duration',
      Webkit = 'Webkit',
      style = 'style',
      push = 'push',
      tabindex = 'tabindex',
      contains = 'contains',
      active = 'active',
      showClass = 'show',
      collapsing = 'collapsing',
      disabled = 'disabled',
      loading = 'loading',
      left = 'left',
      right = 'right',
      top = 'top',
      bottom = 'bottom',
      // tooltip / popover
  tipPositions = /\b(top|bottom|left|right)+/,
      // modal
  modalOverlay = 0,
      fixedTop = 'fixed-top',
      fixedBottom = 'fixed-bottom',
      // transitionEnd since 2.0.4
  supportTransitions = Webkit + Transition in HTML[style] || Transition[toLowerCase]() in HTML[style],
      transitionEndEvent = Webkit + Transition in HTML[style] ? Webkit[toLowerCase]() + Transition + 'End' : Transition[toLowerCase]() + 'end',
      transitionDuration = Webkit + Duration in HTML[style] ? Webkit[toLowerCase]() + Transition + Duration : Transition[toLowerCase]() + Duration,
      // set new focus element since 2.0.3
  setFocus = function (element) {
    element.focus ? element.focus() : element.setActive();
  },
      // class manipulation, since 2.0.0 requires polyfill.js
  addClass = function (element, classNAME) {
    element.classList.add(classNAME);
  },
      removeClass = function (element, classNAME) {
    element.classList.remove(classNAME);
  },
      hasClass = function (element, classNAME) {
    // since 2.0.0
    return element.classList[contains](classNAME);
  },
      // selection methods
  getElementsByClassName = function (element, classNAME) {
    // returns Array
    return [].slice.call(element[getElementsByCLASSNAME](classNAME));
  },
      queryElement = function (selector, parent) {
    var lookUp = parent ? parent : DOC;
    return typeof selector === 'object' ? selector : lookUp.querySelector(selector);
  },
      getClosest = function (element, selector) {
    //element is the element and selector is for the closest parent element to find
    // source http://gomakethings.com/climbing-up-and-down-the-dom-tree-with-vanilla-javascript/
    var firstChar = selector.charAt(0),
        selectorSubstring = selector.substr(1);

    if (firstChar === '.') {
      // If selector is a class
      for (; element && element !== DOC; element = element[parentNode]) {
        // Get closest match
        if (queryElement(selector, element[parentNode]) !== null && hasClass(element, selectorSubstring)) {
          return element;
        }
      }
    } else if (firstChar === '#') {
      // If selector is an ID
      for (; element && element !== DOC; element = element[parentNode]) {
        // Get closest match
        if (element.id === selectorSubstring) {
          return element;
        }
      }
    }

    return false;
  },
      // event attach jQuery style / trigger  since 1.2.0
  on = function (element, event, handler, options) {
    options = options || false;
    element.addEventListener(event, handler, options);
  },
      off = function (element, event, handler, options) {
    options = options || false;
    element.removeEventListener(event, handler, options);
  },
      one = function (element, event, handler, options) {
    // one since 2.0.4
    on(element, event, function handlerWrapper(e) {
      handler(e);
      off(element, event, handlerWrapper, options);
    }, options);
  },
      // determine support for passive events
  supportPassive = function () {
    // Test via a getter in the options object to see if the passive property is accessed
    var result = false;

    try {
      var opts = Object.defineProperty({}, 'passive', {
        get: function () {
          result = true;
        }
      });
      one(globalObject, 'testPassive', null, opts);
    } catch (e) {}

    return result;
  }(),
      // event options
  // https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  passiveHandler = supportPassive ? {
    passive: true
  } : false,
      // transitions
  getTransitionDurationFromElement = function (element) {
    var duration = supportTransitions ? globalObject[getComputedStyle](element)[transitionDuration] : 0;
    duration = parseFloat(duration);
    duration = typeof duration === 'number' && !isNaN(duration) ? duration * 1000 : 0;
    return duration; // we take a short offset to make sure we fire on the next frame after animation
  },
      emulateTransitionEnd = function (element, handler) {
    // emulateTransitionEnd since 2.0.4
    var called = 0,
        duration = getTransitionDurationFromElement(element);
    duration ? one(element, transitionEndEvent, function (e) {
      !called && handler(e), called = 1;
    }) : setTimeout(function () {
      !called && handler(), called = 1;
    }, 17);
  },
      bootstrapCustomEvent = function (eventName, componentName, related) {
    var OriginalCustomEvent = new CustomEvent(eventName + '.bs.' + componentName);
    OriginalCustomEvent.relatedTarget = related;
    this.dispatchEvent(OriginalCustomEvent);
  },
      // tooltip / popover stuff
  getScroll = function () {
    // also Affix and ScrollSpy uses it
    return {
      y: globalObject.pageYOffset || HTML[scrollTop],
      x: globalObject.pageXOffset || HTML[scrollLeft]
    };
  },
      styleTip = function (link, element, position, parent) {
    // both popovers and tooltips (target,tooltip,placement,elementToAppendTo)
    var elementDimensions = {
      w: element[offsetWidth],
      h: element[offsetHeight]
    },
        windowWidth = HTML[clientWidth] || DOC[body][clientWidth],
        windowHeight = HTML[clientHeight] || DOC[body][clientHeight],
        rect = link[getBoundingClientRect](),
        scroll = parent === DOC[body] ? getScroll() : {
      x: parent[offsetLeft] + parent[scrollLeft],
      y: parent[offsetTop] + parent[scrollTop]
    },
        linkDimensions = {
      w: rect[right] - rect[left],
      h: rect[bottom] - rect[top]
    },
        isPopover = hasClass(element, 'popover'),
        topPosition,
        leftPosition,
        arrow = queryElement('.arrow', element),
        arrowTop,
        arrowLeft,
        arrowWidth,
        arrowHeight,
        halfTopExceed = rect[top] + linkDimensions.h / 2 - elementDimensions.h / 2 < 0,
        halfLeftExceed = rect[left] + linkDimensions.w / 2 - elementDimensions.w / 2 < 0,
        halfRightExceed = rect[left] + elementDimensions.w / 2 + linkDimensions.w / 2 >= windowWidth,
        halfBottomExceed = rect[top] + elementDimensions.h / 2 + linkDimensions.h / 2 >= windowHeight,
        topExceed = rect[top] - elementDimensions.h < 0,
        leftExceed = rect[left] - elementDimensions.w < 0,
        bottomExceed = rect[top] + elementDimensions.h + linkDimensions.h >= windowHeight,
        rightExceed = rect[left] + elementDimensions.w + linkDimensions.w >= windowWidth; // recompute position

    position = (position === left || position === right) && leftExceed && rightExceed ? top : position; // first, when both left and right limits are exceeded, we fall back to top|bottom

    position = position === top && topExceed ? bottom : position;
    position = position === bottom && bottomExceed ? top : position;
    position = position === left && leftExceed ? right : position;
    position = position === right && rightExceed ? left : position; // update tooltip/popover class

    element.className[indexOf](position) === -1 && (element.className = element.className.replace(tipPositions, position)); // we check the computed width & height and update here

    arrowWidth = arrow[offsetWidth];
    arrowHeight = arrow[offsetHeight]; // apply styling to tooltip or popover

    if (position === left || position === right) {
      // secondary|side positions
      if (position === left) {
        // LEFT
        leftPosition = rect[left] + scroll.x - elementDimensions.w - (isPopover ? arrowWidth : 0);
      } else {
        // RIGHT
        leftPosition = rect[left] + scroll.x + linkDimensions.w;
      } // adjust top and arrow


      if (halfTopExceed) {
        topPosition = rect[top] + scroll.y;
        arrowTop = linkDimensions.h / 2 - arrowWidth;
      } else if (halfBottomExceed) {
        topPosition = rect[top] + scroll.y - elementDimensions.h + linkDimensions.h;
        arrowTop = elementDimensions.h - linkDimensions.h / 2 - arrowWidth;
      } else {
        topPosition = rect[top] + scroll.y - elementDimensions.h / 2 + linkDimensions.h / 2;
        arrowTop = elementDimensions.h / 2 - (isPopover ? arrowHeight * 0.9 : arrowHeight / 2);
      }
    } else if (position === top || position === bottom) {
      // primary|vertical positions
      if (position === top) {
        // TOP
        topPosition = rect[top] + scroll.y - elementDimensions.h - (isPopover ? arrowHeight : 0);
      } else {
        // BOTTOM
        topPosition = rect[top] + scroll.y + linkDimensions.h;
      } // adjust left | right and also the arrow


      if (halfLeftExceed) {
        leftPosition = 0;
        arrowLeft = rect[left] + linkDimensions.w / 2 - arrowWidth;
      } else if (halfRightExceed) {
        leftPosition = windowWidth - elementDimensions.w * 1.01;
        arrowLeft = elementDimensions.w - (windowWidth - rect[left]) + linkDimensions.w / 2 - arrowWidth / 2;
      } else {
        leftPosition = rect[left] + scroll.x - elementDimensions.w / 2 + linkDimensions.w / 2;
        arrowLeft = elementDimensions.w / 2 - (isPopover ? arrowWidth : arrowWidth / 2);
      }
    } // apply style to tooltip/popover and its arrow


    element[style][top] = topPosition + 'px';
    element[style][left] = leftPosition + 'px';
    arrowTop && (arrow[style][top] = arrowTop + 'px');
    arrowLeft && (arrow[style][left] = arrowLeft + 'px');
  };

  BSN.version = '2.0.27';
  /* Native Javascript for Bootstrap 4 | Alert
  -------------------------------------------*/
  // ALERT DEFINITION
  // ================

  var Alert = function (element) {
    // initialization element
    element = queryElement(element); // bind, target alert, duration and stuff

    var self = this,
        component = 'alert',
        alert = getClosest(element, '.' + component),
        triggerHandler = function () {
      hasClass(alert, 'fade') ? emulateTransitionEnd(alert, transitionEndHandler) : transitionEndHandler();
    },
        // handlers
    clickHandler = function (e) {
      alert = getClosest(e[target], '.' + component);
      element = queryElement('[' + dataDismiss + '="' + component + '"]', alert);
      element && alert && (element === e[target] || element[contains](e[target])) && self.close();
    },
        transitionEndHandler = function () {
      bootstrapCustomEvent.call(alert, closedEvent, component);
      off(element, clickEvent, clickHandler); // detach it's listener

      alert[parentNode].removeChild(alert);
    }; // public method


    this.close = function () {
      if (alert && element && hasClass(alert, showClass)) {
        bootstrapCustomEvent.call(alert, closeEvent, component);
        removeClass(alert, showClass);
        alert && triggerHandler();
      }
    }; // init


    if (!(stringAlert in element)) {
      // prevent adding event handlers twice
      on(element, clickEvent, clickHandler);
    }

    element[stringAlert] = self;
  }; // ALERT DATA API
  // ==============


  supports[push]([stringAlert, Alert, '[' + dataDismiss + '="alert"]']);
  /* Native Javascript for Bootstrap 4 | Button
  ---------------------------------------------*/
  // BUTTON DEFINITION
  // ===================

  var Button = function (element) {
    // initialization element
    element = queryElement(element); // constant

    var toggled = false,
        // toggled makes sure to prevent triggering twice the change.bs.button events
    // strings
    component = 'button',
        checked = 'checked',
        LABEL = 'LABEL',
        INPUT = 'INPUT',
        // private methods
    keyHandler = function (e) {
      var key = e.which || e.keyCode;
      key === 32 && e[target] === DOC.activeElement && toggle(e);
    },
        preventScroll = function (e) {
      var key = e.which || e.keyCode;
      key === 32 && e[preventDefault]();
    },
        toggle = function (e) {
      var label = e[target].tagName === LABEL ? e[target] : e[target][parentNode].tagName === LABEL ? e[target][parentNode] : null; // the .btn label

      if (!label) return; //react if a label or its immediate child is clicked

      var labels = getElementsByClassName(label[parentNode], 'btn'),
          // all the button group buttons
      input = label[getElementsByTagName](INPUT)[0];
      if (!input) return; // return if no input found
      // manage the dom manipulation

      if (input.type === 'checkbox') {
        //checkboxes
        if (!input[checked]) {
          addClass(label, active);
          input[getAttribute](checked);
          input[setAttribute](checked, checked);
          input[checked] = true;
        } else {
          removeClass(label, active);
          input[getAttribute](checked);
          input.removeAttribute(checked);
          input[checked] = false;
        }

        if (!toggled) {
          // prevent triggering the event twice
          toggled = true;
          bootstrapCustomEvent.call(input, changeEvent, component); //trigger the change for the input

          bootstrapCustomEvent.call(element, changeEvent, component); //trigger the change for the btn-group
        }
      }

      if (input.type === 'radio' && !toggled) {
        // radio buttons
        // don't trigger if already active (the OR condition is a hack to check if the buttons were selected with key press and NOT mouse click)
        if (!input[checked] || e.screenX === 0 && e.screenY == 0) {
          addClass(label, active);
          addClass(label, focusEvent);
          input[setAttribute](checked, checked);
          input[checked] = true;
          bootstrapCustomEvent.call(input, changeEvent, component); //trigger the change for the input

          bootstrapCustomEvent.call(element, changeEvent, component); //trigger the change for the btn-group

          toggled = true;

          for (var i = 0, ll = labels[length]; i < ll; i++) {
            var otherLabel = labels[i],
                otherInput = otherLabel[getElementsByTagName](INPUT)[0];

            if (otherLabel !== label && hasClass(otherLabel, active)) {
              removeClass(otherLabel, active);
              otherInput.removeAttribute(checked);
              otherInput[checked] = false;
              bootstrapCustomEvent.call(otherInput, changeEvent, component); // trigger the change
            }
          }
        }
      }

      setTimeout(function () {
        toggled = false;
      }, 50);
    },
        focusHandler = function (e) {
      addClass(e[target][parentNode], focusEvent);
    },
        blurHandler = function (e) {
      removeClass(e[target][parentNode], focusEvent);
    }; // init


    if (!(stringButton in element)) {
      // prevent adding event handlers twice
      on(element, clickEvent, toggle);
      on(element, keyupEvent, keyHandler), on(element, keydownEvent, preventScroll);
      var allBtns = getElementsByClassName(element, 'btn');

      for (var i = 0; i < allBtns.length; i++) {
        var input = allBtns[i][getElementsByTagName](INPUT)[0];
        on(input, focusEvent, focusHandler), on(input, 'blur', blurHandler);
      }
    } // activate items on load


    var labelsToACtivate = getElementsByClassName(element, 'btn'),
        lbll = labelsToACtivate[length];

    for (var i = 0; i < lbll; i++) {
      !hasClass(labelsToACtivate[i], active) && queryElement('input:checked', labelsToACtivate[i]) && addClass(labelsToACtivate[i], active);
    }

    element[stringButton] = this;
  }; // BUTTON DATA API
  // =================


  supports[push]([stringButton, Button, '[' + dataToggle + '="buttons"]']);
  /* Native Javascript for Bootstrap 4 | Collapse
  -----------------------------------------------*/
  // COLLAPSE DEFINITION
  // ===================

  var Collapse = function (element, options) {
    // initialization element
    element = queryElement(element); // set options

    options = options || {}; // event targets and constants

    var accordion = null,
        collapse = null,
        self = this,
        accordionData = element[getAttribute]('data-parent'),
        activeCollapse,
        activeElement,
        // component strings
    component = 'collapse',
        collapsed = 'collapsed',
        isAnimating = 'isAnimating',
        // private methods
    openAction = function (collapseElement, toggle) {
      bootstrapCustomEvent.call(collapseElement, showEvent, component);
      collapseElement[isAnimating] = true;
      addClass(collapseElement, collapsing);
      removeClass(collapseElement, component);
      collapseElement[style][height] = collapseElement[scrollHeight] + 'px';
      emulateTransitionEnd(collapseElement, function () {
        collapseElement[isAnimating] = false;
        collapseElement[setAttribute](ariaExpanded, 'true');
        toggle[setAttribute](ariaExpanded, 'true');
        removeClass(collapseElement, collapsing);
        addClass(collapseElement, component);
        addClass(collapseElement, showClass);
        collapseElement[style][height] = '';
        bootstrapCustomEvent.call(collapseElement, shownEvent, component);
      });
    },
        closeAction = function (collapseElement, toggle) {
      bootstrapCustomEvent.call(collapseElement, hideEvent, component);
      collapseElement[isAnimating] = true;
      collapseElement[style][height] = collapseElement[scrollHeight] + 'px'; // set height first

      removeClass(collapseElement, component);
      removeClass(collapseElement, showClass);
      addClass(collapseElement, collapsing);
      collapseElement[offsetWidth]; // force reflow to enable transition

      collapseElement[style][height] = '0px';
      emulateTransitionEnd(collapseElement, function () {
        collapseElement[isAnimating] = false;
        collapseElement[setAttribute](ariaExpanded, 'false');
        toggle[setAttribute](ariaExpanded, 'false');
        removeClass(collapseElement, collapsing);
        addClass(collapseElement, component);
        collapseElement[style][height] = '';
        bootstrapCustomEvent.call(collapseElement, hiddenEvent, component);
      });
    },
        getTarget = function () {
      var href = element.href && element[getAttribute]('href'),
          parent = element[getAttribute](dataTarget),
          id = href || parent && parent.charAt(0) === '#' && parent;
      return id && queryElement(id);
    }; // public methods


    this.toggle = function (e) {
      e[preventDefault]();

      if (!hasClass(collapse, showClass)) {
        self.show();
      } else {
        self.hide();
      }
    };

    this.hide = function () {
      if (collapse[isAnimating]) return;
      closeAction(collapse, element);
      addClass(element, collapsed);
    };

    this.show = function () {
      if (accordion) {
        activeCollapse = queryElement('.' + component + '.' + showClass, accordion);
        activeElement = activeCollapse && (queryElement('[' + dataTarget + '="#' + activeCollapse.id + '"]', accordion) || queryElement('[href="#' + activeCollapse.id + '"]', accordion));
      }

      if (!collapse[isAnimating] || activeCollapse && !activeCollapse[isAnimating]) {
        if (activeElement && activeCollapse !== collapse) {
          closeAction(activeCollapse, activeElement);
          addClass(activeElement, collapsed);
        }

        openAction(collapse, element);
        removeClass(element, collapsed);
      }
    }; // init


    if (!(stringCollapse in element)) {
      // prevent adding event handlers twice
      on(element, clickEvent, self.toggle);
    }

    collapse = getTarget();
    collapse[isAnimating] = false; // when true it will prevent click handlers  

    accordion = queryElement(options.parent) || accordionData && getClosest(element, accordionData);
    element[stringCollapse] = self;
  }; // COLLAPSE DATA API
  // =================


  supports[push]([stringCollapse, Collapse, '[' + dataToggle + '="collapse"]']);
  /* Native Javascript for Bootstrap 4 | Dropdown
  ----------------------------------------------*/
  // DROPDOWN DEFINITION
  // ===================

  var Dropdown = function (element, option) {
    // initialization element
    element = queryElement(element); // set option

    this.persist = option === true || element[getAttribute]('data-persist') === 'true' || false; // constants, event targets, strings

    var self = this,
        children = 'children',
        parent = element[parentNode],
        component = 'dropdown',
        open = 'open',
        relatedTarget = null,
        menu = queryElement('.dropdown-menu', parent),
        menuItems = function () {
      var set = menu[children],
          newSet = [];

      for (var i = 0; i < set[length]; i++) {
        set[i][children][length] && set[i][children][0].tagName === 'A' && newSet[push](set[i][children][0]);
        set[i].tagName === 'A' && newSet[push](set[i]);
      }

      return newSet;
    }(),
        // preventDefault on empty anchor links
    preventEmptyAnchor = function (anchor) {
      (anchor.href && anchor.href.slice(-1) === '#' || anchor[parentNode] && anchor[parentNode].href && anchor[parentNode].href.slice(-1) === '#') && this[preventDefault]();
    },
        // toggle dismissible events
    toggleDismiss = function () {
      var type = element[open] ? on : off;
      type(DOC, clickEvent, dismissHandler);
      type(DOC, keydownEvent, preventScroll);
      type(DOC, keyupEvent, keyHandler);
      type(DOC, focusEvent, dismissHandler, true);
    },
        // handlers
    dismissHandler = function (e) {
      var eventTarget = e[target],
          hasData = eventTarget && (eventTarget[getAttribute](dataToggle) || eventTarget[parentNode] && getAttribute in eventTarget[parentNode] && eventTarget[parentNode][getAttribute](dataToggle));

      if (e.type === focusEvent && (eventTarget === element || eventTarget === menu || menu[contains](eventTarget))) {
        return;
      }

      if ((eventTarget === menu || menu[contains](eventTarget)) && (self.persist || hasData)) {
        return;
      } else {
        relatedTarget = eventTarget === element || element[contains](eventTarget) ? element : null;
        hide();
      }

      preventEmptyAnchor.call(e, eventTarget);
    },
        clickHandler = function (e) {
      relatedTarget = element;
      show();
      preventEmptyAnchor.call(e, e[target]);
    },
        preventScroll = function (e) {
      var key = e.which || e.keyCode;

      if (key === 38 || key === 40) {
        e[preventDefault]();
      }
    },
        keyHandler = function (e) {
      var key = e.which || e.keyCode,
          activeItem = DOC.activeElement,
          idx = menuItems[indexOf](activeItem),
          isSameElement = activeItem === element,
          isInsideMenu = menu[contains](activeItem),
          isMenuItem = activeItem[parentNode] === menu || activeItem[parentNode][parentNode] === menu;

      if (isMenuItem) {
        // navigate up | down
        idx = isSameElement ? 0 : key === 38 ? idx > 1 ? idx - 1 : 0 : key === 40 ? idx < menuItems[length] - 1 ? idx + 1 : idx : idx;
        menuItems[idx] && setFocus(menuItems[idx]);
      }

      if ((menuItems[length] && isMenuItem // menu has items
      || !menuItems[length] && (isInsideMenu || isSameElement) // menu might be a form
      || !isInsideMenu) && // or the focused element is not in the menu at all
      element[open] && key === 27 // menu must be open
      ) {
          self.toggle();
          relatedTarget = null;
        }
    },
        // private methods
    show = function () {
      bootstrapCustomEvent.call(parent, showEvent, component, relatedTarget);
      addClass(menu, showClass);
      addClass(parent, showClass);
      element[setAttribute](ariaExpanded, true);
      bootstrapCustomEvent.call(parent, shownEvent, component, relatedTarget);
      element[open] = true;
      off(element, clickEvent, clickHandler);
      setTimeout(function () {
        setFocus(menu[getElementsByTagName]('INPUT')[0] || element); // focus the first input item | element

        toggleDismiss();
      }, 1);
    },
        hide = function () {
      bootstrapCustomEvent.call(parent, hideEvent, component, relatedTarget);
      removeClass(menu, showClass);
      removeClass(parent, showClass);
      element[setAttribute](ariaExpanded, false);
      bootstrapCustomEvent.call(parent, hiddenEvent, component, relatedTarget);
      element[open] = false;
      toggleDismiss();
      setFocus(element);
      setTimeout(function () {
        on(element, clickEvent, clickHandler);
      }, 1);
    }; // set initial state to closed


    element[open] = false; // public methods

    this.toggle = function () {
      if (hasClass(parent, showClass) && element[open]) {
        hide();
      } else {
        show();
      }
    }; // init


    if (!(stringDropdown in element)) {
      // prevent adding event handlers twice
      !tabindex in menu && menu[setAttribute](tabindex, '0'); // Fix onblur on Chrome | Safari

      on(element, clickEvent, clickHandler);
    }

    element[stringDropdown] = self;
  }; // DROPDOWN DATA API
  // =================


  supports[push]([stringDropdown, Dropdown, '[' + dataToggle + '="dropdown"]']);
  /* Native Javascript for Bootstrap 4 | Modal
  -------------------------------------------*/
  // MODAL DEFINITION
  // ===============

  var Modal = function (element, options) {
    // element can be the modal/triggering button
    // the modal (both JavaScript / DATA API init) / triggering button element (DATA API)
    element = queryElement(element); // strings

    var component = 'modal',
        staticString = 'static',
        modalTrigger = 'modalTrigger',
        paddingRight = 'paddingRight',
        modalBackdropString = 'modal-backdrop',
        isAnimating = 'isAnimating',
        // determine modal, triggering element
    btnCheck = element[getAttribute](dataTarget) || element[getAttribute]('href'),
        checkModal = queryElement(btnCheck),
        modal = hasClass(element, component) ? element : checkModal;

    if (hasClass(element, component)) {
      element = null;
    } // modal is now independent of it's triggering element


    if (!modal) {
      return;
    } // invalidate
    // set options


    options = options || {};
    this[keyboard] = options[keyboard] === false || modal[getAttribute](dataKeyboard) === 'false' ? false : true;
    this[backdrop] = options[backdrop] === staticString || modal[getAttribute](databackdrop) === staticString ? staticString : true;
    this[backdrop] = options[backdrop] === false || modal[getAttribute](databackdrop) === 'false' ? false : this[backdrop];
    this[animation] = hasClass(modal, 'fade') ? true : false;
    this[content] = options[content]; // JavaScript only
    // set an initial state of the modal

    modal[isAnimating] = false; // bind, constants, event targets and other vars

    var self = this,
        relatedTarget = null,
        bodyIsOverflowing,
        scrollBarWidth,
        overlay,
        overlayDelay,
        modalTimer,
        // also find fixed-top / fixed-bottom items
    fixedItems = getElementsByClassName(HTML, fixedTop).concat(getElementsByClassName(HTML, fixedBottom)),
        // private methods
    getWindowWidth = function () {
      var htmlRect = HTML[getBoundingClientRect]();
      return globalObject[innerWidth] || htmlRect[right] - Math.abs(htmlRect[left]);
    },
        setScrollbar = function () {
      var bodyStyle = globalObject[getComputedStyle](DOC[body]),
          bodyPad = parseInt(bodyStyle[paddingRight], 10),
          itemPad;

      if (bodyIsOverflowing) {
        DOC[body][style][paddingRight] = bodyPad + scrollBarWidth + 'px';
        modal[style][paddingRight] = scrollBarWidth + 'px';

        if (fixedItems[length]) {
          for (var i = 0; i < fixedItems[length]; i++) {
            itemPad = globalObject[getComputedStyle](fixedItems[i])[paddingRight];
            fixedItems[i][style][paddingRight] = parseInt(itemPad) + scrollBarWidth + 'px';
          }
        }
      }
    },
        resetScrollbar = function () {
      DOC[body][style][paddingRight] = '';
      modal[style][paddingRight] = '';

      if (fixedItems[length]) {
        for (var i = 0; i < fixedItems[length]; i++) {
          fixedItems[i][style][paddingRight] = '';
        }
      }
    },
        measureScrollbar = function () {
      // thx walsh
      var scrollDiv = DOC[createElement]('div'),
          widthValue;
      scrollDiv.className = component + '-scrollbar-measure'; // this is here to stay

      DOC[body][appendChild](scrollDiv);
      widthValue = scrollDiv[offsetWidth] - scrollDiv[clientWidth];
      DOC[body].removeChild(scrollDiv);
      return widthValue;
    },
        checkScrollbar = function () {
      bodyIsOverflowing = DOC[body][clientWidth] < getWindowWidth();
      scrollBarWidth = measureScrollbar();
    },
        createOverlay = function () {
      var newOverlay = DOC[createElement]('div');
      overlay = queryElement('.' + modalBackdropString);

      if (overlay === null) {
        newOverlay[setAttribute]('class', modalBackdropString + (self[animation] ? ' fade' : ''));
        overlay = newOverlay;
        DOC[body][appendChild](overlay);
      }

      modalOverlay = 1;
    },
        removeOverlay = function () {
      overlay = queryElement('.' + modalBackdropString);

      if (overlay && overlay !== null && typeof overlay === 'object') {
        modalOverlay = 0;
        DOC[body].removeChild(overlay);
        overlay = null;
      }
    },
        // triggers
    triggerShow = function () {
      setFocus(modal);
      modal[isAnimating] = false;
      bootstrapCustomEvent.call(modal, shownEvent, component, relatedTarget);
      on(globalObject, resizeEvent, self.update, passiveHandler);
      on(modal, clickEvent, dismissHandler);
      on(DOC, keydownEvent, keyHandler);
    },
        triggerHide = function () {
      modal[style].display = '';
      element && setFocus(element);
      bootstrapCustomEvent.call(modal, hiddenEvent, component);

      (function () {
        if (!getElementsByClassName(DOC, component + ' ' + showClass)[0]) {
          resetScrollbar();
          removeClass(DOC[body], component + '-open');
          overlay && hasClass(overlay, 'fade') ? (removeClass(overlay, showClass), emulateTransitionEnd(overlay, removeOverlay)) : removeOverlay();
          off(globalObject, resizeEvent, self.update, passiveHandler);
          off(modal, clickEvent, dismissHandler);
          off(DOC, keydownEvent, keyHandler);
        }
      })();

      modal[isAnimating] = false;
    },
        // handlers
    clickHandler = function (e) {
      if (modal[isAnimating]) return;
      var clickTarget = e[target];
      clickTarget = clickTarget[hasAttribute](dataTarget) || clickTarget[hasAttribute]('href') ? clickTarget : clickTarget[parentNode];

      if (clickTarget === element && !hasClass(modal, showClass)) {
        modal[modalTrigger] = element;
        relatedTarget = element;
        self.show();
        e[preventDefault]();
      }
    },
        keyHandler = function (e) {
      if (modal[isAnimating]) return;

      if (self[keyboard] && e.which == 27 && hasClass(modal, showClass)) {
        self.hide();
      }
    },
        dismissHandler = function (e) {
      if (modal[isAnimating]) return;
      var clickTarget = e[target];

      if (hasClass(modal, showClass) && (clickTarget[parentNode][getAttribute](dataDismiss) === component || clickTarget[getAttribute](dataDismiss) === component || clickTarget === modal && self[backdrop] !== staticString)) {
        self.hide();
        relatedTarget = null;
        e[preventDefault]();
      }
    }; // public methods


    this.toggle = function () {
      if (hasClass(modal, showClass)) {
        this.hide();
      } else {
        this.show();
      }
    };

    this.show = function () {
      if (hasClass(modal, showClass) || modal[isAnimating]) {
        return;
      }

      clearTimeout(modalTimer);
      modalTimer = setTimeout(function () {
        modal[isAnimating] = true;
        bootstrapCustomEvent.call(modal, showEvent, component, relatedTarget); // we elegantly hide any opened modal

        var currentOpen = getElementsByClassName(DOC, component + ' ' + showClass)[0];

        if (currentOpen && currentOpen !== modal) {
          modalTrigger in currentOpen && currentOpen[modalTrigger][stringModal].hide();
          stringModal in currentOpen && currentOpen[stringModal].hide();
        }

        if (self[backdrop]) {
          !modalOverlay && !overlay && createOverlay();
        }

        if (overlay && !hasClass(overlay, showClass)) {
          overlay[offsetWidth]; // force reflow to enable trasition

          overlayDelay = getTransitionDurationFromElement(overlay);
          addClass(overlay, showClass);
        }

        setTimeout(function () {
          modal[style].display = 'block';
          checkScrollbar();
          setScrollbar();
          addClass(DOC[body], component + '-open');
          addClass(modal, showClass);
          modal[setAttribute](ariaHidden, false);
          hasClass(modal, 'fade') ? emulateTransitionEnd(modal, triggerShow) : triggerShow();
        }, supportTransitions && overlay && overlayDelay ? overlayDelay : 1);
      }, 1);
    };

    this.hide = function () {
      if (modal[isAnimating] || !hasClass(modal, showClass)) {
        return;
      }

      clearTimeout(modalTimer);
      modalTimer = setTimeout(function () {
        modal[isAnimating] = true;
        bootstrapCustomEvent.call(modal, hideEvent, component);
        overlay = queryElement('.' + modalBackdropString);
        overlayDelay = overlay && getTransitionDurationFromElement(overlay);
        removeClass(modal, showClass);
        modal[setAttribute](ariaHidden, true);
        setTimeout(function () {
          hasClass(modal, 'fade') ? emulateTransitionEnd(modal, triggerHide) : triggerHide();
        }, supportTransitions && overlay && overlayDelay ? overlayDelay : 2);
      }, 2);
    };

    this.setContent = function (content) {
      queryElement('.' + component + '-content', modal)[innerHTML] = content;
    };

    this.update = function () {
      if (hasClass(modal, showClass)) {
        checkScrollbar();
        setScrollbar();
      }
    }; // init
    // prevent adding event handlers over and over
    // modal is independent of a triggering element


    if (!!element && !(stringModal in element)) {
      on(element, clickEvent, clickHandler);
    }

    if (!!self[content]) {
      self.setContent(self[content]);
    }

    if (element) {
      element[stringModal] = self;
      modal[modalTrigger] = element;
    } else {
      modal[stringModal] = self;
    }
  }; // DATA API


  supports[push]([stringModal, Modal, '[' + dataToggle + '="modal"]']);
  /* Native Javascript for Bootstrap 4 | Popover
  ----------------------------------------------*/
  // POPOVER DEFINITION
  // ==================

  var Popover = function (element, options) {
    // initialization element
    element = queryElement(element); // set options

    options = options || {}; // DATA API

    var triggerData = element[getAttribute](dataTrigger),
        // click / hover / focus
    animationData = element[getAttribute](dataAnimation),
        // true / false
    placementData = element[getAttribute](dataPlacement),
        dismissibleData = element[getAttribute](dataDismissible),
        delayData = element[getAttribute](dataDelay),
        containerData = element[getAttribute](dataContainer),
        // internal strings
    component = 'popover',
        template = 'template',
        trigger = 'trigger',
        classString = 'class',
        div = 'div',
        fade = 'fade',
        dataContent = 'data-content',
        dismissible = 'dismissible',
        closeBtn = '<button type="button" class="close">×</button>',
        // check container
    containerElement = queryElement(options[container]),
        containerDataElement = queryElement(containerData),
        // maybe the element is inside a modal
    modal = getClosest(element, '.modal'),
        // maybe the element is inside a fixed navbar
    navbarFixedTop = getClosest(element, '.' + fixedTop),
        navbarFixedBottom = getClosest(element, '.' + fixedBottom); // set instance options

    this[template] = options[template] ? options[template] : null; // JavaScript only

    this[trigger] = options[trigger] ? options[trigger] : triggerData || hoverEvent;
    this[animation] = options[animation] && options[animation] !== fade ? options[animation] : animationData || fade;
    this[placement] = options[placement] ? options[placement] : placementData || top;
    this[delay] = parseInt(options[delay] || delayData) || 200;
    this[dismissible] = options[dismissible] || dismissibleData === 'true' ? true : false;
    this[container] = containerElement ? containerElement : containerDataElement ? containerDataElement : navbarFixedTop ? navbarFixedTop : navbarFixedBottom ? navbarFixedBottom : modal ? modal : DOC[body]; // bind, content

    var self = this,
        titleString = options.title || element[getAttribute](dataTitle) || null,
        contentString = options.content || element[getAttribute](dataContent) || null;
    if (!contentString && !this[template]) return; // invalidate
    // constants, vars

    var popover = null,
        timer = 0,
        placementSetting = this[placement],
        // handlers
    dismissibleHandler = function (e) {
      if (popover !== null && e[target] === queryElement('.close', popover)) {
        self.hide();
      }
    },
        // private methods
    removePopover = function () {
      self[container].removeChild(popover);
      timer = null;
      popover = null;
    },
        createPopover = function () {
      titleString = options.title || element[getAttribute](dataTitle);
      contentString = options.content || element[getAttribute](dataContent); // fixing https://github.com/thednp/bootstrap.native/issues/233

      contentString = !!contentString ? contentString.trim() : null;
      popover = DOC[createElement](div); // popover arrow

      var popoverArrow = DOC[createElement](div);
      popoverArrow[setAttribute](classString, 'arrow');
      popover[appendChild](popoverArrow);

      if (contentString !== null && self[template] === null) {
        //create the popover from data attributes
        popover[setAttribute]('role', 'tooltip');

        if (titleString !== null) {
          var popoverTitle = DOC[createElement]('h3');
          popoverTitle[setAttribute](classString, component + '-header');
          popoverTitle[innerHTML] = self[dismissible] ? titleString + closeBtn : titleString;
          popover[appendChild](popoverTitle);
        } //set popover content


        var popoverContent = DOC[createElement](div);
        popoverContent[setAttribute](classString, component + '-body');
        popoverContent[innerHTML] = self[dismissible] && titleString === null ? contentString + closeBtn : contentString;
        popover[appendChild](popoverContent);
      } else {
        // or create the popover from template
        var popoverTemplate = DOC[createElement](div);
        self[template] = self[template].trim();
        popoverTemplate[innerHTML] = self[template];
        popover[innerHTML] = popoverTemplate.firstChild[innerHTML];
      } //append to the container


      self[container][appendChild](popover);
      popover[style].display = 'block';
      popover[setAttribute](classString, component + ' bs-' + component + '-' + placementSetting + ' ' + self[animation]);
    },
        showPopover = function () {
      !hasClass(popover, showClass) && addClass(popover, showClass);
    },
        updatePopover = function () {
      styleTip(element, popover, placementSetting, self[container]);
    },
        // event toggle
    dismissHandlerToggle = function (type) {
      if (clickEvent == self[trigger] || 'focus' == self[trigger]) {
        !self[dismissible] && type(element, 'blur', self.hide);
      }

      self[dismissible] && type(DOC, clickEvent, dismissibleHandler);
      type(globalObject, resizeEvent, self.hide, passiveHandler);
    },
        // triggers
    showTrigger = function () {
      dismissHandlerToggle(on);
      bootstrapCustomEvent.call(element, shownEvent, component);
    },
        hideTrigger = function () {
      dismissHandlerToggle(off);
      removePopover();
      bootstrapCustomEvent.call(element, hiddenEvent, component);
    }; // public methods / handlers


    this.toggle = function () {
      if (popover === null) {
        self.show();
      } else {
        self.hide();
      }
    };

    this.show = function () {
      clearTimeout(timer);
      timer = setTimeout(function () {
        if (popover === null) {
          placementSetting = self[placement]; // we reset placement in all cases

          createPopover();
          updatePopover();
          showPopover();
          bootstrapCustomEvent.call(element, showEvent, component);
          !!self[animation] ? emulateTransitionEnd(popover, showTrigger) : showTrigger();
        }
      }, 20);
    };

    this.hide = function () {
      clearTimeout(timer);
      timer = setTimeout(function () {
        if (popover && popover !== null && hasClass(popover, showClass)) {
          bootstrapCustomEvent.call(element, hideEvent, component);
          removeClass(popover, showClass);
          !!self[animation] ? emulateTransitionEnd(popover, hideTrigger) : hideTrigger();
        }
      }, self[delay]);
    }; // init


    if (!(stringPopover in element)) {
      // prevent adding event handlers twice
      if (self[trigger] === hoverEvent) {
        on(element, mouseHover[0], self.show);

        if (!self[dismissible]) {
          on(element, mouseHover[1], self.hide);
        }
      } else if (clickEvent == self[trigger] || 'focus' == self[trigger]) {
        on(element, self[trigger], self.toggle);
      }
    }

    element[stringPopover] = self;
  }; // POPOVER DATA API
  // ================


  supports[push]([stringPopover, Popover, '[' + dataToggle + '="popover"]']);
  /* Native Javascript for Bootstrap 4 | Tab
  -----------------------------------------*/
  // TAB DEFINITION
  // ==============

  var Tab = function (element, options) {
    // initialization element
    element = queryElement(element); // DATA API

    var heightData = element[getAttribute](dataHeight),
        // strings
    component = 'tab',
        height = 'height',
        float = 'float',
        isAnimating = 'isAnimating'; // set options

    options = options || {};
    this[height] = supportTransitions ? options[height] || heightData === 'true' : false; // bind, event targets

    var self = this,
        next,
        tabs = getClosest(element, '.nav'),
        tabsContentContainer = false,
        dropdown = tabs && queryElement('.dropdown-toggle', tabs),
        activeTab,
        activeContent,
        nextContent,
        containerHeight,
        equalContents,
        nextHeight,
        // trigger
    triggerEnd = function () {
      tabsContentContainer[style][height] = '';
      removeClass(tabsContentContainer, collapsing);
      tabs[isAnimating] = false;
    },
        triggerShow = function () {
      if (tabsContentContainer) {
        // height animation
        if (equalContents) {
          triggerEnd();
        } else {
          setTimeout(function () {
            // enables height animation
            tabsContentContainer[style][height] = nextHeight + 'px'; // height animation

            tabsContentContainer[offsetWidth];
            emulateTransitionEnd(tabsContentContainer, triggerEnd);
          }, 50);
        }
      } else {
        tabs[isAnimating] = false;
      }

      bootstrapCustomEvent.call(next, shownEvent, component, activeTab);
    },
        triggerHide = function () {
      if (tabsContentContainer) {
        activeContent[style][float] = left;
        nextContent[style][float] = left;
        containerHeight = activeContent[scrollHeight];
      }

      addClass(nextContent, active);
      bootstrapCustomEvent.call(next, showEvent, component, activeTab);
      removeClass(activeContent, active);
      bootstrapCustomEvent.call(activeTab, hiddenEvent, component, next);

      if (tabsContentContainer) {
        nextHeight = nextContent[scrollHeight];
        equalContents = nextHeight === containerHeight;
        addClass(tabsContentContainer, collapsing);
        tabsContentContainer[style][height] = containerHeight + 'px'; // height animation

        tabsContentContainer[offsetHeight];
        activeContent[style][float] = '';
        nextContent[style][float] = '';
      }

      if (hasClass(nextContent, 'fade')) {
        setTimeout(function () {
          addClass(nextContent, showClass);
          emulateTransitionEnd(nextContent, triggerShow);
        }, 20);
      } else {
        triggerShow();
      }
    };

    if (!tabs) return; // invalidate
    // set default animation state

    tabs[isAnimating] = false; // private methods

    var getActiveTab = function () {
      var activeTabs = getElementsByClassName(tabs, active),
          activeTab;

      if (activeTabs[length] === 1 && !hasClass(activeTabs[0][parentNode], 'dropdown')) {
        activeTab = activeTabs[0];
      } else if (activeTabs[length] > 1) {
        activeTab = activeTabs[activeTabs[length] - 1];
      }

      return activeTab;
    },
        getActiveContent = function () {
      return queryElement(getActiveTab()[getAttribute]('href'));
    },
        // handler 
    clickHandler = function (e) {
      e[preventDefault]();
      next = e[currentTarget];
      !tabs[isAnimating] && !hasClass(next, active) && self.show();
    }; // public method


    this.show = function () {
      // the tab we clicked is now the next tab
      next = next || element;
      nextContent = queryElement(next[getAttribute]('href')); //this is the actual object, the next tab content to activate

      activeTab = getActiveTab();
      activeContent = getActiveContent();
      tabs[isAnimating] = true;
      removeClass(activeTab, active);
      activeTab[setAttribute](ariaSelected, 'false');
      addClass(next, active);
      next[setAttribute](ariaSelected, 'true');

      if (dropdown) {
        if (!hasClass(element[parentNode], 'dropdown-menu')) {
          if (hasClass(dropdown, active)) removeClass(dropdown, active);
        } else {
          if (!hasClass(dropdown, active)) addClass(dropdown, active);
        }
      }

      bootstrapCustomEvent.call(activeTab, hideEvent, component, next);

      if (hasClass(activeContent, 'fade')) {
        removeClass(activeContent, showClass);
        emulateTransitionEnd(activeContent, triggerHide);
      } else {
        triggerHide();
      }
    }; // init


    if (!(stringTab in element)) {
      // prevent adding event handlers twice
      on(element, clickEvent, clickHandler);
    }

    if (self[height]) {
      tabsContentContainer = getActiveContent()[parentNode];
    }

    element[stringTab] = self;
  }; // TAB DATA API
  // ============


  supports[push]([stringTab, Tab, '[' + dataToggle + '="tab"]']);
  /* Native Javascript for Bootstrap 4 | Toast
  ---------------------------------------------*/
  // TOAST DEFINITION
  // ==================

  var Toast = function (element, options) {
    // initialization element
    element = queryElement(element); // set options

    options = options || {}; // DATA API

    var animationData = element[getAttribute](dataAnimation),
        autohideData = element[getAttribute](dataAutohide),
        delayData = element[getAttribute](dataDelay),
        // strings
    component = 'toast',
        autohide = 'autohide',
        animation = 'animation',
        showing = 'showing',
        hide = 'hide',
        fade = 'fade'; // set instance options

    this[animation] = options[animation] === false || animationData === 'false' ? 0 : 1; // true by default

    this[autohide] = options[autohide] === false || autohideData === 'false' ? 0 : 1; // true by default

    this[delay] = parseInt(options[delay] || delayData) || 500; // 500ms default
    // bind,toast and timer

    var self = this,
        timer = 0,
        // get the toast element
    toast = getClosest(element, '.toast'); // private methods
    // animation complete

    var showComplete = function () {
      removeClass(toast, showing);
      addClass(toast, showClass);
      bootstrapCustomEvent.call(toast, shownEvent, component);

      if (self[autohide]) {
        self.hide();
      }
    },
        hideComplete = function () {
      addClass(toast, hide);
      bootstrapCustomEvent.call(toast, hiddenEvent, component);
    },
        close = function () {
      removeClass(toast, showClass);
      self[animation] ? emulateTransitionEnd(toast, hideComplete) : hideComplete();
    },
        disposeComplete = function () {
      clearTimeout(timer);
      timer = null;
      addClass(toast, hide);
      off(element, clickEvent, self.hide);
      element[stringToast] = null;
      element = null;
      toast = null;
    }; // public methods


    this.show = function () {
      if (toast) {
        bootstrapCustomEvent.call(toast, showEvent, component);
        self[animation] && addClass(toast, fade);
        removeClass(toast, hide);
        addClass(toast, showing);
        self[animation] ? emulateTransitionEnd(toast, showComplete) : showComplete();
      }
    };

    this.hide = function (noTimer) {
      if (toast && hasClass(toast, showClass)) {
        bootstrapCustomEvent.call(toast, hideEvent, component);

        if (noTimer) {
          close();
        } else {
          timer = setTimeout(close, self[delay]);
        }
      }
    };

    this.dispose = function () {
      if (toast && hasClass(toast, showClass)) {
        removeClass(toast, showClass);
        self[animation] ? emulateTransitionEnd(toast, disposeComplete) : disposeComplete();
      }
    }; // init


    if (!(stringToast in element)) {
      // prevent adding event handlers twice
      on(element, clickEvent, self.hide);
    }

    element[stringToast] = self;
  }; // TOAST DATA API
  // =================


  supports[push]([stringToast, Toast, '[' + dataDismiss + '="toast"]']);
  /* Native Javascript for Bootstrap 4 | Tooltip
  ---------------------------------------------*/
  // TOOLTIP DEFINITION
  // ==================

  var Tooltip = function (element, options) {
    // initialization element
    element = queryElement(element); // set options

    options = options || {}; // DATA API

    var animationData = element[getAttribute](dataAnimation),
        placementData = element[getAttribute](dataPlacement),
        delayData = element[getAttribute](dataDelay),
        containerData = element[getAttribute](dataContainer),
        // strings
    component = 'tooltip',
        classString = 'class',
        title = 'title',
        fade = 'fade',
        div = 'div',
        // check container
    containerElement = queryElement(options[container]),
        containerDataElement = queryElement(containerData),
        // maybe the element is inside a modal
    modal = getClosest(element, '.modal'),
        // maybe the element is inside a fixed navbar
    navbarFixedTop = getClosest(element, '.' + fixedTop),
        navbarFixedBottom = getClosest(element, '.' + fixedBottom); // set instance options

    this[animation] = options[animation] && options[animation] !== fade ? options[animation] : animationData || fade;
    this[placement] = options[placement] ? options[placement] : placementData || top;
    this[delay] = parseInt(options[delay] || delayData) || 200;
    this[container] = containerElement ? containerElement : containerDataElement ? containerDataElement : navbarFixedTop ? navbarFixedTop : navbarFixedBottom ? navbarFixedBottom : modal ? modal : DOC[body]; // bind, event targets, title and constants

    var self = this,
        timer = 0,
        placementSetting = this[placement],
        tooltip = null,
        titleString = element[getAttribute](title) || element[getAttribute](dataTitle) || element[getAttribute](dataOriginalTitle);
    if (!titleString || titleString == "") return; // invalidate
    // private methods

    var removeToolTip = function () {
      self[container].removeChild(tooltip);
      tooltip = null;
      timer = null;
    },
        createToolTip = function () {
      titleString = element[getAttribute](title) || element[getAttribute](dataTitle) || element[getAttribute](dataOriginalTitle); // read the title again

      if (titleString && titleString !== "") {
        // invalidate, maybe markup changed
        tooltip = DOC[createElement](div);
        tooltip[setAttribute]('role', component);
        tooltip[style][left] = '0';
        tooltip[style][top] = '0'; // tooltip arrow

        var tooltipArrow = DOC[createElement](div);
        tooltipArrow[setAttribute](classString, 'arrow');
        tooltip[appendChild](tooltipArrow);
        var tooltipInner = DOC[createElement](div);
        tooltipInner[setAttribute](classString, component + '-inner');
        tooltip[appendChild](tooltipInner);
        tooltipInner[innerHTML] = titleString;
        self[container][appendChild](tooltip);
        tooltip[setAttribute](classString, component + ' bs-' + component + '-' + placementSetting + ' ' + self[animation]);
      }
    },
        updateTooltip = function () {
      styleTip(element, tooltip, placementSetting, self[container]);
    },
        showTooltip = function () {
      !hasClass(tooltip, showClass) && addClass(tooltip, showClass);
    },
        // triggers
    showTrigger = function () {
      on(globalObject, resizeEvent, self.hide, passiveHandler);
      bootstrapCustomEvent.call(element, shownEvent, component);
    },
        hideTrigger = function () {
      off(globalObject, resizeEvent, self.hide, passiveHandler);
      removeToolTip();
      bootstrapCustomEvent.call(element, hiddenEvent, component);
    }; // public methods


    this.show = function () {
      clearTimeout(timer);
      timer = setTimeout(function () {
        if (tooltip === null) {
          placementSetting = self[placement]; // we reset placement in all cases
          // if(createToolTip() == false) return;

          if (createToolTip() !== false) {
            updateTooltip();
            showTooltip();
            bootstrapCustomEvent.call(element, showEvent, component);
            !!self[animation] ? emulateTransitionEnd(tooltip, showTrigger) : showTrigger();
          }
        }
      }, 20);
    };

    this.hide = function () {
      clearTimeout(timer);
      timer = setTimeout(function () {
        if (tooltip && hasClass(tooltip, showClass)) {
          bootstrapCustomEvent.call(element, hideEvent, component);
          removeClass(tooltip, showClass);
          !!self[animation] ? emulateTransitionEnd(tooltip, hideTrigger) : hideTrigger();
        }
      }, self[delay]);
    };

    this.toggle = function () {
      if (!tooltip) {
        self.show();
      } else {
        self.hide();
      }
    }; // init


    if (!(stringTooltip in element)) {
      // prevent adding event handlers twice
      element[setAttribute](dataOriginalTitle, titleString);
      element.removeAttribute(title);
      on(element, mouseHover[0], self.show);
      on(element, mouseHover[1], self.hide);
    }

    element[stringTooltip] = self;
  }; // TOOLTIP DATA API
  // =================


  supports[push]([stringTooltip, Tooltip, '[' + dataToggle + '="tooltip"]']);
  /* Native Javascript for Bootstrap | Initialize Data API
  --------------------------------------------------------*/

  var initializeDataAPI = function (constructor, collection) {
    for (var i = 0, l = collection[length]; i < l; i++) {
      new constructor(collection[i]);
    }
  },
      initCallback = BSN.initCallback = function (lookUp) {
    lookUp = lookUp || DOC;

    for (var i = 0, l = supports[length]; i < l; i++) {
      initializeDataAPI(supports[i][1], lookUp[querySelectorAll](supports[i][2]));
    }
  }; // bulk initialize all components


  DOC[body] ? initCallback() : on(DOC, 'DOMContentLoaded', function () {
    initCallback();
  });
  return {
    Alert: Alert,
    Button: Button,
    Collapse: Collapse,
    Dropdown: Dropdown,
    Modal: Modal,
    Popover: Popover,
    Tab: Tab,
    Toast: Toast,
    Tooltip: Tooltip
  };
});
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(18)))

/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * URI.js - Mutating URLs
 *
 * Version: 1.19.6
 *
 * Author: Rodney Rehm
 * Web: http://medialize.github.io/URI.js/
 *
 * Licensed under
 *   MIT License http://www.opensource.org/licenses/mit-license
 *
 */
(function (root, factory) {
  'use strict'; // https://github.com/umdjs/umd/blob/master/returnExports.js

  if ( true && module.exports) {
    // Node
    module.exports = factory(__webpack_require__(153), __webpack_require__(154), __webpack_require__(155));
  } else if (true) {
    // AMD. Register as an anonymous module.
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(153), __webpack_require__(154), __webpack_require__(155)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  } else {}
})(this, function (punycode, IPv6, SLD, root) {
  'use strict';
  /*global location, escape, unescape */
  // FIXME: v2.0.0 renamce non-camelCase properties to uppercase

  /*jshint camelcase: false */
  // save current URI variable, if any

  var _URI = root && root.URI;

  function URI(url, base) {
    var _urlSupplied = arguments.length >= 1;

    var _baseSupplied = arguments.length >= 2; // Allow instantiation without the 'new' keyword


    if (!(this instanceof URI)) {
      if (_urlSupplied) {
        if (_baseSupplied) {
          return new URI(url, base);
        }

        return new URI(url);
      }

      return new URI();
    }

    if (url === undefined) {
      if (_urlSupplied) {
        throw new TypeError('undefined is not a valid argument for URI');
      }

      if (typeof location !== 'undefined') {
        url = location.href + '';
      } else {
        url = '';
      }
    }

    if (url === null) {
      if (_urlSupplied) {
        throw new TypeError('null is not a valid argument for URI');
      }
    }

    this.href(url); // resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor

    if (base !== undefined) {
      return this.absoluteTo(base);
    }

    return this;
  }

  function isInteger(value) {
    return /^[0-9]+$/.test(value);
  }

  URI.version = '1.19.6';
  var p = URI.prototype;
  var hasOwn = Object.prototype.hasOwnProperty;

  function escapeRegEx(string) {
    // https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963
    return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  }

  function getType(value) {
    // IE8 doesn't return [Object Undefined] but [Object Object] for undefined value
    if (value === undefined) {
      return 'Undefined';
    }

    return String(Object.prototype.toString.call(value)).slice(8, -1);
  }

  function isArray(obj) {
    return getType(obj) === 'Array';
  }

  function filterArrayValues(data, value) {
    var lookup = {};
    var i, length;

    if (getType(value) === 'RegExp') {
      lookup = null;
    } else if (isArray(value)) {
      for (i = 0, length = value.length; i < length; i++) {
        lookup[value[i]] = true;
      }
    } else {
      lookup[value] = true;
    }

    for (i = 0, length = data.length; i < length; i++) {
      /*jshint laxbreak: true */
      var _match = lookup && lookup[data[i]] !== undefined || !lookup && value.test(data[i]);
      /*jshint laxbreak: false */


      if (_match) {
        data.splice(i, 1);
        length--;
        i--;
      }
    }

    return data;
  }

  function arrayContains(list, value) {
    var i, length; // value may be string, number, array, regexp

    if (isArray(value)) {
      // Note: this can be optimized to O(n) (instead of current O(m * n))
      for (i = 0, length = value.length; i < length; i++) {
        if (!arrayContains(list, value[i])) {
          return false;
        }
      }

      return true;
    }

    var _type = getType(value);

    for (i = 0, length = list.length; i < length; i++) {
      if (_type === 'RegExp') {
        if (typeof list[i] === 'string' && list[i].match(value)) {
          return true;
        }
      } else if (list[i] === value) {
        return true;
      }
    }

    return false;
  }

  function arraysEqual(one, two) {
    if (!isArray(one) || !isArray(two)) {
      return false;
    } // arrays can't be equal if they have different amount of content


    if (one.length !== two.length) {
      return false;
    }

    one.sort();
    two.sort();

    for (var i = 0, l = one.length; i < l; i++) {
      if (one[i] !== two[i]) {
        return false;
      }
    }

    return true;
  }

  function trimSlashes(text) {
    var trim_expression = /^\/+|\/+$/g;
    return text.replace(trim_expression, '');
  }

  URI._parts = function () {
    return {
      protocol: null,
      username: null,
      password: null,
      hostname: null,
      urn: null,
      port: null,
      path: null,
      query: null,
      fragment: null,
      // state
      preventInvalidHostname: URI.preventInvalidHostname,
      duplicateQueryParameters: URI.duplicateQueryParameters,
      escapeQuerySpace: URI.escapeQuerySpace
    };
  }; // state: throw on invalid hostname
  // see https://github.com/medialize/URI.js/pull/345
  // and https://github.com/medialize/URI.js/issues/354


  URI.preventInvalidHostname = false; // state: allow duplicate query parameters (a=1&a=1)

  URI.duplicateQueryParameters = false; // state: replaces + with %20 (space in query strings)

  URI.escapeQuerySpace = true; // static properties

  URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i;
  URI.idn_expression = /[^a-z0-9\._-]/i;
  URI.punycode_expression = /(xn--)/i; // well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care?

  URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; // credits to Rich Brown
  // source: http://forums.intermapper.com/viewtopic.php?p=1096#1096
  // specification: http://www.ietf.org/rfc/rfc4291.txt

  URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/; // expression used is "gruber revised" (@gruber v2) determined to be the
  // best solution in a regex-golf we did a couple of ages ago at
  // * http://mathiasbynens.be/demo/url-regex
  // * http://rodneyrehm.de/t/url-regex.html

  URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig;
  URI.findUri = {
    // valid "scheme://" or "www."
    start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,
    // everything up to the next whitespace
    end: /[\s\r\n]|$/,
    // trim trailing punctuation captured by end RegExp
    trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/,
    // balanced parens inclusion (), [], {}, <>
    parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g
  }; // http://www.iana.org/assignments/uri-schemes.html
  // http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports

  URI.defaultPorts = {
    http: '80',
    https: '443',
    ftp: '21',
    gopher: '70',
    ws: '80',
    wss: '443'
  }; // list of protocols which always require a hostname

  URI.hostProtocols = ['http', 'https']; // allowed hostname characters according to RFC 3986
  // ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded
  // I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _

  URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/; // map DOM Elements to their URI attribute

  URI.domAttributes = {
    'a': 'href',
    'blockquote': 'cite',
    'link': 'href',
    'base': 'href',
    'script': 'src',
    'form': 'action',
    'img': 'src',
    'area': 'href',
    'iframe': 'src',
    'embed': 'src',
    'source': 'src',
    'track': 'src',
    'input': 'src',
    // but only if type="image"
    'audio': 'src',
    'video': 'src'
  };

  URI.getDomAttribute = function (node) {
    if (!node || !node.nodeName) {
      return undefined;
    }

    var nodeName = node.nodeName.toLowerCase(); // <input> should only expose src for type="image"

    if (nodeName === 'input' && node.type !== 'image') {
      return undefined;
    }

    return URI.domAttributes[nodeName];
  };

  function escapeForDumbFirefox36(value) {
    // https://github.com/medialize/URI.js/issues/91
    return escape(value);
  } // encoding / decoding according to RFC3986


  function strictEncodeURIComponent(string) {
    // see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
    return encodeURIComponent(string).replace(/[!'()*]/g, escapeForDumbFirefox36).replace(/\*/g, '%2A');
  }

  URI.encode = strictEncodeURIComponent;
  URI.decode = decodeURIComponent;

  URI.iso8859 = function () {
    URI.encode = escape;
    URI.decode = unescape;
  };

  URI.unicode = function () {
    URI.encode = strictEncodeURIComponent;
    URI.decode = decodeURIComponent;
  };

  URI.characters = {
    pathname: {
      encode: {
        // RFC3986 2.1: For consistency, URI producers and normalizers should
        // use uppercase hexadecimal digits for all percent-encodings.
        expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig,
        map: {
          // -._~!'()*
          '%24': '$',
          '%26': '&',
          '%2B': '+',
          '%2C': ',',
          '%3B': ';',
          '%3D': '=',
          '%3A': ':',
          '%40': '@'
        }
      },
      decode: {
        expression: /[\/\?#]/g,
        map: {
          '/': '%2F',
          '?': '%3F',
          '#': '%23'
        }
      }
    },
    reserved: {
      encode: {
        // RFC3986 2.1: For consistency, URI producers and normalizers should
        // use uppercase hexadecimal digits for all percent-encodings.
        expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,
        map: {
          // gen-delims
          '%3A': ':',
          '%2F': '/',
          '%3F': '?',
          '%23': '#',
          '%5B': '[',
          '%5D': ']',
          '%40': '@',
          // sub-delims
          '%21': '!',
          '%24': '$',
          '%26': '&',
          '%27': '\'',
          '%28': '(',
          '%29': ')',
          '%2A': '*',
          '%2B': '+',
          '%2C': ',',
          '%3B': ';',
          '%3D': '='
        }
      }
    },
    urnpath: {
      // The characters under `encode` are the characters called out by RFC 2141 as being acceptable
      // for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but
      // these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also
      // note that the colon character is not featured in the encoding map; this is because URI.js
      // gives the colons in URNs semantic meaning as the delimiters of path segements, and so it
      // should not appear unencoded in a segment itself.
      // See also the note above about RFC3986 and capitalalized hex digits.
      encode: {
        expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,
        map: {
          '%21': '!',
          '%24': '$',
          '%27': '\'',
          '%28': '(',
          '%29': ')',
          '%2A': '*',
          '%2B': '+',
          '%2C': ',',
          '%3B': ';',
          '%3D': '=',
          '%40': '@'
        }
      },
      // These characters are the characters called out by RFC2141 as "reserved" characters that
      // should never appear in a URN, plus the colon character (see note above).
      decode: {
        expression: /[\/\?#:]/g,
        map: {
          '/': '%2F',
          '?': '%3F',
          '#': '%23',
          ':': '%3A'
        }
      }
    }
  };

  URI.encodeQuery = function (string, escapeQuerySpace) {
    var escaped = URI.encode(string + '');

    if (escapeQuerySpace === undefined) {
      escapeQuerySpace = URI.escapeQuerySpace;
    }

    return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped;
  };

  URI.decodeQuery = function (string, escapeQuerySpace) {
    string += '';

    if (escapeQuerySpace === undefined) {
      escapeQuerySpace = URI.escapeQuerySpace;
    }

    try {
      return URI.decode(escapeQuerySpace ? string.replace(/\+/g, '%20') : string);
    } catch (e) {
      // we're not going to mess with weird encodings,
      // give up and return the undecoded original string
      // see https://github.com/medialize/URI.js/issues/87
      // see https://github.com/medialize/URI.js/issues/92
      return string;
    }
  }; // generate encode/decode path functions


  var _parts = {
    'encode': 'encode',
    'decode': 'decode'
  };

  var _part;

  var generateAccessor = function (_group, _part) {
    return function (string) {
      try {
        return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function (c) {
          return URI.characters[_group][_part].map[c];
        });
      } catch (e) {
        // we're not going to mess with weird encodings,
        // give up and return the undecoded original string
        // see https://github.com/medialize/URI.js/issues/87
        // see https://github.com/medialize/URI.js/issues/92
        return string;
      }
    };
  };

  for (_part in _parts) {
    URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]);
    URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]);
  }

  var generateSegmentedPathFunction = function (_sep, _codingFuncName, _innerCodingFuncName) {
    return function (string) {
      // Why pass in names of functions, rather than the function objects themselves? The
      // definitions of some functions (but in particular, URI.decode) will occasionally change due
      // to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure
      // that the functions we use here are "fresh".
      var actualCodingFunc;

      if (!_innerCodingFuncName) {
        actualCodingFunc = URI[_codingFuncName];
      } else {
        actualCodingFunc = function (string) {
          return URI[_codingFuncName](URI[_innerCodingFuncName](string));
        };
      }

      var segments = (string + '').split(_sep);

      for (var i = 0, length = segments.length; i < length; i++) {
        segments[i] = actualCodingFunc(segments[i]);
      }

      return segments.join(_sep);
    };
  }; // This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions.


  URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment');
  URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment');
  URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode');
  URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode');
  URI.encodeReserved = generateAccessor('reserved', 'encode');

  URI.parse = function (string, parts) {
    var pos;

    if (!parts) {
      parts = {
        preventInvalidHostname: URI.preventInvalidHostname
      };
    } // [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment]
    // extract fragment


    pos = string.indexOf('#');

    if (pos > -1) {
      // escaping?
      parts.fragment = string.substring(pos + 1) || null;
      string = string.substring(0, pos);
    } // extract query


    pos = string.indexOf('?');

    if (pos > -1) {
      // escaping?
      parts.query = string.substring(pos + 1) || null;
      string = string.substring(0, pos);
    } // extract protocol


    if (string.substring(0, 2) === '//') {
      // relative-scheme
      parts.protocol = null;
      string = string.substring(2); // extract "user:pass@host:port"

      string = URI.parseAuthority(string, parts);
    } else {
      pos = string.indexOf(':');

      if (pos > -1) {
        parts.protocol = string.substring(0, pos) || null;

        if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {
          // : may be within the path
          parts.protocol = undefined;
        } else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') {
          string = string.substring(pos + 3); // extract "user:pass@host:port"

          string = URI.parseAuthority(string, parts);
        } else {
          string = string.substring(pos + 1);
          parts.urn = true;
        }
      }
    } // what's left must be the path


    parts.path = string; // and we're done

    return parts;
  };

  URI.parseHost = function (string, parts) {
    if (!string) {
      string = '';
    } // Copy chrome, IE, opera backslash-handling behavior.
    // Back slashes before the query string get converted to forward slashes
    // See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124
    // See: https://code.google.com/p/chromium/issues/detail?id=25916
    // https://github.com/medialize/URI.js/pull/233


    string = string.replace(/\\/g, '/'); // extract host:port

    var pos = string.indexOf('/');
    var bracketPos;
    var t;

    if (pos === -1) {
      pos = string.length;
    }

    if (string.charAt(0) === '[') {
      // IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6
      // I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts
      // IPv6+port in the format [2001:db8::1]:80 (for the time being)
      bracketPos = string.indexOf(']');
      parts.hostname = string.substring(1, bracketPos) || null;
      parts.port = string.substring(bracketPos + 2, pos) || null;

      if (parts.port === '/') {
        parts.port = null;
      }
    } else {
      var firstColon = string.indexOf(':');
      var firstSlash = string.indexOf('/');
      var nextColon = string.indexOf(':', firstColon + 1);

      if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) {
        // IPv6 host contains multiple colons - but no port
        // this notation is actually not allowed by RFC 3986, but we're a liberal parser
        parts.hostname = string.substring(0, pos) || null;
        parts.port = null;
      } else {
        t = string.substring(0, pos).split(':');
        parts.hostname = t[0] || null;
        parts.port = t[1] || null;
      }
    }

    if (parts.hostname && string.substring(pos).charAt(0) !== '/') {
      pos++;
      string = '/' + string;
    }

    if (parts.preventInvalidHostname) {
      URI.ensureValidHostname(parts.hostname, parts.protocol);
    }

    if (parts.port) {
      URI.ensureValidPort(parts.port);
    }

    return string.substring(pos) || '/';
  };

  URI.parseAuthority = function (string, parts) {
    string = URI.parseUserinfo(string, parts);
    return URI.parseHost(string, parts);
  };

  URI.parseUserinfo = function (string, parts) {
    // extract username:password
    var _string = string;
    var firstBackSlash = string.indexOf('\\');

    if (firstBackSlash !== -1) {
      string = string.replace(/\\/g, '/');
    }

    var firstSlash = string.indexOf('/');
    var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1);
    var t; // authority@ must come before /path or \path

    if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) {
      t = string.substring(0, pos).split(':');
      parts.username = t[0] ? URI.decode(t[0]) : null;
      t.shift();
      parts.password = t[0] ? URI.decode(t.join(':')) : null;
      string = _string.substring(pos + 1);
    } else {
      parts.username = null;
      parts.password = null;
    }

    return string;
  };

  URI.parseQuery = function (string, escapeQuerySpace) {
    if (!string) {
      return {};
    } // throw out the funky business - "?"[name"="value"&"]+


    string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, '');

    if (!string) {
      return {};
    }

    var items = {};
    var splits = string.split('&');
    var length = splits.length;
    var v, name, value;

    for (var i = 0; i < length; i++) {
      v = splits[i].split('=');
      name = URI.decodeQuery(v.shift(), escapeQuerySpace); // no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters

      value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null;

      if (hasOwn.call(items, name)) {
        if (typeof items[name] === 'string' || items[name] === null) {
          items[name] = [items[name]];
        }

        items[name].push(value);
      } else {
        items[name] = value;
      }
    }

    return items;
  };

  URI.build = function (parts) {
    var t = '';
    var requireAbsolutePath = false;

    if (parts.protocol) {
      t += parts.protocol + ':';
    }

    if (!parts.urn && (t || parts.hostname)) {
      t += '//';
      requireAbsolutePath = true;
    }

    t += URI.buildAuthority(parts) || '';

    if (typeof parts.path === 'string') {
      if (parts.path.charAt(0) !== '/' && requireAbsolutePath) {
        t += '/';
      }

      t += parts.path;
    }

    if (typeof parts.query === 'string' && parts.query) {
      t += '?' + parts.query;
    }

    if (typeof parts.fragment === 'string' && parts.fragment) {
      t += '#' + parts.fragment;
    }

    return t;
  };

  URI.buildHost = function (parts) {
    var t = '';

    if (!parts.hostname) {
      return '';
    } else if (URI.ip6_expression.test(parts.hostname)) {
      t += '[' + parts.hostname + ']';
    } else {
      t += parts.hostname;
    }

    if (parts.port) {
      t += ':' + parts.port;
    }

    return t;
  };

  URI.buildAuthority = function (parts) {
    return URI.buildUserinfo(parts) + URI.buildHost(parts);
  };

  URI.buildUserinfo = function (parts) {
    var t = '';

    if (parts.username) {
      t += URI.encode(parts.username);
    }

    if (parts.password) {
      t += ':' + URI.encode(parts.password);
    }

    if (t) {
      t += '@';
    }

    return t;
  };

  URI.buildQuery = function (data, duplicateQueryParameters, escapeQuerySpace) {
    // according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html
    // being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed
    // the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax!
    // URI.js treats the query string as being application/x-www-form-urlencoded
    // see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type
    var t = '';
    var unique, key, i, length;

    for (key in data) {
      if (hasOwn.call(data, key)) {
        if (isArray(data[key])) {
          unique = {};

          for (i = 0, length = data[key].length; i < length; i++) {
            if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) {
              t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace);

              if (duplicateQueryParameters !== true) {
                unique[data[key][i] + ''] = true;
              }
            }
          }
        } else if (data[key] !== undefined) {
          t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace);
        }
      }
    }

    return t.substring(1);
  };

  URI.buildQueryParameter = function (name, value, escapeQuerySpace) {
    // http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded
    // don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization
    return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : '');
  };

  URI.addQuery = function (data, name, value) {
    if (typeof name === 'object') {
      for (var key in name) {
        if (hasOwn.call(name, key)) {
          URI.addQuery(data, key, name[key]);
        }
      }
    } else if (typeof name === 'string') {
      if (data[name] === undefined) {
        data[name] = value;
        return;
      } else if (typeof data[name] === 'string') {
        data[name] = [data[name]];
      }

      if (!isArray(value)) {
        value = [value];
      }

      data[name] = (data[name] || []).concat(value);
    } else {
      throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
    }
  };

  URI.setQuery = function (data, name, value) {
    if (typeof name === 'object') {
      for (var key in name) {
        if (hasOwn.call(name, key)) {
          URI.setQuery(data, key, name[key]);
        }
      }
    } else if (typeof name === 'string') {
      data[name] = value === undefined ? null : value;
    } else {
      throw new TypeError('URI.setQuery() accepts an object, string as the name parameter');
    }
  };

  URI.removeQuery = function (data, name, value) {
    var i, length, key;

    if (isArray(name)) {
      for (i = 0, length = name.length; i < length; i++) {
        data[name[i]] = undefined;
      }
    } else if (getType(name) === 'RegExp') {
      for (key in data) {
        if (name.test(key)) {
          data[key] = undefined;
        }
      }
    } else if (typeof name === 'object') {
      for (key in name) {
        if (hasOwn.call(name, key)) {
          URI.removeQuery(data, key, name[key]);
        }
      }
    } else if (typeof name === 'string') {
      if (value !== undefined) {
        if (getType(value) === 'RegExp') {
          if (!isArray(data[name]) && value.test(data[name])) {
            data[name] = undefined;
          } else {
            data[name] = filterArrayValues(data[name], value);
          }
        } else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) {
          data[name] = undefined;
        } else if (isArray(data[name])) {
          data[name] = filterArrayValues(data[name], value);
        }
      } else {
        data[name] = undefined;
      }
    } else {
      throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter');
    }
  };

  URI.hasQuery = function (data, name, value, withinArray) {
    switch (getType(name)) {
      case 'String':
        // Nothing to do here
        break;

      case 'RegExp':
        for (var key in data) {
          if (hasOwn.call(data, key)) {
            if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) {
              return true;
            }
          }
        }

        return false;

      case 'Object':
        for (var _key in name) {
          if (hasOwn.call(name, _key)) {
            if (!URI.hasQuery(data, _key, name[_key])) {
              return false;
            }
          }
        }

        return true;

      default:
        throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter');
    }

    switch (getType(value)) {
      case 'Undefined':
        // true if exists (but may be empty)
        return name in data;
      // data[name] !== undefined;

      case 'Boolean':
        // true if exists and non-empty
        var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]);

        return value === _booly;

      case 'Function':
        // allow complex comparison
        return !!value(data[name], name, data);

      case 'Array':
        if (!isArray(data[name])) {
          return false;
        }

        var op = withinArray ? arrayContains : arraysEqual;
        return op(data[name], value);

      case 'RegExp':
        if (!isArray(data[name])) {
          return Boolean(data[name] && data[name].match(value));
        }

        if (!withinArray) {
          return false;
        }

        return arrayContains(data[name], value);

      case 'Number':
        value = String(value);

      /* falls through */

      case 'String':
        if (!isArray(data[name])) {
          return data[name] === value;
        }

        if (!withinArray) {
          return false;
        }

        return arrayContains(data[name], value);

      default:
        throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter');
    }
  };

  URI.joinPaths = function () {
    var input = [];
    var segments = [];
    var nonEmptySegments = 0;

    for (var i = 0; i < arguments.length; i++) {
      var url = new URI(arguments[i]);
      input.push(url);

      var _segments = url.segment();

      for (var s = 0; s < _segments.length; s++) {
        if (typeof _segments[s] === 'string') {
          segments.push(_segments[s]);
        }

        if (_segments[s]) {
          nonEmptySegments++;
        }
      }
    }

    if (!segments.length || !nonEmptySegments) {
      return new URI('');
    }

    var uri = new URI('').segment(segments);

    if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') {
      uri.path('/' + uri.path());
    }

    return uri.normalize();
  };

  URI.commonPath = function (one, two) {
    var length = Math.min(one.length, two.length);
    var pos; // find first non-matching character

    for (pos = 0; pos < length; pos++) {
      if (one.charAt(pos) !== two.charAt(pos)) {
        pos--;
        break;
      }
    }

    if (pos < 1) {
      return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : '';
    } // revert to last /


    if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') {
      pos = one.substring(0, pos).lastIndexOf('/');
    }

    return one.substring(0, pos + 1);
  };

  URI.withinString = function (string, callback, options) {
    options || (options = {});

    var _start = options.start || URI.findUri.start;

    var _end = options.end || URI.findUri.end;

    var _trim = options.trim || URI.findUri.trim;

    var _parens = options.parens || URI.findUri.parens;

    var _attributeOpen = /[a-z0-9-]=["']?$/i;
    _start.lastIndex = 0;

    while (true) {
      var match = _start.exec(string);

      if (!match) {
        break;
      }

      var start = match.index;

      if (options.ignoreHtml) {
        // attribut(e=["']?$)
        var attributeOpen = string.slice(Math.max(start - 3, 0), start);

        if (attributeOpen && _attributeOpen.test(attributeOpen)) {
          continue;
        }
      }

      var end = start + string.slice(start).search(_end);
      var slice = string.slice(start, end); // make sure we include well balanced parens

      var parensEnd = -1;

      while (true) {
        var parensMatch = _parens.exec(slice);

        if (!parensMatch) {
          break;
        }

        var parensMatchEnd = parensMatch.index + parensMatch[0].length;
        parensEnd = Math.max(parensEnd, parensMatchEnd);
      }

      if (parensEnd > -1) {
        slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, '');
      } else {
        slice = slice.replace(_trim, '');
      }

      if (slice.length <= match[0].length) {
        // the extract only contains the starting marker of a URI,
        // e.g. "www" or "http://"
        continue;
      }

      if (options.ignore && options.ignore.test(slice)) {
        continue;
      }

      end = start + slice.length;
      var result = callback(slice, start, end, string);

      if (result === undefined) {
        _start.lastIndex = end;
        continue;
      }

      result = String(result);
      string = string.slice(0, start) + result + string.slice(end);
      _start.lastIndex = start + result.length;
    }

    _start.lastIndex = 0;
    return string;
  };

  URI.ensureValidHostname = function (v, protocol) {
    // Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986)
    // they are not part of DNS and therefore ignored by URI.js
    var hasHostname = !!v; // not null and not an empty string

    var hasProtocol = !!protocol;
    var rejectEmptyHostname = false;

    if (hasProtocol) {
      rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol);
    }

    if (rejectEmptyHostname && !hasHostname) {
      throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol);
    } else if (v && v.match(URI.invalid_hostname_characters)) {
      // test punycode
      if (!punycode) {
        throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');
      }

      if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) {
        throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]');
      }
    }
  };

  URI.ensureValidPort = function (v) {
    if (!v) {
      return;
    }

    var port = Number(v);

    if (isInteger(port) && port > 0 && port < 65536) {
      return;
    }

    throw new TypeError('Port "' + v + '" is not a valid port');
  }; // noConflict


  URI.noConflict = function (removeAll) {
    if (removeAll) {
      var unconflicted = {
        URI: this.noConflict()
      };

      if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') {
        unconflicted.URITemplate = root.URITemplate.noConflict();
      }

      if (root.IPv6 && typeof root.IPv6.noConflict === 'function') {
        unconflicted.IPv6 = root.IPv6.noConflict();
      }

      if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') {
        unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict();
      }

      return unconflicted;
    } else if (root.URI === this) {
      root.URI = _URI;
    }

    return this;
  };

  p.build = function (deferBuild) {
    if (deferBuild === true) {
      this._deferred_build = true;
    } else if (deferBuild === undefined || this._deferred_build) {
      this._string = URI.build(this._parts);
      this._deferred_build = false;
    }

    return this;
  };

  p.clone = function () {
    return new URI(this);
  };

  p.valueOf = p.toString = function () {
    return this.build(false)._string;
  };

  function generateSimpleAccessor(_part) {
    return function (v, build) {
      if (v === undefined) {
        return this._parts[_part] || '';
      } else {
        this._parts[_part] = v || null;
        this.build(!build);
        return this;
      }
    };
  }

  function generatePrefixAccessor(_part, _key) {
    return function (v, build) {
      if (v === undefined) {
        return this._parts[_part] || '';
      } else {
        if (v !== null) {
          v = v + '';

          if (v.charAt(0) === _key) {
            v = v.substring(1);
          }
        }

        this._parts[_part] = v;
        this.build(!build);
        return this;
      }
    };
  }

  p.protocol = generateSimpleAccessor('protocol');
  p.username = generateSimpleAccessor('username');
  p.password = generateSimpleAccessor('password');
  p.hostname = generateSimpleAccessor('hostname');
  p.port = generateSimpleAccessor('port');
  p.query = generatePrefixAccessor('query', '?');
  p.fragment = generatePrefixAccessor('fragment', '#');

  p.search = function (v, build) {
    var t = this.query(v, build);
    return typeof t === 'string' && t.length ? '?' + t : t;
  };

  p.hash = function (v, build) {
    var t = this.fragment(v, build);
    return typeof t === 'string' && t.length ? '#' + t : t;
  };

  p.pathname = function (v, build) {
    if (v === undefined || v === true) {
      var res = this._parts.path || (this._parts.hostname ? '/' : '');
      return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res;
    } else {
      if (this._parts.urn) {
        this._parts.path = v ? URI.recodeUrnPath(v) : '';
      } else {
        this._parts.path = v ? URI.recodePath(v) : '/';
      }

      this.build(!build);
      return this;
    }
  };

  p.path = p.pathname;

  p.href = function (href, build) {
    var key;

    if (href === undefined) {
      return this.toString();
    }

    this._string = '';
    this._parts = URI._parts();

    var _URI = href instanceof URI;

    var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname);

    if (href.nodeName) {
      var attribute = URI.getDomAttribute(href);
      href = href[attribute] || '';
      _object = false;
    } // window.location is reported to be an object, but it's not the sort
    // of object we're looking for:
    // * location.protocol ends with a colon
    // * location.query != object.search
    // * location.hash != object.fragment
    // simply serializing the unknown object should do the trick
    // (for location, not for everything...)


    if (!_URI && _object && href.pathname !== undefined) {
      href = href.toString();
    }

    if (typeof href === 'string' || href instanceof String) {
      this._parts = URI.parse(String(href), this._parts);
    } else if (_URI || _object) {
      var src = _URI ? href._parts : href;

      for (key in src) {
        if (key === 'query') {
          continue;
        }

        if (hasOwn.call(this._parts, key)) {
          this._parts[key] = src[key];
        }
      }

      if (src.query) {
        this.query(src.query, false);
      }
    } else {
      throw new TypeError('invalid input');
    }

    this.build(!build);
    return this;
  }; // identification accessors


  p.is = function (what) {
    var ip = false;
    var ip4 = false;
    var ip6 = false;
    var name = false;
    var sld = false;
    var idn = false;
    var punycode = false;
    var relative = !this._parts.urn;

    if (this._parts.hostname) {
      relative = false;
      ip4 = URI.ip4_expression.test(this._parts.hostname);
      ip6 = URI.ip6_expression.test(this._parts.hostname);
      ip = ip4 || ip6;
      name = !ip;
      sld = name && SLD && SLD.has(this._parts.hostname);
      idn = name && URI.idn_expression.test(this._parts.hostname);
      punycode = name && URI.punycode_expression.test(this._parts.hostname);
    }

    switch (what.toLowerCase()) {
      case 'relative':
        return relative;

      case 'absolute':
        return !relative;
      // hostname identification

      case 'domain':
      case 'name':
        return name;

      case 'sld':
        return sld;

      case 'ip':
        return ip;

      case 'ip4':
      case 'ipv4':
      case 'inet4':
        return ip4;

      case 'ip6':
      case 'ipv6':
      case 'inet6':
        return ip6;

      case 'idn':
        return idn;

      case 'url':
        return !this._parts.urn;

      case 'urn':
        return !!this._parts.urn;

      case 'punycode':
        return punycode;
    }

    return null;
  }; // component specific input validation


  var _protocol = p.protocol;
  var _port = p.port;
  var _hostname = p.hostname;

  p.protocol = function (v, build) {
    if (v) {
      // accept trailing ://
      v = v.replace(/:(\/\/)?$/, '');

      if (!v.match(URI.protocol_expression)) {
        throw new TypeError('Protocol "' + v + '" contains characters other than [A-Z0-9.+-] or doesn\'t start with [A-Z]');
      }
    }

    return _protocol.call(this, v, build);
  };

  p.scheme = p.protocol;

  p.port = function (v, build) {
    if (this._parts.urn) {
      return v === undefined ? '' : this;
    }

    if (v !== undefined) {
      if (v === 0) {
        v = null;
      }

      if (v) {
        v += '';

        if (v.charAt(0) === ':') {
          v = v.substring(1);
        }

        URI.ensureValidPort(v);
      }
    }

    return _port.call(this, v, build);
  };

  p.hostname = function (v, build) {
    if (this._parts.urn) {
      return v === undefined ? '' : this;
    }

    if (v !== undefined) {
      var x = {
        preventInvalidHostname: this._parts.preventInvalidHostname
      };
      var res = URI.parseHost(v, x);

      if (res !== '/') {
        throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
      }

      v = x.hostname;

      if (this._parts.preventInvalidHostname) {
        URI.ensureValidHostname(v, this._parts.protocol);
      }
    }

    return _hostname.call(this, v, build);
  }; // compound accessors


  p.origin = function (v, build) {
    if (this._parts.urn) {
      return v === undefined ? '' : this;
    }

    if (v === undefined) {
      var protocol = this.protocol();
      var authority = this.authority();

      if (!authority) {
        return '';
      }

      return (protocol ? protocol + '://' : '') + this.authority();
    } else {
      var origin = URI(v);
      this.protocol(origin.protocol()).authority(origin.authority()).build(!build);
      return this;
    }
  };

  p.host = function (v, build) {
    if (this._parts.urn) {
      return v === undefined ? '' : this;
    }

    if (v === undefined) {
      return this._parts.hostname ? URI.buildHost(this._parts) : '';
    } else {
      var res = URI.parseHost(v, this._parts);

      if (res !== '/') {
        throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
      }

      this.build(!build);
      return this;
    }
  };

  p.authority = function (v, build) {
    if (this._parts.urn) {
      return v === undefined ? '' : this;
    }

    if (v === undefined) {
      return this._parts.hostname ? URI.buildAuthority(this._parts) : '';
    } else {
      var res = URI.parseAuthority(v, this._parts);

      if (res !== '/') {
        throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
      }

      this.build(!build);
      return this;
    }
  };

  p.userinfo = function (v, build) {
    if (this._parts.urn) {
      return v === undefined ? '' : this;
    }

    if (v === undefined) {
      var t = URI.buildUserinfo(this._parts);
      return t ? t.substring(0, t.length - 1) : t;
    } else {
      if (v[v.length - 1] !== '@') {
        v += '@';
      }

      URI.parseUserinfo(v, this._parts);
      this.build(!build);
      return this;
    }
  };

  p.resource = function (v, build) {
    var parts;

    if (v === undefined) {
      return this.path() + this.search() + this.hash();
    }

    parts = URI.parse(v);
    this._parts.path = parts.path;
    this._parts.query = parts.query;
    this._parts.fragment = parts.fragment;
    this.build(!build);
    return this;
  }; // fraction accessors


  p.subdomain = function (v, build) {
    if (this._parts.urn) {
      return v === undefined ? '' : this;
    } // convenience, return "www" from "www.example.org"


    if (v === undefined) {
      if (!this._parts.hostname || this.is('IP')) {
        return '';
      } // grab domain and add another segment


      var end = this._parts.hostname.length - this.domain().length - 1;
      return this._parts.hostname.substring(0, end) || '';
    } else {
      var e = this._parts.hostname.length - this.domain().length;

      var sub = this._parts.hostname.substring(0, e);

      var replace = new RegExp('^' + escapeRegEx(sub));

      if (v && v.charAt(v.length - 1) !== '.') {
        v += '.';
      }

      if (v.indexOf(':') !== -1) {
        throw new TypeError('Domains cannot contain colons');
      }

      if (v) {
        URI.ensureValidHostname(v, this._parts.protocol);
      }

      this._parts.hostname = this._parts.hostname.replace(replace, v);
      this.build(!build);
      return this;
    }
  };

  p.domain = function (v, build) {
    if (this._parts.urn) {
      return v === undefined ? '' : this;
    }

    if (typeof v === 'boolean') {
      build = v;
      v = undefined;
    } // convenience, return "example.org" from "www.example.org"


    if (v === undefined) {
      if (!this._parts.hostname || this.is('IP')) {
        return '';
      } // if hostname consists of 1 or 2 segments, it must be the domain


      var t = this._parts.hostname.match(/\./g);

      if (t && t.length < 2) {
        return this._parts.hostname;
      } // grab tld and add another segment


      var end = this._parts.hostname.length - this.tld(build).length - 1;
      end = this._parts.hostname.lastIndexOf('.', end - 1) + 1;
      return this._parts.hostname.substring(end) || '';
    } else {
      if (!v) {
        throw new TypeError('cannot set domain empty');
      }

      if (v.indexOf(':') !== -1) {
        throw new TypeError('Domains cannot contain colons');
      }

      URI.ensureValidHostname(v, this._parts.protocol);

      if (!this._parts.hostname || this.is('IP')) {
        this._parts.hostname = v;
      } else {
        var replace = new RegExp(escapeRegEx(this.domain()) + '$');
        this._parts.hostname = this._parts.hostname.replace(replace, v);
      }

      this.build(!build);
      return this;
    }
  };

  p.tld = function (v, build) {
    if (this._parts.urn) {
      return v === undefined ? '' : this;
    }

    if (typeof v === 'boolean') {
      build = v;
      v = undefined;
    } // return "org" from "www.example.org"


    if (v === undefined) {
      if (!this._parts.hostname || this.is('IP')) {
        return '';
      }

      var pos = this._parts.hostname.lastIndexOf('.');

      var tld = this._parts.hostname.substring(pos + 1);

      if (build !== true && SLD && SLD.list[tld.toLowerCase()]) {
        return SLD.get(this._parts.hostname) || tld;
      }

      return tld;
    } else {
      var replace;

      if (!v) {
        throw new TypeError('cannot set TLD empty');
      } else if (v.match(/[^a-zA-Z0-9-]/)) {
        if (SLD && SLD.is(v)) {
          replace = new RegExp(escapeRegEx(this.tld()) + '$');
          this._parts.hostname = this._parts.hostname.replace(replace, v);
        } else {
          throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]');
        }
      } else if (!this._parts.hostname || this.is('IP')) {
        throw new ReferenceError('cannot set TLD on non-domain host');
      } else {
        replace = new RegExp(escapeRegEx(this.tld()) + '$');
        this._parts.hostname = this._parts.hostname.replace(replace, v);
      }

      this.build(!build);
      return this;
    }
  };

  p.directory = function (v, build) {
    if (this._parts.urn) {
      return v === undefined ? '' : this;
    }

    if (v === undefined || v === true) {
      if (!this._parts.path && !this._parts.hostname) {
        return '';
      }

      if (this._parts.path === '/') {
        return '/';
      }

      var end = this._parts.path.length - this.filename().length - 1;
      var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : '');
      return v ? URI.decodePath(res) : res;
    } else {
      var e = this._parts.path.length - this.filename().length;

      var directory = this._parts.path.substring(0, e);

      var replace = new RegExp('^' + escapeRegEx(directory)); // fully qualifier directories begin with a slash

      if (!this.is('relative')) {
        if (!v) {
          v = '/';
        }

        if (v.charAt(0) !== '/') {
          v = '/' + v;
        }
      } // directories always end with a slash


      if (v && v.charAt(v.length - 1) !== '/') {
        v += '/';
      }

      v = URI.recodePath(v);
      this._parts.path = this._parts.path.replace(replace, v);
      this.build(!build);
      return this;
    }
  };

  p.filename = function (v, build) {
    if (this._parts.urn) {
      return v === undefined ? '' : this;
    }

    if (typeof v !== 'string') {
      if (!this._parts.path || this._parts.path === '/') {
        return '';
      }

      var pos = this._parts.path.lastIndexOf('/');

      var res = this._parts.path.substring(pos + 1);

      return v ? URI.decodePathSegment(res) : res;
    } else {
      var mutatedDirectory = false;

      if (v.charAt(0) === '/') {
        v = v.substring(1);
      }

      if (v.match(/\.?\//)) {
        mutatedDirectory = true;
      }

      var replace = new RegExp(escapeRegEx(this.filename()) + '$');
      v = URI.recodePath(v);
      this._parts.path = this._parts.path.replace(replace, v);

      if (mutatedDirectory) {
        this.normalizePath(build);
      } else {
        this.build(!build);
      }

      return this;
    }
  };

  p.suffix = function (v, build) {
    if (this._parts.urn) {
      return v === undefined ? '' : this;
    }

    if (v === undefined || v === true) {
      if (!this._parts.path || this._parts.path === '/') {
        return '';
      }

      var filename = this.filename();
      var pos = filename.lastIndexOf('.');
      var s, res;

      if (pos === -1) {
        return '';
      } // suffix may only contain alnum characters (yup, I made this up.)


      s = filename.substring(pos + 1);
      res = /^[a-z0-9%]+$/i.test(s) ? s : '';
      return v ? URI.decodePathSegment(res) : res;
    } else {
      if (v.charAt(0) === '.') {
        v = v.substring(1);
      }

      var suffix = this.suffix();
      var replace;

      if (!suffix) {
        if (!v) {
          return this;
        }

        this._parts.path += '.' + URI.recodePath(v);
      } else if (!v) {
        replace = new RegExp(escapeRegEx('.' + suffix) + '$');
      } else {
        replace = new RegExp(escapeRegEx(suffix) + '$');
      }

      if (replace) {
        v = URI.recodePath(v);
        this._parts.path = this._parts.path.replace(replace, v);
      }

      this.build(!build);
      return this;
    }
  };

  p.segment = function (segment, v, build) {
    var separator = this._parts.urn ? ':' : '/';
    var path = this.path();
    var absolute = path.substring(0, 1) === '/';
    var segments = path.split(separator);

    if (segment !== undefined && typeof segment !== 'number') {
      build = v;
      v = segment;
      segment = undefined;
    }

    if (segment !== undefined && typeof segment !== 'number') {
      throw new Error('Bad segment "' + segment + '", must be 0-based integer');
    }

    if (absolute) {
      segments.shift();
    }

    if (segment < 0) {
      // allow negative indexes to address from the end
      segment = Math.max(segments.length + segment, 0);
    }

    if (v === undefined) {
      /*jshint laxbreak: true */
      return segment === undefined ? segments : segments[segment];
      /*jshint laxbreak: false */
    } else if (segment === null || segments[segment] === undefined) {
      if (isArray(v)) {
        segments = []; // collapse empty elements within array

        for (var i = 0, l = v.length; i < l; i++) {
          if (!v[i].length && (!segments.length || !segments[segments.length - 1].length)) {
            continue;
          }

          if (segments.length && !segments[segments.length - 1].length) {
            segments.pop();
          }

          segments.push(trimSlashes(v[i]));
        }
      } else if (v || typeof v === 'string') {
        v = trimSlashes(v);

        if (segments[segments.length - 1] === '') {
          // empty trailing elements have to be overwritten
          // to prevent results such as /foo//bar
          segments[segments.length - 1] = v;
        } else {
          segments.push(v);
        }
      }
    } else {
      if (v) {
        segments[segment] = trimSlashes(v);
      } else {
        segments.splice(segment, 1);
      }
    }

    if (absolute) {
      segments.unshift('');
    }

    return this.path(segments.join(separator), build);
  };

  p.segmentCoded = function (segment, v, build) {
    var segments, i, l;

    if (typeof segment !== 'number') {
      build = v;
      v = segment;
      segment = undefined;
    }

    if (v === undefined) {
      segments = this.segment(segment, v, build);

      if (!isArray(segments)) {
        segments = segments !== undefined ? URI.decode(segments) : undefined;
      } else {
        for (i = 0, l = segments.length; i < l; i++) {
          segments[i] = URI.decode(segments[i]);
        }
      }

      return segments;
    }

    if (!isArray(v)) {
      v = typeof v === 'string' || v instanceof String ? URI.encode(v) : v;
    } else {
      for (i = 0, l = v.length; i < l; i++) {
        v[i] = URI.encode(v[i]);
      }
    }

    return this.segment(segment, v, build);
  }; // mutating query string


  var q = p.query;

  p.query = function (v, build) {
    if (v === true) {
      return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
    } else if (typeof v === 'function') {
      var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
      var result = v.call(this, data);
      this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
      this.build(!build);
      return this;
    } else if (v !== undefined && typeof v !== 'string') {
      this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
      this.build(!build);
      return this;
    } else {
      return q.call(this, v, build);
    }
  };

  p.setQuery = function (name, value, build) {
    var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);

    if (typeof name === 'string' || name instanceof String) {
      data[name] = value !== undefined ? value : null;
    } else if (typeof name === 'object') {
      for (var key in name) {
        if (hasOwn.call(name, key)) {
          data[key] = name[key];
        }
      }
    } else {
      throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
    }

    this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);

    if (typeof name !== 'string') {
      build = value;
    }

    this.build(!build);
    return this;
  };

  p.addQuery = function (name, value, build) {
    var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
    URI.addQuery(data, name, value === undefined ? null : value);
    this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);

    if (typeof name !== 'string') {
      build = value;
    }

    this.build(!build);
    return this;
  };

  p.removeQuery = function (name, value, build) {
    var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
    URI.removeQuery(data, name, value);
    this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);

    if (typeof name !== 'string') {
      build = value;
    }

    this.build(!build);
    return this;
  };

  p.hasQuery = function (name, value, withinArray) {
    var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
    return URI.hasQuery(data, name, value, withinArray);
  };

  p.setSearch = p.setQuery;
  p.addSearch = p.addQuery;
  p.removeSearch = p.removeQuery;
  p.hasSearch = p.hasQuery; // sanitizing URLs

  p.normalize = function () {
    if (this._parts.urn) {
      return this.normalizeProtocol(false).normalizePath(false).normalizeQuery(false).normalizeFragment(false).build();
    }

    return this.normalizeProtocol(false).normalizeHostname(false).normalizePort(false).normalizePath(false).normalizeQuery(false).normalizeFragment(false).build();
  };

  p.normalizeProtocol = function (build) {
    if (typeof this._parts.protocol === 'string') {
      this._parts.protocol = this._parts.protocol.toLowerCase();
      this.build(!build);
    }

    return this;
  };

  p.normalizeHostname = function (build) {
    if (this._parts.hostname) {
      if (this.is('IDN') && punycode) {
        this._parts.hostname = punycode.toASCII(this._parts.hostname);
      } else if (this.is('IPv6') && IPv6) {
        this._parts.hostname = IPv6.best(this._parts.hostname);
      }

      this._parts.hostname = this._parts.hostname.toLowerCase();
      this.build(!build);
    }

    return this;
  };

  p.normalizePort = function (build) {
    // remove port of it's the protocol's default
    if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) {
      this._parts.port = null;
      this.build(!build);
    }

    return this;
  };

  p.normalizePath = function (build) {
    var _path = this._parts.path;

    if (!_path) {
      return this;
    }

    if (this._parts.urn) {
      this._parts.path = URI.recodeUrnPath(this._parts.path);
      this.build(!build);
      return this;
    }

    if (this._parts.path === '/') {
      return this;
    }

    _path = URI.recodePath(_path);

    var _was_relative;

    var _leadingParents = '';

    var _parent, _pos; // handle relative paths


    if (_path.charAt(0) !== '/') {
      _was_relative = true;
      _path = '/' + _path;
    } // handle relative files (as opposed to directories)


    if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') {
      _path += '/';
    } // resolve simples


    _path = _path.replace(/(\/(\.\/)+)|(\/\.$)/g, '/').replace(/\/{2,}/g, '/'); // remember leading parents

    if (_was_relative) {
      _leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || '';

      if (_leadingParents) {
        _leadingParents = _leadingParents[0];
      }
    } // resolve parents


    while (true) {
      _parent = _path.search(/\/\.\.(\/|$)/);

      if (_parent === -1) {
        // no more ../ to resolve
        break;
      } else if (_parent === 0) {
        // top level cannot be relative, skip it
        _path = _path.substring(3);
        continue;
      }

      _pos = _path.substring(0, _parent).lastIndexOf('/');

      if (_pos === -1) {
        _pos = _parent;
      }

      _path = _path.substring(0, _pos) + _path.substring(_parent + 3);
    } // revert to relative


    if (_was_relative && this.is('relative')) {
      _path = _leadingParents + _path.substring(1);
    }

    this._parts.path = _path;
    this.build(!build);
    return this;
  };

  p.normalizePathname = p.normalizePath;

  p.normalizeQuery = function (build) {
    if (typeof this._parts.query === 'string') {
      if (!this._parts.query.length) {
        this._parts.query = null;
      } else {
        this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace));
      }

      this.build(!build);
    }

    return this;
  };

  p.normalizeFragment = function (build) {
    if (!this._parts.fragment) {
      this._parts.fragment = null;
      this.build(!build);
    }

    return this;
  };

  p.normalizeSearch = p.normalizeQuery;
  p.normalizeHash = p.normalizeFragment;

  p.iso8859 = function () {
    // expect unicode input, iso8859 output
    var e = URI.encode;
    var d = URI.decode;
    URI.encode = escape;
    URI.decode = decodeURIComponent;

    try {
      this.normalize();
    } finally {
      URI.encode = e;
      URI.decode = d;
    }

    return this;
  };

  p.unicode = function () {
    // expect iso8859 input, unicode output
    var e = URI.encode;
    var d = URI.decode;
    URI.encode = strictEncodeURIComponent;
    URI.decode = unescape;

    try {
      this.normalize();
    } finally {
      URI.encode = e;
      URI.decode = d;
    }

    return this;
  };

  p.readable = function () {
    var uri = this.clone(); // removing username, password, because they shouldn't be displayed according to RFC 3986

    uri.username('').password('').normalize();
    var t = '';

    if (uri._parts.protocol) {
      t += uri._parts.protocol + '://';
    }

    if (uri._parts.hostname) {
      if (uri.is('punycode') && punycode) {
        t += punycode.toUnicode(uri._parts.hostname);

        if (uri._parts.port) {
          t += ':' + uri._parts.port;
        }
      } else {
        t += uri.host();
      }
    }

    if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') {
      t += '/';
    }

    t += uri.path(true);

    if (uri._parts.query) {
      var q = '';

      for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) {
        var kv = (qp[i] || '').split('=');
        q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace).replace(/&/g, '%26');

        if (kv[1] !== undefined) {
          q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace).replace(/&/g, '%26');
        }
      }

      t += '?' + q.substring(1);
    }

    t += URI.decodeQuery(uri.hash(), true);
    return t;
  }; // resolving relative and absolute URLs


  p.absoluteTo = function (base) {
    var resolved = this.clone();
    var properties = ['protocol', 'username', 'password', 'hostname', 'port'];
    var basedir, i, p;

    if (this._parts.urn) {
      throw new Error('URNs do not have any generally defined hierarchical components');
    }

    if (!(base instanceof URI)) {
      base = new URI(base);
    }

    if (resolved._parts.protocol) {
      // Directly returns even if this._parts.hostname is empty.
      return resolved;
    } else {
      resolved._parts.protocol = base._parts.protocol;
    }

    if (this._parts.hostname) {
      return resolved;
    }

    for (i = 0; p = properties[i]; i++) {
      resolved._parts[p] = base._parts[p];
    }

    if (!resolved._parts.path) {
      resolved._parts.path = base._parts.path;

      if (!resolved._parts.query) {
        resolved._parts.query = base._parts.query;
      }
    } else {
      if (resolved._parts.path.substring(-2) === '..') {
        resolved._parts.path += '/';
      }

      if (resolved.path().charAt(0) !== '/') {
        basedir = base.directory();
        basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : '';
        resolved._parts.path = (basedir ? basedir + '/' : '') + resolved._parts.path;
        resolved.normalizePath();
      }
    }

    resolved.build();
    return resolved;
  };

  p.relativeTo = function (base) {
    var relative = this.clone().normalize();
    var relativeParts, baseParts, common, relativePath, basePath;

    if (relative._parts.urn) {
      throw new Error('URNs do not have any generally defined hierarchical components');
    }

    base = new URI(base).normalize();
    relativeParts = relative._parts;
    baseParts = base._parts;
    relativePath = relative.path();
    basePath = base.path();

    if (relativePath.charAt(0) !== '/') {
      throw new Error('URI is already relative');
    }

    if (basePath.charAt(0) !== '/') {
      throw new Error('Cannot calculate a URI relative to another relative URI');
    }

    if (relativeParts.protocol === baseParts.protocol) {
      relativeParts.protocol = null;
    }

    if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) {
      return relative.build();
    }

    if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) {
      return relative.build();
    }

    if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) {
      relativeParts.hostname = null;
      relativeParts.port = null;
    } else {
      return relative.build();
    }

    if (relativePath === basePath) {
      relativeParts.path = '';
      return relative.build();
    } // determine common sub path


    common = URI.commonPath(relativePath, basePath); // If the paths have nothing in common, return a relative URL with the absolute path.

    if (!common) {
      return relative.build();
    }

    var parents = baseParts.path.substring(common.length).replace(/[^\/]*$/, '').replace(/.*?\//g, '../');
    relativeParts.path = parents + relativeParts.path.substring(common.length) || './';
    return relative.build();
  }; // comparing URIs


  p.equals = function (uri) {
    var one = this.clone();
    var two = new URI(uri);
    var one_map = {};
    var two_map = {};
    var checked = {};
    var one_query, two_query, key;
    one.normalize();
    two.normalize(); // exact match

    if (one.toString() === two.toString()) {
      return true;
    } // extract query string


    one_query = one.query();
    two_query = two.query();
    one.query('');
    two.query(''); // definitely not equal if not even non-query parts match

    if (one.toString() !== two.toString()) {
      return false;
    } // query parameters have the same length, even if they're permuted


    if (one_query.length !== two_query.length) {
      return false;
    }

    one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace);
    two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace);

    for (key in one_map) {
      if (hasOwn.call(one_map, key)) {
        if (!isArray(one_map[key])) {
          if (one_map[key] !== two_map[key]) {
            return false;
          }
        } else if (!arraysEqual(one_map[key], two_map[key])) {
          return false;
        }

        checked[key] = true;
      }
    }

    for (key in two_map) {
      if (hasOwn.call(two_map, key)) {
        if (!checked[key]) {
          // two contains a parameter not present in one
          return false;
        }
      }
    }

    return true;
  }; // state


  p.preventInvalidHostname = function (v) {
    this._parts.preventInvalidHostname = !!v;
    return this;
  };

  p.duplicateQueryParameters = function (v) {
    this._parts.duplicateQueryParameters = !!v;
    return this;
  };

  p.escapeQuerySpace = function (v) {
    this._parts.escapeQuerySpace = !!v;
    return this;
  };

  return URI;
});

/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {

var baseIndexOf = __webpack_require__(111),
    isArrayLike = __webpack_require__(25),
    isString = __webpack_require__(112),
    toInteger = __webpack_require__(67),
    values = __webpack_require__(89);
/* Built-in method references for those with the same name as other `lodash` methods. */


var nativeMax = Math.max;
/**
 * Checks if `value` is in `collection`. If `collection` is a string, it's
 * checked for a substring of `value`, otherwise
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * is used for equality comparisons. If `fromIndex` is negative, it's used as
 * the offset from the end of `collection`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object|string} collection The collection to inspect.
 * @param {*} value The value to search for.
 * @param {number} [fromIndex=0] The index to search from.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
 * @returns {boolean} Returns `true` if `value` is found, else `false`.
 * @example
 *
 * _.includes([1, 2, 3], 1);
 * // => true
 *
 * _.includes([1, 2, 3], 1, 2);
 * // => false
 *
 * _.includes({ 'a': 1, 'b': 2 }, 1);
 * // => true
 *
 * _.includes('abcd', 'bc');
 * // => true
 */

function includes(collection, value, fromIndex, guard) {
  collection = isArrayLike(collection) ? collection : values(collection);
  fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0;
  var length = collection.length;

  if (fromIndex < 0) {
    fromIndex = nativeMax(length + fromIndex, 0);
  }

  return isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1;
}

module.exports = includes;

/***/ }),
/* 33 */
/***/ (function(module, exports) {

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used to detect unsigned integer values. */

var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
 * Checks if `value` is a valid array-like index.
 *
 * @private
 * @param {*} value The value to check.
 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
 */

function isIndex(value, length) {
  var type = typeof value;
  length = length == null ? MAX_SAFE_INTEGER : length;
  return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
}

module.exports = isIndex;

/***/ }),
/* 34 */
/***/ (function(module, exports) {

/**
 * This method returns the first argument it receives.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {*} value Any value.
 * @returns {*} Returns `value`.
 * @example
 *
 * var object = { 'a': 1 };
 *
 * console.log(_.identity(object) === object);
 * // => true
 */
function identity(value) {
  return value;
}

module.exports = identity;

/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {

var isSymbol = __webpack_require__(44);
/** Used as references for various `Number` constants. */


var INFINITY = 1 / 0;
/**
 * Converts `value` to a string key if it's not a string or symbol.
 *
 * @private
 * @param {*} value The value to inspect.
 * @returns {string|symbol} Returns the key.
 */

function toKey(value) {
  if (typeof value == 'string' || isSymbol(value)) {
    return value;
  }

  var result = value + '';
  return result == '0' && 1 / value == -INFINITY ? '-0' : result;
}

module.exports = toKey;

/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {

var anObject = __webpack_require__(22);

var IE8_DOM_DEFINE = __webpack_require__(449);

var toPrimitive = __webpack_require__(450);

var dP = Object.defineProperty;
exports.f = __webpack_require__(28) ? Object.defineProperty : function defineProperty(O, P, Attributes) {
  anObject(O);
  P = toPrimitive(P, true);
  anObject(Attributes);
  if (IE8_DOM_DEFINE) try {
    return dP(O, P, Attributes);
  } catch (e) {
    /* empty */
  }
  if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
  if ('value' in Attributes) O[P] = Attributes.value;
  return O;
};

/***/ }),
/* 37 */
/***/ (function(module, exports) {

module.exports = function (it) {
  return typeof it === 'object' ? it !== null : typeof it === 'function';
};

/***/ }),
/* 38 */
/***/ (function(module, exports) {

module.exports = {};

/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global, module) {var __WEBPACK_AMD_DEFINE_RESULT__;/**
 * @license
 * Lodash <https://lodash.com/>
 * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
 * Released under MIT license <https://lodash.com/license>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 */;(function(){/** Used as a safe reference for `undefined` in pre-ES5 environments. */var undefined;/** Used as the semantic version number. */var VERSION='4.17.21';/** Used as the size to enable large array optimizations. */var LARGE_ARRAY_SIZE=200;/** Error message constants. */var CORE_ERROR_TEXT='Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',FUNC_ERROR_TEXT='Expected a function',INVALID_TEMPL_VAR_ERROR_TEXT='Invalid `variable` option passed into `_.template`';/** Used to stand-in for `undefined` hash values. */var HASH_UNDEFINED='__lodash_hash_undefined__';/** Used as the maximum memoize cache size. */var MAX_MEMOIZE_SIZE=500;/** Used as the internal argument placeholder. */var PLACEHOLDER='__lodash_placeholder__';/** Used to compose bitmasks for cloning. */var CLONE_DEEP_FLAG=1,CLONE_FLAT_FLAG=2,CLONE_SYMBOLS_FLAG=4;/** Used to compose bitmasks for value comparisons. */var COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2;/** Used to compose bitmasks for function metadata. */var WRAP_BIND_FLAG=1,WRAP_BIND_KEY_FLAG=2,WRAP_CURRY_BOUND_FLAG=4,WRAP_CURRY_FLAG=8,WRAP_CURRY_RIGHT_FLAG=16,WRAP_PARTIAL_FLAG=32,WRAP_PARTIAL_RIGHT_FLAG=64,WRAP_ARY_FLAG=128,WRAP_REARG_FLAG=256,WRAP_FLIP_FLAG=512;/** Used as default options for `_.truncate`. */var DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION='...';/** Used to detect hot functions by number of calls within a span of milliseconds. */var HOT_COUNT=800,HOT_SPAN=16;/** Used to indicate the type of lazy iteratees. */var LAZY_FILTER_FLAG=1,LAZY_MAP_FLAG=2,LAZY_WHILE_FLAG=3;/** Used as references for various `Number` constants. */var INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e+308,NAN=0/0;/** Used as references for the maximum length and index of an array. */var MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1;/** Used to associate wrap methods with their bit flags. */var wrapFlags=[['ary',WRAP_ARY_FLAG],['bind',WRAP_BIND_FLAG],['bindKey',WRAP_BIND_KEY_FLAG],['curry',WRAP_CURRY_FLAG],['curryRight',WRAP_CURRY_RIGHT_FLAG],['flip',WRAP_FLIP_FLAG],['partial',WRAP_PARTIAL_FLAG],['partialRight',WRAP_PARTIAL_RIGHT_FLAG],['rearg',WRAP_REARG_FLAG]];/** `Object#toString` result references. */var argsTag='[object Arguments]',arrayTag='[object Array]',asyncTag='[object AsyncFunction]',boolTag='[object Boolean]',dateTag='[object Date]',domExcTag='[object DOMException]',errorTag='[object Error]',funcTag='[object Function]',genTag='[object GeneratorFunction]',mapTag='[object Map]',numberTag='[object Number]',nullTag='[object Null]',objectTag='[object Object]',promiseTag='[object Promise]',proxyTag='[object Proxy]',regexpTag='[object RegExp]',setTag='[object Set]',stringTag='[object String]',symbolTag='[object Symbol]',undefinedTag='[object Undefined]',weakMapTag='[object WeakMap]',weakSetTag='[object WeakSet]';var arrayBufferTag='[object ArrayBuffer]',dataViewTag='[object DataView]',float32Tag='[object Float32Array]',float64Tag='[object Float64Array]',int8Tag='[object Int8Array]',int16Tag='[object Int16Array]',int32Tag='[object Int32Array]',uint8Tag='[object Uint8Array]',uint8ClampedTag='[object Uint8ClampedArray]',uint16Tag='[object Uint16Array]',uint32Tag='[object Uint32Array]';/** Used to match empty string literals in compiled template source. */var reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g;/** Used to match HTML entities and HTML characters. */var reEscapedHtml=/&(?:amp|lt|gt|quot|#39);/g,reUnescapedHtml=/[&<>"']/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source);/** Used to match template delimiters. */var reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g;/** Used to match property names within property paths. */var reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;/**
   * Used to match `RegExp`
   * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
   */var reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source);/** Used to match leading whitespace. */var reTrimStart=/^\s+/;/** Used to match a single whitespace character. */var reWhitespace=/\s/;/** Used to match wrap detail comments. */var reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /;/** Used to match words composed of alphanumeric characters. */var reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;/**
   * Used to validate the `validate` option in `_.template` variable.
   *
   * Forbids characters which could potentially change the meaning of the function argument definition:
   * - "()," (modification of function parameters)
   * - "=" (default value)
   * - "[]{}" (destructuring of function parameters)
   * - "/" (beginning of a comment)
   * - whitespace
   */var reForbiddenIdentifierChars=/[()=,{}\[\]\/\s]/;/** Used to match backslashes in property paths. */var reEscapeChar=/\\(\\)?/g;/**
   * Used to match
   * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
   */var reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;/** Used to match `RegExp` flags from their coerced string values. */var reFlags=/\w*$/;/** Used to detect bad signed hexadecimal string values. */var reIsBadHex=/^[-+]0x[0-9a-f]+$/i;/** Used to detect binary string values. */var reIsBinary=/^0b[01]+$/i;/** Used to detect host constructors (Safari). */var reIsHostCtor=/^\[object .+?Constructor\]$/;/** Used to detect octal string values. */var reIsOctal=/^0o[0-7]+$/i;/** Used to detect unsigned integer values. */var reIsUint=/^(?:0|[1-9]\d*)$/;/** Used to match Latin Unicode letters (excluding mathematical operators). */var reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;/** Used to ensure capturing order of template delimiters. */var reNoMatch=/($^)/;/** Used to match unescaped characters in compiled string literals. */var reUnescapedString=/['\n\r\u2028\u2029\\]/g;/** Used to compose unicode character classes. */var rsAstralRange='\\ud800-\\udfff',rsComboMarksRange='\\u0300-\\u036f',reComboHalfMarksRange='\\ufe20-\\ufe2f',rsComboSymbolsRange='\\u20d0-\\u20ff',rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange,rsDingbatRange='\\u2700-\\u27bf',rsLowerRange='a-z\\xdf-\\xf6\\xf8-\\xff',rsMathOpRange='\\xac\\xb1\\xd7\\xf7',rsNonCharRange='\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',rsPunctuationRange='\\u2000-\\u206f',rsSpaceRange=' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',rsUpperRange='A-Z\\xc0-\\xd6\\xd8-\\xde',rsVarRange='\\ufe0e\\ufe0f',rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange;/** Used to compose unicode capture groups. */var rsApos="['\u2019]",rsAstral='['+rsAstralRange+']',rsBreak='['+rsBreakRange+']',rsCombo='['+rsComboRange+']',rsDigits='\\d+',rsDingbat='['+rsDingbatRange+']',rsLower='['+rsLowerRange+']',rsMisc='[^'+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+']',rsFitz='\\ud83c[\\udffb-\\udfff]',rsModifier='(?:'+rsCombo+'|'+rsFitz+')',rsNonAstral='[^'+rsAstralRange+']',rsRegional='(?:\\ud83c[\\udde6-\\uddff]){2}',rsSurrPair='[\\ud800-\\udbff][\\udc00-\\udfff]',rsUpper='['+rsUpperRange+']',rsZWJ='\\u200d';/** Used to compose unicode regexes. */var rsMiscLower='(?:'+rsLower+'|'+rsMisc+')',rsMiscUpper='(?:'+rsUpper+'|'+rsMisc+')',rsOptContrLower='(?:'+rsApos+'(?:d|ll|m|re|s|t|ve))?',rsOptContrUpper='(?:'+rsApos+'(?:D|LL|M|RE|S|T|VE))?',reOptMod=rsModifier+'?',rsOptVar='['+rsVarRange+']?',rsOptJoin='(?:'+rsZWJ+'(?:'+[rsNonAstral,rsRegional,rsSurrPair].join('|')+')'+rsOptVar+reOptMod+')*',rsOrdLower='\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',rsOrdUpper='\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji='(?:'+[rsDingbat,rsRegional,rsSurrPair].join('|')+')'+rsSeq,rsSymbol='(?:'+[rsNonAstral+rsCombo+'?',rsCombo,rsRegional,rsSurrPair,rsAstral].join('|')+')';/** Used to match apostrophes. */var reApos=RegExp(rsApos,'g');/**
   * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
   * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
   */var reComboMark=RegExp(rsCombo,'g');/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */var reUnicode=RegExp(rsFitz+'(?='+rsFitz+')|'+rsSymbol+rsSeq,'g');/** Used to match complex or compound words. */var reUnicodeWord=RegExp([rsUpper+'?'+rsLower+'+'+rsOptContrLower+'(?='+[rsBreak,rsUpper,'$'].join('|')+')',rsMiscUpper+'+'+rsOptContrUpper+'(?='+[rsBreak,rsUpper+rsMiscLower,'$'].join('|')+')',rsUpper+'?'+rsMiscLower+'+'+rsOptContrLower,rsUpper+'+'+rsOptContrUpper,rsOrdUpper,rsOrdLower,rsDigits,rsEmoji].join('|'),'g');/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */var reHasUnicode=RegExp('['+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+']');/** Used to detect strings that need a more robust regexp to match words. */var reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;/** Used to assign default `context` object properties. */var contextProps=['Array','Buffer','DataView','Date','Error','Float32Array','Float64Array','Function','Int8Array','Int16Array','Int32Array','Map','Math','Object','Promise','RegExp','Set','String','Symbol','TypeError','Uint8Array','Uint8ClampedArray','Uint16Array','Uint32Array','WeakMap','_','clearTimeout','isFinite','parseInt','setTimeout'];/** Used to make template sourceURLs easier to identify. */var templateCounter=-1;/** Used to identify `toStringTag` values of typed arrays. */var typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=true;typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=false;/** Used to identify `toStringTag` values supported by `_.clone`. */var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=true;cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=false;/** Used to map Latin Unicode letters to basic Latin letters. */var deburredLetters={// Latin-1 Supplement block.
'\xc0':'A','\xc1':'A','\xc2':'A','\xc3':'A','\xc4':'A','\xc5':'A','\xe0':'a','\xe1':'a','\xe2':'a','\xe3':'a','\xe4':'a','\xe5':'a','\xc7':'C','\xe7':'c','\xd0':'D','\xf0':'d','\xc8':'E','\xc9':'E','\xca':'E','\xcb':'E','\xe8':'e','\xe9':'e','\xea':'e','\xeb':'e','\xcc':'I','\xcd':'I','\xce':'I','\xcf':'I','\xec':'i','\xed':'i','\xee':'i','\xef':'i','\xd1':'N','\xf1':'n','\xd2':'O','\xd3':'O','\xd4':'O','\xd5':'O','\xd6':'O','\xd8':'O','\xf2':'o','\xf3':'o','\xf4':'o','\xf5':'o','\xf6':'o','\xf8':'o','\xd9':'U','\xda':'U','\xdb':'U','\xdc':'U','\xf9':'u','\xfa':'u','\xfb':'u','\xfc':'u','\xdd':'Y','\xfd':'y','\xff':'y','\xc6':'Ae','\xe6':'ae','\xde':'Th','\xfe':'th','\xdf':'ss',// Latin Extended-A block.
'\u0100':'A','\u0102':'A','\u0104':'A','\u0101':'a','\u0103':'a','\u0105':'a','\u0106':'C','\u0108':'C','\u010a':'C','\u010c':'C','\u0107':'c','\u0109':'c','\u010b':'c','\u010d':'c','\u010e':'D','\u0110':'D','\u010f':'d','\u0111':'d','\u0112':'E','\u0114':'E','\u0116':'E','\u0118':'E','\u011a':'E','\u0113':'e','\u0115':'e','\u0117':'e','\u0119':'e','\u011b':'e','\u011c':'G','\u011e':'G','\u0120':'G','\u0122':'G','\u011d':'g','\u011f':'g','\u0121':'g','\u0123':'g','\u0124':'H','\u0126':'H','\u0125':'h','\u0127':'h','\u0128':'I','\u012a':'I','\u012c':'I','\u012e':'I','\u0130':'I','\u0129':'i','\u012b':'i','\u012d':'i','\u012f':'i','\u0131':'i','\u0134':'J','\u0135':'j','\u0136':'K','\u0137':'k','\u0138':'k','\u0139':'L','\u013b':'L','\u013d':'L','\u013f':'L','\u0141':'L','\u013a':'l','\u013c':'l','\u013e':'l','\u0140':'l','\u0142':'l','\u0143':'N','\u0145':'N','\u0147':'N','\u014a':'N','\u0144':'n','\u0146':'n','\u0148':'n','\u014b':'n','\u014c':'O','\u014e':'O','\u0150':'O','\u014d':'o','\u014f':'o','\u0151':'o','\u0154':'R','\u0156':'R','\u0158':'R','\u0155':'r','\u0157':'r','\u0159':'r','\u015a':'S','\u015c':'S','\u015e':'S','\u0160':'S','\u015b':'s','\u015d':'s','\u015f':'s','\u0161':'s','\u0162':'T','\u0164':'T','\u0166':'T','\u0163':'t','\u0165':'t','\u0167':'t','\u0168':'U','\u016a':'U','\u016c':'U','\u016e':'U','\u0170':'U','\u0172':'U','\u0169':'u','\u016b':'u','\u016d':'u','\u016f':'u','\u0171':'u','\u0173':'u','\u0174':'W','\u0175':'w','\u0176':'Y','\u0177':'y','\u0178':'Y','\u0179':'Z','\u017b':'Z','\u017d':'Z','\u017a':'z','\u017c':'z','\u017e':'z','\u0132':'IJ','\u0133':'ij','\u0152':'Oe','\u0153':'oe','\u0149':"'n",'\u017f':'s'};/** Used to map characters to HTML entities. */var htmlEscapes={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'};/** Used to map HTML entities to characters. */var htmlUnescapes={'&amp;':'&','&lt;':'<','&gt;':'>','&quot;':'"','&#39;':"'"};/** Used to escape characters for inclusion in compiled string literals. */var stringEscapes={'\\':'\\',"'":"'",'\n':'n','\r':'r','\u2028':'u2028','\u2029':'u2029'};/** Built-in method references without a dependency on `root`. */var freeParseFloat=parseFloat,freeParseInt=parseInt;/** Detect free variable `global` from Node.js. */var freeGlobal=typeof global=='object'&&global&&global.Object===Object&&global;/** Detect free variable `self`. */var freeSelf=typeof self=='object'&&self&&self.Object===Object&&self;/** Used as a reference to the global object. */var root=freeGlobal||freeSelf||Function('return this')();/** Detect free variable `exports`. */var freeExports= true&&exports&&!exports.nodeType&&exports;/** Detect free variable `module`. */var freeModule=freeExports&&typeof module=='object'&&module&&!module.nodeType&&module;/** Detect the popular CommonJS extension `module.exports`. */var moduleExports=freeModule&&freeModule.exports===freeExports;/** Detect free variable `process` from Node.js. */var freeProcess=moduleExports&&freeGlobal.process;/** Used to access faster Node.js helpers. */var nodeUtil=function(){try{// Use `util.types` for Node.js 10+.
var types=freeModule&&freeModule.require&&freeModule.require('util').types;if(types){return types;}// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess&&freeProcess.binding&&freeProcess.binding('util');}catch(e){}}();/* Node.js helper references. */var nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray;/*--------------------------------------------------------------------------*/ /**
   * A faster alternative to `Function#apply`, this function invokes `func`
   * with the `this` binding of `thisArg` and the arguments of `args`.
   *
   * @private
   * @param {Function} func The function to invoke.
   * @param {*} thisArg The `this` binding of `func`.
   * @param {Array} args The arguments to invoke `func` with.
   * @returns {*} Returns the result of `func`.
   */function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2]);}return func.apply(thisArg,args);}/**
   * A specialized version of `baseAggregator` for arrays.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} setter The function to set `accumulator` values.
   * @param {Function} iteratee The iteratee to transform keys.
   * @param {Object} accumulator The initial aggregated object.
   * @returns {Function} Returns `accumulator`.
   */function arrayAggregator(array,setter,iteratee,accumulator){var index=-1,length=array==null?0:array.length;while(++index<length){var value=array[index];setter(accumulator,value,iteratee(value),array);}return accumulator;}/**
   * A specialized version of `_.forEach` for arrays without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @returns {Array} Returns `array`.
   */function arrayEach(array,iteratee){var index=-1,length=array==null?0:array.length;while(++index<length){if(iteratee(array[index],index,array)===false){break;}}return array;}/**
   * A specialized version of `_.forEachRight` for arrays without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @returns {Array} Returns `array`.
   */function arrayEachRight(array,iteratee){var length=array==null?0:array.length;while(length--){if(iteratee(array[length],length,array)===false){break;}}return array;}/**
   * A specialized version of `_.every` for arrays without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} predicate The function invoked per iteration.
   * @returns {boolean} Returns `true` if all elements pass the predicate check,
   *  else `false`.
   */function arrayEvery(array,predicate){var index=-1,length=array==null?0:array.length;while(++index<length){if(!predicate(array[index],index,array)){return false;}}return true;}/**
   * A specialized version of `_.filter` for arrays without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} predicate The function invoked per iteration.
   * @returns {Array} Returns the new filtered array.
   */function arrayFilter(array,predicate){var index=-1,length=array==null?0:array.length,resIndex=0,result=[];while(++index<length){var value=array[index];if(predicate(value,index,array)){result[resIndex++]=value;}}return result;}/**
   * A specialized version of `_.includes` for arrays without support for
   * specifying an index to search from.
   *
   * @private
   * @param {Array} [array] The array to inspect.
   * @param {*} target The value to search for.
   * @returns {boolean} Returns `true` if `target` is found, else `false`.
   */function arrayIncludes(array,value){var length=array==null?0:array.length;return!!length&&baseIndexOf(array,value,0)>-1;}/**
   * This function is like `arrayIncludes` except that it accepts a comparator.
   *
   * @private
   * @param {Array} [array] The array to inspect.
   * @param {*} target The value to search for.
   * @param {Function} comparator The comparator invoked per element.
   * @returns {boolean} Returns `true` if `target` is found, else `false`.
   */function arrayIncludesWith(array,value,comparator){var index=-1,length=array==null?0:array.length;while(++index<length){if(comparator(value,array[index])){return true;}}return false;}/**
   * A specialized version of `_.map` for arrays without support for iteratee
   * shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @returns {Array} Returns the new mapped array.
   */function arrayMap(array,iteratee){var index=-1,length=array==null?0:array.length,result=Array(length);while(++index<length){result[index]=iteratee(array[index],index,array);}return result;}/**
   * Appends the elements of `values` to `array`.
   *
   * @private
   * @param {Array} array The array to modify.
   * @param {Array} values The values to append.
   * @returns {Array} Returns `array`.
   */function arrayPush(array,values){var index=-1,length=values.length,offset=array.length;while(++index<length){array[offset+index]=values[index];}return array;}/**
   * A specialized version of `_.reduce` for arrays without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @param {*} [accumulator] The initial value.
   * @param {boolean} [initAccum] Specify using the first element of `array` as
   *  the initial value.
   * @returns {*} Returns the accumulated value.
   */function arrayReduce(array,iteratee,accumulator,initAccum){var index=-1,length=array==null?0:array.length;if(initAccum&&length){accumulator=array[++index];}while(++index<length){accumulator=iteratee(accumulator,array[index],index,array);}return accumulator;}/**
   * A specialized version of `_.reduceRight` for arrays without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @param {*} [accumulator] The initial value.
   * @param {boolean} [initAccum] Specify using the last element of `array` as
   *  the initial value.
   * @returns {*} Returns the accumulated value.
   */function arrayReduceRight(array,iteratee,accumulator,initAccum){var length=array==null?0:array.length;if(initAccum&&length){accumulator=array[--length];}while(length--){accumulator=iteratee(accumulator,array[length],length,array);}return accumulator;}/**
   * A specialized version of `_.some` for arrays without support for iteratee
   * shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} predicate The function invoked per iteration.
   * @returns {boolean} Returns `true` if any element passes the predicate check,
   *  else `false`.
   */function arraySome(array,predicate){var index=-1,length=array==null?0:array.length;while(++index<length){if(predicate(array[index],index,array)){return true;}}return false;}/**
   * Gets the size of an ASCII `string`.
   *
   * @private
   * @param {string} string The string inspect.
   * @returns {number} Returns the string size.
   */var asciiSize=baseProperty('length');/**
   * Converts an ASCII `string` to an array.
   *
   * @private
   * @param {string} string The string to convert.
   * @returns {Array} Returns the converted array.
   */function asciiToArray(string){return string.split('');}/**
   * Splits an ASCII `string` into an array of its words.
   *
   * @private
   * @param {string} The string to inspect.
   * @returns {Array} Returns the words of `string`.
   */function asciiWords(string){return string.match(reAsciiWord)||[];}/**
   * The base implementation of methods like `_.findKey` and `_.findLastKey`,
   * without support for iteratee shorthands, which iterates over `collection`
   * using `eachFunc`.
   *
   * @private
   * @param {Array|Object} collection The collection to inspect.
   * @param {Function} predicate The function invoked per iteration.
   * @param {Function} eachFunc The function to iterate over `collection`.
   * @returns {*} Returns the found element or its key, else `undefined`.
   */function baseFindKey(collection,predicate,eachFunc){var result;eachFunc(collection,function(value,key,collection){if(predicate(value,key,collection)){result=key;return false;}});return result;}/**
   * The base implementation of `_.findIndex` and `_.findLastIndex` without
   * support for iteratee shorthands.
   *
   * @private
   * @param {Array} array The array to inspect.
   * @param {Function} predicate The function invoked per iteration.
   * @param {number} fromIndex The index to search from.
   * @param {boolean} [fromRight] Specify iterating from right to left.
   * @returns {number} Returns the index of the matched value, else `-1`.
   */function baseFindIndex(array,predicate,fromIndex,fromRight){var length=array.length,index=fromIndex+(fromRight?1:-1);while(fromRight?index--:++index<length){if(predicate(array[index],index,array)){return index;}}return-1;}/**
   * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
   *
   * @private
   * @param {Array} array The array to inspect.
   * @param {*} value The value to search for.
   * @param {number} fromIndex The index to search from.
   * @returns {number} Returns the index of the matched value, else `-1`.
   */function baseIndexOf(array,value,fromIndex){return value===value?strictIndexOf(array,value,fromIndex):baseFindIndex(array,baseIsNaN,fromIndex);}/**
   * This function is like `baseIndexOf` except that it accepts a comparator.
   *
   * @private
   * @param {Array} array The array to inspect.
   * @param {*} value The value to search for.
   * @param {number} fromIndex The index to search from.
   * @param {Function} comparator The comparator invoked per element.
   * @returns {number} Returns the index of the matched value, else `-1`.
   */function baseIndexOfWith(array,value,fromIndex,comparator){var index=fromIndex-1,length=array.length;while(++index<length){if(comparator(array[index],value)){return index;}}return-1;}/**
   * The base implementation of `_.isNaN` without support for number objects.
   *
   * @private
   * @param {*} value The value to check.
   * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
   */function baseIsNaN(value){return value!==value;}/**
   * The base implementation of `_.mean` and `_.meanBy` without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} array The array to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @returns {number} Returns the mean.
   */function baseMean(array,iteratee){var length=array==null?0:array.length;return length?baseSum(array,iteratee)/length:NAN;}/**
   * The base implementation of `_.property` without support for deep paths.
   *
   * @private
   * @param {string} key The key of the property to get.
   * @returns {Function} Returns the new accessor function.
   */function baseProperty(key){return function(object){return object==null?undefined:object[key];};}/**
   * The base implementation of `_.propertyOf` without support for deep paths.
   *
   * @private
   * @param {Object} object The object to query.
   * @returns {Function} Returns the new accessor function.
   */function basePropertyOf(object){return function(key){return object==null?undefined:object[key];};}/**
   * The base implementation of `_.reduce` and `_.reduceRight`, without support
   * for iteratee shorthands, which iterates over `collection` using `eachFunc`.
   *
   * @private
   * @param {Array|Object} collection The collection to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @param {*} accumulator The initial value.
   * @param {boolean} initAccum Specify using the first or last element of
   *  `collection` as the initial value.
   * @param {Function} eachFunc The function to iterate over `collection`.
   * @returns {*} Returns the accumulated value.
   */function baseReduce(collection,iteratee,accumulator,initAccum,eachFunc){eachFunc(collection,function(value,index,collection){accumulator=initAccum?(initAccum=false,value):iteratee(accumulator,value,index,collection);});return accumulator;}/**
   * The base implementation of `_.sortBy` which uses `comparer` to define the
   * sort order of `array` and replaces criteria objects with their corresponding
   * values.
   *
   * @private
   * @param {Array} array The array to sort.
   * @param {Function} comparer The function to define sort order.
   * @returns {Array} Returns `array`.
   */function baseSortBy(array,comparer){var length=array.length;array.sort(comparer);while(length--){array[length]=array[length].value;}return array;}/**
   * The base implementation of `_.sum` and `_.sumBy` without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} array The array to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @returns {number} Returns the sum.
   */function baseSum(array,iteratee){var result,index=-1,length=array.length;while(++index<length){var current=iteratee(array[index]);if(current!==undefined){result=result===undefined?current:result+current;}}return result;}/**
   * The base implementation of `_.times` without support for iteratee shorthands
   * or max array length checks.
   *
   * @private
   * @param {number} n The number of times to invoke `iteratee`.
   * @param {Function} iteratee The function invoked per iteration.
   * @returns {Array} Returns the array of results.
   */function baseTimes(n,iteratee){var index=-1,result=Array(n);while(++index<n){result[index]=iteratee(index);}return result;}/**
   * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
   * of key-value pairs for `object` corresponding to the property names of `props`.
   *
   * @private
   * @param {Object} object The object to query.
   * @param {Array} props The property names to get values for.
   * @returns {Object} Returns the key-value pairs.
   */function baseToPairs(object,props){return arrayMap(props,function(key){return[key,object[key]];});}/**
   * The base implementation of `_.trim`.
   *
   * @private
   * @param {string} string The string to trim.
   * @returns {string} Returns the trimmed string.
   */function baseTrim(string){return string?string.slice(0,trimmedEndIndex(string)+1).replace(reTrimStart,''):string;}/**
   * The base implementation of `_.unary` without support for storing metadata.
   *
   * @private
   * @param {Function} func The function to cap arguments for.
   * @returns {Function} Returns the new capped function.
   */function baseUnary(func){return function(value){return func(value);};}/**
   * The base implementation of `_.values` and `_.valuesIn` which creates an
   * array of `object` property values corresponding to the property names
   * of `props`.
   *
   * @private
   * @param {Object} object The object to query.
   * @param {Array} props The property names to get values for.
   * @returns {Object} Returns the array of property values.
   */function baseValues(object,props){return arrayMap(props,function(key){return object[key];});}/**
   * Checks if a `cache` value for `key` exists.
   *
   * @private
   * @param {Object} cache The cache to query.
   * @param {string} key The key of the entry to check.
   * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
   */function cacheHas(cache,key){return cache.has(key);}/**
   * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
   * that is not found in the character symbols.
   *
   * @private
   * @param {Array} strSymbols The string symbols to inspect.
   * @param {Array} chrSymbols The character symbols to find.
   * @returns {number} Returns the index of the first unmatched string symbol.
   */function charsStartIndex(strSymbols,chrSymbols){var index=-1,length=strSymbols.length;while(++index<length&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1){}return index;}/**
   * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
   * that is not found in the character symbols.
   *
   * @private
   * @param {Array} strSymbols The string symbols to inspect.
   * @param {Array} chrSymbols The character symbols to find.
   * @returns {number} Returns the index of the last unmatched string symbol.
   */function charsEndIndex(strSymbols,chrSymbols){var index=strSymbols.length;while(index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1){}return index;}/**
   * Gets the number of `placeholder` occurrences in `array`.
   *
   * @private
   * @param {Array} array The array to inspect.
   * @param {*} placeholder The placeholder to search for.
   * @returns {number} Returns the placeholder count.
   */function countHolders(array,placeholder){var length=array.length,result=0;while(length--){if(array[length]===placeholder){++result;}}return result;}/**
   * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
   * letters to basic Latin letters.
   *
   * @private
   * @param {string} letter The matched letter to deburr.
   * @returns {string} Returns the deburred letter.
   */var deburrLetter=basePropertyOf(deburredLetters);/**
   * Used by `_.escape` to convert characters to HTML entities.
   *
   * @private
   * @param {string} chr The matched character to escape.
   * @returns {string} Returns the escaped character.
   */var escapeHtmlChar=basePropertyOf(htmlEscapes);/**
   * Used by `_.template` to escape characters for inclusion in compiled string literals.
   *
   * @private
   * @param {string} chr The matched character to escape.
   * @returns {string} Returns the escaped character.
   */function escapeStringChar(chr){return'\\'+stringEscapes[chr];}/**
   * Gets the value at `key` of `object`.
   *
   * @private
   * @param {Object} [object] The object to query.
   * @param {string} key The key of the property to get.
   * @returns {*} Returns the property value.
   */function getValue(object,key){return object==null?undefined:object[key];}/**
   * Checks if `string` contains Unicode symbols.
   *
   * @private
   * @param {string} string The string to inspect.
   * @returns {boolean} Returns `true` if a symbol is found, else `false`.
   */function hasUnicode(string){return reHasUnicode.test(string);}/**
   * Checks if `string` contains a word composed of Unicode symbols.
   *
   * @private
   * @param {string} string The string to inspect.
   * @returns {boolean} Returns `true` if a word is found, else `false`.
   */function hasUnicodeWord(string){return reHasUnicodeWord.test(string);}/**
   * Converts `iterator` to an array.
   *
   * @private
   * @param {Object} iterator The iterator to convert.
   * @returns {Array} Returns the converted array.
   */function iteratorToArray(iterator){var data,result=[];while(!(data=iterator.next()).done){result.push(data.value);}return result;}/**
   * Converts `map` to its key-value pairs.
   *
   * @private
   * @param {Object} map The map to convert.
   * @returns {Array} Returns the key-value pairs.
   */function mapToArray(map){var index=-1,result=Array(map.size);map.forEach(function(value,key){result[++index]=[key,value];});return result;}/**
   * Creates a unary function that invokes `func` with its argument transformed.
   *
   * @private
   * @param {Function} func The function to wrap.
   * @param {Function} transform The argument transform.
   * @returns {Function} Returns the new function.
   */function overArg(func,transform){return function(arg){return func(transform(arg));};}/**
   * Replaces all `placeholder` elements in `array` with an internal placeholder
   * and returns an array of their indexes.
   *
   * @private
   * @param {Array} array The array to modify.
   * @param {*} placeholder The placeholder to replace.
   * @returns {Array} Returns the new array of placeholder indexes.
   */function replaceHolders(array,placeholder){var index=-1,length=array.length,resIndex=0,result=[];while(++index<length){var value=array[index];if(value===placeholder||value===PLACEHOLDER){array[index]=PLACEHOLDER;result[resIndex++]=index;}}return result;}/**
   * Converts `set` to an array of its values.
   *
   * @private
   * @param {Object} set The set to convert.
   * @returns {Array} Returns the values.
   */function setToArray(set){var index=-1,result=Array(set.size);set.forEach(function(value){result[++index]=value;});return result;}/**
   * Converts `set` to its value-value pairs.
   *
   * @private
   * @param {Object} set The set to convert.
   * @returns {Array} Returns the value-value pairs.
   */function setToPairs(set){var index=-1,result=Array(set.size);set.forEach(function(value){result[++index]=[value,value];});return result;}/**
   * A specialized version of `_.indexOf` which performs strict equality
   * comparisons of values, i.e. `===`.
   *
   * @private
   * @param {Array} array The array to inspect.
   * @param {*} value The value to search for.
   * @param {number} fromIndex The index to search from.
   * @returns {number} Returns the index of the matched value, else `-1`.
   */function strictIndexOf(array,value,fromIndex){var index=fromIndex-1,length=array.length;while(++index<length){if(array[index]===value){return index;}}return-1;}/**
   * A specialized version of `_.lastIndexOf` which performs strict equality
   * comparisons of values, i.e. `===`.
   *
   * @private
   * @param {Array} array The array to inspect.
   * @param {*} value The value to search for.
   * @param {number} fromIndex The index to search from.
   * @returns {number} Returns the index of the matched value, else `-1`.
   */function strictLastIndexOf(array,value,fromIndex){var index=fromIndex+1;while(index--){if(array[index]===value){return index;}}return index;}/**
   * Gets the number of symbols in `string`.
   *
   * @private
   * @param {string} string The string to inspect.
   * @returns {number} Returns the string size.
   */function stringSize(string){return hasUnicode(string)?unicodeSize(string):asciiSize(string);}/**
   * Converts `string` to an array.
   *
   * @private
   * @param {string} string The string to convert.
   * @returns {Array} Returns the converted array.
   */function stringToArray(string){return hasUnicode(string)?unicodeToArray(string):asciiToArray(string);}/**
   * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
   * character of `string`.
   *
   * @private
   * @param {string} string The string to inspect.
   * @returns {number} Returns the index of the last non-whitespace character.
   */function trimmedEndIndex(string){var index=string.length;while(index--&&reWhitespace.test(string.charAt(index))){}return index;}/**
   * Used by `_.unescape` to convert HTML entities to characters.
   *
   * @private
   * @param {string} chr The matched character to unescape.
   * @returns {string} Returns the unescaped character.
   */var unescapeHtmlChar=basePropertyOf(htmlUnescapes);/**
   * Gets the size of a Unicode `string`.
   *
   * @private
   * @param {string} string The string inspect.
   * @returns {number} Returns the string size.
   */function unicodeSize(string){var result=reUnicode.lastIndex=0;while(reUnicode.test(string)){++result;}return result;}/**
   * Converts a Unicode `string` to an array.
   *
   * @private
   * @param {string} string The string to convert.
   * @returns {Array} Returns the converted array.
   */function unicodeToArray(string){return string.match(reUnicode)||[];}/**
   * Splits a Unicode `string` into an array of its words.
   *
   * @private
   * @param {string} The string to inspect.
   * @returns {Array} Returns the words of `string`.
   */function unicodeWords(string){return string.match(reUnicodeWord)||[];}/*--------------------------------------------------------------------------*/ /**
   * Create a new pristine `lodash` function using the `context` object.
   *
   * @static
   * @memberOf _
   * @since 1.1.0
   * @category Util
   * @param {Object} [context=root] The context object.
   * @returns {Function} Returns a new `lodash` function.
   * @example
   *
   * _.mixin({ 'foo': _.constant('foo') });
   *
   * var lodash = _.runInContext();
   * lodash.mixin({ 'bar': lodash.constant('bar') });
   *
   * _.isFunction(_.foo);
   * // => true
   * _.isFunction(_.bar);
   * // => false
   *
   * lodash.isFunction(lodash.foo);
   * // => false
   * lodash.isFunction(lodash.bar);
   * // => true
   *
   * // Create a suped-up `defer` in Node.js.
   * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
   */var runInContext=function runInContext(context){context=context==null?root:_.defaults(root.Object(),context,_.pick(root,contextProps));/** Built-in constructor references. */var Array=context.Array,Date=context.Date,Error=context.Error,Function=context.Function,Math=context.Math,Object=context.Object,RegExp=context.RegExp,String=context.String,TypeError=context.TypeError;/** Used for built-in method references. */var arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype;/** Used to detect overreaching core-js shims. */var coreJsData=context['__core-js_shared__'];/** Used to resolve the decompiled source of functions. */var funcToString=funcProto.toString;/** Used to check objects for own properties. */var hasOwnProperty=objectProto.hasOwnProperty;/** Used to generate unique IDs. */var idCounter=0;/** Used to detect methods masquerading as native. */var maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||'');return uid?'Symbol(src)_1.'+uid:'';}();/**
     * Used to resolve the
     * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
     * of values.
     */var nativeObjectToString=objectProto.toString;/** Used to infer the `Object` constructor. */var objectCtorString=funcToString.call(Object);/** Used to restore the original `_` reference in `_.noConflict`. */var oldDash=root._;/** Used to detect if a method is native. */var reIsNative=RegExp('^'+funcToString.call(hasOwnProperty).replace(reRegExpChar,'\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,'$1.*?')+'$');/** Built-in value references. */var Buffer=moduleExports?context.Buffer:undefined,Symbol=context.Symbol,Uint8Array=context.Uint8Array,allocUnsafe=Buffer?Buffer.allocUnsafe:undefined,getPrototype=overArg(Object.getPrototypeOf,Object),objectCreate=Object.create,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=Symbol?Symbol.isConcatSpreadable:undefined,symIterator=Symbol?Symbol.iterator:undefined,symToStringTag=Symbol?Symbol.toStringTag:undefined;var defineProperty=function(){try{var func=getNative(Object,'defineProperty');func({},'',{});return func;}catch(e){}}();/** Mocked built-ins. */var ctxClearTimeout=context.clearTimeout!==root.clearTimeout&&context.clearTimeout,ctxNow=Date&&Date.now!==root.Date.now&&Date.now,ctxSetTimeout=context.setTimeout!==root.setTimeout&&context.setTimeout;/* Built-in method references for those with the same name as other `lodash` methods. */var nativeCeil=Math.ceil,nativeFloor=Math.floor,nativeGetSymbols=Object.getOwnPropertySymbols,nativeIsBuffer=Buffer?Buffer.isBuffer:undefined,nativeIsFinite=context.isFinite,nativeJoin=arrayProto.join,nativeKeys=overArg(Object.keys,Object),nativeMax=Math.max,nativeMin=Math.min,nativeNow=Date.now,nativeParseInt=context.parseInt,nativeRandom=Math.random,nativeReverse=arrayProto.reverse;/* Built-in method references that are verified to be native. */var DataView=getNative(context,'DataView'),Map=getNative(context,'Map'),Promise=getNative(context,'Promise'),Set=getNative(context,'Set'),WeakMap=getNative(context,'WeakMap'),nativeCreate=getNative(Object,'create');/** Used to store function metadata. */var metaMap=WeakMap&&new WeakMap();/** Used to lookup unminified function names. */var realNames={};/** Used to detect maps, sets, and weakmaps. */var dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map),promiseCtorString=toSource(Promise),setCtorString=toSource(Set),weakMapCtorString=toSource(WeakMap);/** Used to convert symbols to primitives and strings. */var symbolProto=Symbol?Symbol.prototype:undefined,symbolValueOf=symbolProto?symbolProto.valueOf:undefined,symbolToString=symbolProto?symbolProto.toString:undefined;/*------------------------------------------------------------------------*/ /**
     * Creates a `lodash` object which wraps `value` to enable implicit method
     * chain sequences. Methods that operate on and return arrays, collections,
     * and functions can be chained together. Methods that retrieve a single value
     * or may return a primitive value will automatically end the chain sequence
     * and return the unwrapped value. Otherwise, the value must be unwrapped
     * with `_#value`.
     *
     * Explicit chain sequences, which must be unwrapped with `_#value`, may be
     * enabled using `_.chain`.
     *
     * The execution of chained methods is lazy, that is, it's deferred until
     * `_#value` is implicitly or explicitly called.
     *
     * Lazy evaluation allows several methods to support shortcut fusion.
     * Shortcut fusion is an optimization to merge iteratee calls; this avoids
     * the creation of intermediate arrays and can greatly reduce the number of
     * iteratee executions. Sections of a chain sequence qualify for shortcut
     * fusion if the section is applied to an array and iteratees accept only
     * one argument. The heuristic for whether a section qualifies for shortcut
     * fusion is subject to change.
     *
     * Chaining is supported in custom builds as long as the `_#value` method is
     * directly or indirectly included in the build.
     *
     * In addition to lodash methods, wrappers have `Array` and `String` methods.
     *
     * The wrapper `Array` methods are:
     * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
     *
     * The wrapper `String` methods are:
     * `replace` and `split`
     *
     * The wrapper methods that support shortcut fusion are:
     * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
     * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
     * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
     *
     * The chainable wrapper methods are:
     * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
     * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
     * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
     * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
     * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
     * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
     * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
     * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
     * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
     * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
     * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
     * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
     * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
     * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
     * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
     * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
     * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
     * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
     * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
     * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
     * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
     * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
     * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
     * `zipObject`, `zipObjectDeep`, and `zipWith`
     *
     * The wrapper methods that are **not** chainable by default are:
     * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
     * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
     * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
     * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
     * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
     * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
     * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
     * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
     * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
     * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
     * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
     * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
     * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
     * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
     * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
     * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
     * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
     * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
     * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
     * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
     * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
     * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
     * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
     * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
     * `upperFirst`, `value`, and `words`
     *
     * @name _
     * @constructor
     * @category Seq
     * @param {*} value The value to wrap in a `lodash` instance.
     * @returns {Object} Returns the new `lodash` wrapper instance.
     * @example
     *
     * function square(n) {
     *   return n * n;
     * }
     *
     * var wrapped = _([1, 2, 3]);
     *
     * // Returns an unwrapped value.
     * wrapped.reduce(_.add);
     * // => 6
     *
     * // Returns a wrapped value.
     * var squares = wrapped.map(square);
     *
     * _.isArray(squares);
     * // => false
     *
     * _.isArray(squares.value());
     * // => true
     */function lodash(value){if(isObjectLike(value)&&!isArray(value)&&!(value instanceof LazyWrapper)){if(value instanceof LodashWrapper){return value;}if(hasOwnProperty.call(value,'__wrapped__')){return wrapperClone(value);}}return new LodashWrapper(value);}/**
     * The base implementation of `_.create` without support for assigning
     * properties to the created object.
     *
     * @private
     * @param {Object} proto The object to inherit from.
     * @returns {Object} Returns the new object.
     */var baseCreate=function(){function object(){}return function(proto){if(!isObject(proto)){return{};}if(objectCreate){return objectCreate(proto);}object.prototype=proto;var result=new object();object.prototype=undefined;return result;};}();/**
     * The function whose prototype chain sequence wrappers inherit from.
     *
     * @private
     */function baseLodash(){// No operation performed.
}/**
     * The base constructor for creating `lodash` wrapper objects.
     *
     * @private
     * @param {*} value The value to wrap.
     * @param {boolean} [chainAll] Enable explicit method chain sequences.
     */function LodashWrapper(value,chainAll){this.__wrapped__=value;this.__actions__=[];this.__chain__=!!chainAll;this.__index__=0;this.__values__=undefined;}/**
     * By default, the template delimiters used by lodash are like those in
     * embedded Ruby (ERB) as well as ES2015 template strings. Change the
     * following template settings to use alternative delimiters.
     *
     * @static
     * @memberOf _
     * @type {Object}
     */lodash.templateSettings={/**
       * Used to detect `data` property values to be HTML-escaped.
       *
       * @memberOf _.templateSettings
       * @type {RegExp}
       */'escape':reEscape,/**
       * Used to detect code to be evaluated.
       *
       * @memberOf _.templateSettings
       * @type {RegExp}
       */'evaluate':reEvaluate,/**
       * Used to detect `data` property values to inject.
       *
       * @memberOf _.templateSettings
       * @type {RegExp}
       */'interpolate':reInterpolate,/**
       * Used to reference the data object in the template text.
       *
       * @memberOf _.templateSettings
       * @type {string}
       */'variable':'',/**
       * Used to import variables into the compiled template.
       *
       * @memberOf _.templateSettings
       * @type {Object}
       */'imports':{/**
         * A reference to the `lodash` function.
         *
         * @memberOf _.templateSettings.imports
         * @type {Function}
         */'_':lodash}};// Ensure wrappers are instances of `baseLodash`.
lodash.prototype=baseLodash.prototype;lodash.prototype.constructor=lodash;LodashWrapper.prototype=baseCreate(baseLodash.prototype);LodashWrapper.prototype.constructor=LodashWrapper;/*------------------------------------------------------------------------*/ /**
     * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
     *
     * @private
     * @constructor
     * @param {*} value The value to wrap.
     */function LazyWrapper(value){this.__wrapped__=value;this.__actions__=[];this.__dir__=1;this.__filtered__=false;this.__iteratees__=[];this.__takeCount__=MAX_ARRAY_LENGTH;this.__views__=[];}/**
     * Creates a clone of the lazy wrapper object.
     *
     * @private
     * @name clone
     * @memberOf LazyWrapper
     * @returns {Object} Returns the cloned `LazyWrapper` object.
     */function lazyClone(){var result=new LazyWrapper(this.__wrapped__);result.__actions__=copyArray(this.__actions__);result.__dir__=this.__dir__;result.__filtered__=this.__filtered__;result.__iteratees__=copyArray(this.__iteratees__);result.__takeCount__=this.__takeCount__;result.__views__=copyArray(this.__views__);return result;}/**
     * Reverses the direction of lazy iteration.
     *
     * @private
     * @name reverse
     * @memberOf LazyWrapper
     * @returns {Object} Returns the new reversed `LazyWrapper` object.
     */function lazyReverse(){if(this.__filtered__){var result=new LazyWrapper(this);result.__dir__=-1;result.__filtered__=true;}else{result=this.clone();result.__dir__*=-1;}return result;}/**
     * Extracts the unwrapped value from its lazy wrapper.
     *
     * @private
     * @name value
     * @memberOf LazyWrapper
     * @returns {*} Returns the unwrapped value.
     */function lazyValue(){var array=this.__wrapped__.value(),dir=this.__dir__,isArr=isArray(array),isRight=dir<0,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||!isRight&&arrLength==length&&takeCount==length){return baseWrapperValue(array,this.__actions__);}var result=[];outer:while(length--&&resIndex<takeCount){index+=dir;var iterIndex=-1,value=array[index];while(++iterIndex<iterLength){var data=iteratees[iterIndex],iteratee=data.iteratee,type=data.type,computed=iteratee(value);if(type==LAZY_MAP_FLAG){value=computed;}else if(!computed){if(type==LAZY_FILTER_FLAG){continue outer;}else{break outer;}}}result[resIndex++]=value;}return result;}// Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype=baseCreate(baseLodash.prototype);LazyWrapper.prototype.constructor=LazyWrapper;/*------------------------------------------------------------------------*/ /**
     * Creates a hash object.
     *
     * @private
     * @constructor
     * @param {Array} [entries] The key-value pairs to cache.
     */function Hash(entries){var index=-1,length=entries==null?0:entries.length;this.clear();while(++index<length){var entry=entries[index];this.set(entry[0],entry[1]);}}/**
     * Removes all key-value entries from the hash.
     *
     * @private
     * @name clear
     * @memberOf Hash
     */function hashClear(){this.__data__=nativeCreate?nativeCreate(null):{};this.size=0;}/**
     * Removes `key` and its value from the hash.
     *
     * @private
     * @name delete
     * @memberOf Hash
     * @param {Object} hash The hash to modify.
     * @param {string} key The key of the value to remove.
     * @returns {boolean} Returns `true` if the entry was removed, else `false`.
     */function hashDelete(key){var result=this.has(key)&&delete this.__data__[key];this.size-=result?1:0;return result;}/**
     * Gets the hash value for `key`.
     *
     * @private
     * @name get
     * @memberOf Hash
     * @param {string} key The key of the value to get.
     * @returns {*} Returns the entry value.
     */function hashGet(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?undefined:result;}return hasOwnProperty.call(data,key)?data[key]:undefined;}/**
     * Checks if a hash value for `key` exists.
     *
     * @private
     * @name has
     * @memberOf Hash
     * @param {string} key The key of the entry to check.
     * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
     */function hashHas(key){var data=this.__data__;return nativeCreate?data[key]!==undefined:hasOwnProperty.call(data,key);}/**
     * Sets the hash `key` to `value`.
     *
     * @private
     * @name set
     * @memberOf Hash
     * @param {string} key The key of the value to set.
     * @param {*} value The value to set.
     * @returns {Object} Returns the hash instance.
     */function hashSet(key,value){var data=this.__data__;this.size+=this.has(key)?0:1;data[key]=nativeCreate&&value===undefined?HASH_UNDEFINED:value;return this;}// Add methods to `Hash`.
Hash.prototype.clear=hashClear;Hash.prototype['delete']=hashDelete;Hash.prototype.get=hashGet;Hash.prototype.has=hashHas;Hash.prototype.set=hashSet;/*------------------------------------------------------------------------*/ /**
     * Creates an list cache object.
     *
     * @private
     * @constructor
     * @param {Array} [entries] The key-value pairs to cache.
     */function ListCache(entries){var index=-1,length=entries==null?0:entries.length;this.clear();while(++index<length){var entry=entries[index];this.set(entry[0],entry[1]);}}/**
     * Removes all key-value entries from the list cache.
     *
     * @private
     * @name clear
     * @memberOf ListCache
     */function listCacheClear(){this.__data__=[];this.size=0;}/**
     * Removes `key` and its value from the list cache.
     *
     * @private
     * @name delete
     * @memberOf ListCache
     * @param {string} key The key of the value to remove.
     * @returns {boolean} Returns `true` if the entry was removed, else `false`.
     */function listCacheDelete(key){var data=this.__data__,index=assocIndexOf(data,key);if(index<0){return false;}var lastIndex=data.length-1;if(index==lastIndex){data.pop();}else{splice.call(data,index,1);}--this.size;return true;}/**
     * Gets the list cache value for `key`.
     *
     * @private
     * @name get
     * @memberOf ListCache
     * @param {string} key The key of the value to get.
     * @returns {*} Returns the entry value.
     */function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?undefined:data[index][1];}/**
     * Checks if a list cache value for `key` exists.
     *
     * @private
     * @name has
     * @memberOf ListCache
     * @param {string} key The key of the entry to check.
     * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
     */function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1;}/**
     * Sets the list cache `key` to `value`.
     *
     * @private
     * @name set
     * @memberOf ListCache
     * @param {string} key The key of the value to set.
     * @param {*} value The value to set.
     * @returns {Object} Returns the list cache instance.
     */function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);if(index<0){++this.size;data.push([key,value]);}else{data[index][1]=value;}return this;}// Add methods to `ListCache`.
ListCache.prototype.clear=listCacheClear;ListCache.prototype['delete']=listCacheDelete;ListCache.prototype.get=listCacheGet;ListCache.prototype.has=listCacheHas;ListCache.prototype.set=listCacheSet;/*------------------------------------------------------------------------*/ /**
     * Creates a map cache object to store key-value pairs.
     *
     * @private
     * @constructor
     * @param {Array} [entries] The key-value pairs to cache.
     */function MapCache(entries){var index=-1,length=entries==null?0:entries.length;this.clear();while(++index<length){var entry=entries[index];this.set(entry[0],entry[1]);}}/**
     * Removes all key-value entries from the map.
     *
     * @private
     * @name clear
     * @memberOf MapCache
     */function mapCacheClear(){this.size=0;this.__data__={'hash':new Hash(),'map':new(Map||ListCache)(),'string':new Hash()};}/**
     * Removes `key` and its value from the map.
     *
     * @private
     * @name delete
     * @memberOf MapCache
     * @param {string} key The key of the value to remove.
     * @returns {boolean} Returns `true` if the entry was removed, else `false`.
     */function mapCacheDelete(key){var result=getMapData(this,key)['delete'](key);this.size-=result?1:0;return result;}/**
     * Gets the map value for `key`.
     *
     * @private
     * @name get
     * @memberOf MapCache
     * @param {string} key The key of the value to get.
     * @returns {*} Returns the entry value.
     */function mapCacheGet(key){return getMapData(this,key).get(key);}/**
     * Checks if a map value for `key` exists.
     *
     * @private
     * @name has
     * @memberOf MapCache
     * @param {string} key The key of the entry to check.
     * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
     */function mapCacheHas(key){return getMapData(this,key).has(key);}/**
     * Sets the map `key` to `value`.
     *
     * @private
     * @name set
     * @memberOf MapCache
     * @param {string} key The key of the value to set.
     * @param {*} value The value to set.
     * @returns {Object} Returns the map cache instance.
     */function mapCacheSet(key,value){var data=getMapData(this,key),size=data.size;data.set(key,value);this.size+=data.size==size?0:1;return this;}// Add methods to `MapCache`.
MapCache.prototype.clear=mapCacheClear;MapCache.prototype['delete']=mapCacheDelete;MapCache.prototype.get=mapCacheGet;MapCache.prototype.has=mapCacheHas;MapCache.prototype.set=mapCacheSet;/*------------------------------------------------------------------------*/ /**
     *
     * Creates an array cache object to store unique values.
     *
     * @private
     * @constructor
     * @param {Array} [values] The values to cache.
     */function SetCache(values){var index=-1,length=values==null?0:values.length;this.__data__=new MapCache();while(++index<length){this.add(values[index]);}}/**
     * Adds `value` to the array cache.
     *
     * @private
     * @name add
     * @memberOf SetCache
     * @alias push
     * @param {*} value The value to cache.
     * @returns {Object} Returns the cache instance.
     */function setCacheAdd(value){this.__data__.set(value,HASH_UNDEFINED);return this;}/**
     * Checks if `value` is in the array cache.
     *
     * @private
     * @name has
     * @memberOf SetCache
     * @param {*} value The value to search for.
     * @returns {number} Returns `true` if `value` is found, else `false`.
     */function setCacheHas(value){return this.__data__.has(value);}// Add methods to `SetCache`.
SetCache.prototype.add=SetCache.prototype.push=setCacheAdd;SetCache.prototype.has=setCacheHas;/*------------------------------------------------------------------------*/ /**
     * Creates a stack cache object to store key-value pairs.
     *
     * @private
     * @constructor
     * @param {Array} [entries] The key-value pairs to cache.
     */function Stack(entries){var data=this.__data__=new ListCache(entries);this.size=data.size;}/**
     * Removes all key-value entries from the stack.
     *
     * @private
     * @name clear
     * @memberOf Stack
     */function stackClear(){this.__data__=new ListCache();this.size=0;}/**
     * Removes `key` and its value from the stack.
     *
     * @private
     * @name delete
     * @memberOf Stack
     * @param {string} key The key of the value to remove.
     * @returns {boolean} Returns `true` if the entry was removed, else `false`.
     */function stackDelete(key){var data=this.__data__,result=data['delete'](key);this.size=data.size;return result;}/**
     * Gets the stack value for `key`.
     *
     * @private
     * @name get
     * @memberOf Stack
     * @param {string} key The key of the value to get.
     * @returns {*} Returns the entry value.
     */function stackGet(key){return this.__data__.get(key);}/**
     * Checks if a stack value for `key` exists.
     *
     * @private
     * @name has
     * @memberOf Stack
     * @param {string} key The key of the entry to check.
     * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
     */function stackHas(key){return this.__data__.has(key);}/**
     * Sets the stack `key` to `value`.
     *
     * @private
     * @name set
     * @memberOf Stack
     * @param {string} key The key of the value to set.
     * @param {*} value The value to set.
     * @returns {Object} Returns the stack cache instance.
     */function stackSet(key,value){var data=this.__data__;if(data instanceof ListCache){var pairs=data.__data__;if(!Map||pairs.length<LARGE_ARRAY_SIZE-1){pairs.push([key,value]);this.size=++data.size;return this;}data=this.__data__=new MapCache(pairs);}data.set(key,value);this.size=data.size;return this;}// Add methods to `Stack`.
Stack.prototype.clear=stackClear;Stack.prototype['delete']=stackDelete;Stack.prototype.get=stackGet;Stack.prototype.has=stackHas;Stack.prototype.set=stackSet;/*------------------------------------------------------------------------*/ /**
     * Creates an array of the enumerable property names of the array-like `value`.
     *
     * @private
     * @param {*} value The value to query.
     * @param {boolean} inherited Specify returning inherited property names.
     * @returns {Array} Returns the array of property names.
     */function arrayLikeKeys(value,inherited){var isArr=isArray(value),isArg=!isArr&&isArguments(value),isBuff=!isArr&&!isArg&&isBuffer(value),isType=!isArr&&!isArg&&!isBuff&&isTypedArray(value),skipIndexes=isArr||isArg||isBuff||isType,result=skipIndexes?baseTimes(value.length,String):[],length=result.length;for(var key in value){if((inherited||hasOwnProperty.call(value,key))&&!(skipIndexes&&(// Safari 9 has enumerable `arguments.length` in strict mode.
key=='length'||// Node.js 0.10 has enumerable non-index properties on buffers.
isBuff&&(key=='offset'||key=='parent')||// PhantomJS 2 has enumerable non-index properties on typed arrays.
isType&&(key=='buffer'||key=='byteLength'||key=='byteOffset')||// Skip index properties.
isIndex(key,length)))){result.push(key);}}return result;}/**
     * A specialized version of `_.sample` for arrays.
     *
     * @private
     * @param {Array} array The array to sample.
     * @returns {*} Returns the random element.
     */function arraySample(array){var length=array.length;return length?array[baseRandom(0,length-1)]:undefined;}/**
     * A specialized version of `_.sampleSize` for arrays.
     *
     * @private
     * @param {Array} array The array to sample.
     * @param {number} n The number of elements to sample.
     * @returns {Array} Returns the random elements.
     */function arraySampleSize(array,n){return shuffleSelf(copyArray(array),baseClamp(n,0,array.length));}/**
     * A specialized version of `_.shuffle` for arrays.
     *
     * @private
     * @param {Array} array The array to shuffle.
     * @returns {Array} Returns the new shuffled array.
     */function arrayShuffle(array){return shuffleSelf(copyArray(array));}/**
     * This function is like `assignValue` except that it doesn't assign
     * `undefined` values.
     *
     * @private
     * @param {Object} object The object to modify.
     * @param {string} key The key of the property to assign.
     * @param {*} value The value to assign.
     */function assignMergeValue(object,key,value){if(value!==undefined&&!eq(object[key],value)||value===undefined&&!(key in object)){baseAssignValue(object,key,value);}}/**
     * Assigns `value` to `key` of `object` if the existing value is not equivalent
     * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons.
     *
     * @private
     * @param {Object} object The object to modify.
     * @param {string} key The key of the property to assign.
     * @param {*} value The value to assign.
     */function assignValue(object,key,value){var objValue=object[key];if(!(hasOwnProperty.call(object,key)&&eq(objValue,value))||value===undefined&&!(key in object)){baseAssignValue(object,key,value);}}/**
     * Gets the index at which the `key` is found in `array` of key-value pairs.
     *
     * @private
     * @param {Array} array The array to inspect.
     * @param {*} key The key to search for.
     * @returns {number} Returns the index of the matched value, else `-1`.
     */function assocIndexOf(array,key){var length=array.length;while(length--){if(eq(array[length][0],key)){return length;}}return-1;}/**
     * Aggregates elements of `collection` on `accumulator` with keys transformed
     * by `iteratee` and values set by `setter`.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} setter The function to set `accumulator` values.
     * @param {Function} iteratee The iteratee to transform keys.
     * @param {Object} accumulator The initial aggregated object.
     * @returns {Function} Returns `accumulator`.
     */function baseAggregator(collection,setter,iteratee,accumulator){baseEach(collection,function(value,key,collection){setter(accumulator,value,iteratee(value),collection);});return accumulator;}/**
     * The base implementation of `_.assign` without support for multiple sources
     * or `customizer` functions.
     *
     * @private
     * @param {Object} object The destination object.
     * @param {Object} source The source object.
     * @returns {Object} Returns `object`.
     */function baseAssign(object,source){return object&&copyObject(source,keys(source),object);}/**
     * The base implementation of `_.assignIn` without support for multiple sources
     * or `customizer` functions.
     *
     * @private
     * @param {Object} object The destination object.
     * @param {Object} source The source object.
     * @returns {Object} Returns `object`.
     */function baseAssignIn(object,source){return object&&copyObject(source,keysIn(source),object);}/**
     * The base implementation of `assignValue` and `assignMergeValue` without
     * value checks.
     *
     * @private
     * @param {Object} object The object to modify.
     * @param {string} key The key of the property to assign.
     * @param {*} value The value to assign.
     */function baseAssignValue(object,key,value){if(key=='__proto__'&&defineProperty){defineProperty(object,key,{'configurable':true,'enumerable':true,'value':value,'writable':true});}else{object[key]=value;}}/**
     * The base implementation of `_.at` without support for individual paths.
     *
     * @private
     * @param {Object} object The object to iterate over.
     * @param {string[]} paths The property paths to pick.
     * @returns {Array} Returns the picked elements.
     */function baseAt(object,paths){var index=-1,length=paths.length,result=Array(length),skip=object==null;while(++index<length){result[index]=skip?undefined:get(object,paths[index]);}return result;}/**
     * The base implementation of `_.clamp` which doesn't coerce arguments.
     *
     * @private
     * @param {number} number The number to clamp.
     * @param {number} [lower] The lower bound.
     * @param {number} upper The upper bound.
     * @returns {number} Returns the clamped number.
     */function baseClamp(number,lower,upper){if(number===number){if(upper!==undefined){number=number<=upper?number:upper;}if(lower!==undefined){number=number>=lower?number:lower;}}return number;}/**
     * The base implementation of `_.clone` and `_.cloneDeep` which tracks
     * traversed objects.
     *
     * @private
     * @param {*} value The value to clone.
     * @param {boolean} bitmask The bitmask flags.
     *  1 - Deep clone
     *  2 - Flatten inherited properties
     *  4 - Clone symbols
     * @param {Function} [customizer] The function to customize cloning.
     * @param {string} [key] The key of `value`.
     * @param {Object} [object] The parent object of `value`.
     * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
     * @returns {*} Returns the cloned value.
     */function baseClone(value,bitmask,customizer,key,object,stack){var result,isDeep=bitmask&CLONE_DEEP_FLAG,isFlat=bitmask&CLONE_FLAT_FLAG,isFull=bitmask&CLONE_SYMBOLS_FLAG;if(customizer){result=object?customizer(value,key,object,stack):customizer(value);}if(result!==undefined){return result;}if(!isObject(value)){return value;}var isArr=isArray(value);if(isArr){result=initCloneArray(value);if(!isDeep){return copyArray(value,result);}}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value)){return cloneBuffer(value,isDeep);}if(tag==objectTag||tag==argsTag||isFunc&&!object){result=isFlat||isFunc?{}:initCloneObject(value);if(!isDeep){return isFlat?copySymbolsIn(value,baseAssignIn(result,value)):copySymbols(value,baseAssign(result,value));}}else{if(!cloneableTags[tag]){return object?value:{};}result=initCloneByTag(value,tag,isDeep);}}// Check for circular references and return its corresponding clone.
stack||(stack=new Stack());var stacked=stack.get(value);if(stacked){return stacked;}stack.set(value,result);if(isSet(value)){value.forEach(function(subValue){result.add(baseClone(subValue,bitmask,customizer,subValue,value,stack));});}else if(isMap(value)){value.forEach(function(subValue,key){result.set(key,baseClone(subValue,bitmask,customizer,key,value,stack));});}var keysFunc=isFull?isFlat?getAllKeysIn:getAllKeys:isFlat?keysIn:keys;var props=isArr?undefined:keysFunc(value);arrayEach(props||value,function(subValue,key){if(props){key=subValue;subValue=value[key];}// Recursively populate clone (susceptible to call stack limits).
assignValue(result,key,baseClone(subValue,bitmask,customizer,key,value,stack));});return result;}/**
     * The base implementation of `_.conforms` which doesn't clone `source`.
     *
     * @private
     * @param {Object} source The object of property predicates to conform to.
     * @returns {Function} Returns the new spec function.
     */function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props);};}/**
     * The base implementation of `_.conformsTo` which accepts `props` to check.
     *
     * @private
     * @param {Object} object The object to inspect.
     * @param {Object} source The object of property predicates to conform to.
     * @returns {boolean} Returns `true` if `object` conforms, else `false`.
     */function baseConformsTo(object,source,props){var length=props.length;if(object==null){return!length;}object=Object(object);while(length--){var key=props[length],predicate=source[key],value=object[key];if(value===undefined&&!(key in object)||!predicate(value)){return false;}}return true;}/**
     * The base implementation of `_.delay` and `_.defer` which accepts `args`
     * to provide to `func`.
     *
     * @private
     * @param {Function} func The function to delay.
     * @param {number} wait The number of milliseconds to delay invocation.
     * @param {Array} args The arguments to provide to `func`.
     * @returns {number|Object} Returns the timer id or timeout object.
     */function baseDelay(func,wait,args){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}return setTimeout(function(){func.apply(undefined,args);},wait);}/**
     * The base implementation of methods like `_.difference` without support
     * for excluding multiple arrays or iteratee shorthands.
     *
     * @private
     * @param {Array} array The array to inspect.
     * @param {Array} values The values to exclude.
     * @param {Function} [iteratee] The iteratee invoked per element.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new array of filtered values.
     */function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=true,length=array.length,result=[],valuesLength=values.length;if(!length){return result;}if(iteratee){values=arrayMap(values,baseUnary(iteratee));}if(comparator){includes=arrayIncludesWith;isCommon=false;}else if(values.length>=LARGE_ARRAY_SIZE){includes=cacheHas;isCommon=false;values=new SetCache(values);}outer:while(++index<length){var value=array[index],computed=iteratee==null?value:iteratee(value);value=comparator||value!==0?value:0;if(isCommon&&computed===computed){var valuesIndex=valuesLength;while(valuesIndex--){if(values[valuesIndex]===computed){continue outer;}}result.push(value);}else if(!includes(values,computed,comparator)){result.push(value);}}return result;}/**
     * The base implementation of `_.forEach` without support for iteratee shorthands.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} iteratee The function invoked per iteration.
     * @returns {Array|Object} Returns `collection`.
     */var baseEach=createBaseEach(baseForOwn);/**
     * The base implementation of `_.forEachRight` without support for iteratee shorthands.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} iteratee The function invoked per iteration.
     * @returns {Array|Object} Returns `collection`.
     */var baseEachRight=createBaseEach(baseForOwnRight,true);/**
     * The base implementation of `_.every` without support for iteratee shorthands.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} predicate The function invoked per iteration.
     * @returns {boolean} Returns `true` if all elements pass the predicate check,
     *  else `false`
     */function baseEvery(collection,predicate){var result=true;baseEach(collection,function(value,index,collection){result=!!predicate(value,index,collection);return result;});return result;}/**
     * The base implementation of methods like `_.max` and `_.min` which accepts a
     * `comparator` to determine the extremum value.
     *
     * @private
     * @param {Array} array The array to iterate over.
     * @param {Function} iteratee The iteratee invoked per iteration.
     * @param {Function} comparator The comparator used to compare values.
     * @returns {*} Returns the extremum value.
     */function baseExtremum(array,iteratee,comparator){var index=-1,length=array.length;while(++index<length){var value=array[index],current=iteratee(value);if(current!=null&&(computed===undefined?current===current&&!isSymbol(current):comparator(current,computed))){var computed=current,result=value;}}return result;}/**
     * The base implementation of `_.fill` without an iteratee call guard.
     *
     * @private
     * @param {Array} array The array to fill.
     * @param {*} value The value to fill `array` with.
     * @param {number} [start=0] The start position.
     * @param {number} [end=array.length] The end position.
     * @returns {Array} Returns `array`.
     */function baseFill(array,value,start,end){var length=array.length;start=toInteger(start);if(start<0){start=-start>length?0:length+start;}end=end===undefined||end>length?length:toInteger(end);if(end<0){end+=length;}end=start>end?0:toLength(end);while(start<end){array[start++]=value;}return array;}/**
     * The base implementation of `_.filter` without support for iteratee shorthands.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} predicate The function invoked per iteration.
     * @returns {Array} Returns the new filtered array.
     */function baseFilter(collection,predicate){var result=[];baseEach(collection,function(value,index,collection){if(predicate(value,index,collection)){result.push(value);}});return result;}/**
     * The base implementation of `_.flatten` with support for restricting flattening.
     *
     * @private
     * @param {Array} array The array to flatten.
     * @param {number} depth The maximum recursion depth.
     * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
     * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
     * @param {Array} [result=[]] The initial result value.
     * @returns {Array} Returns the new flattened array.
     */function baseFlatten(array,depth,predicate,isStrict,result){var index=-1,length=array.length;predicate||(predicate=isFlattenable);result||(result=[]);while(++index<length){var value=array[index];if(depth>0&&predicate(value)){if(depth>1){// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value,depth-1,predicate,isStrict,result);}else{arrayPush(result,value);}}else if(!isStrict){result[result.length]=value;}}return result;}/**
     * The base implementation of `baseForOwn` which iterates over `object`
     * properties returned by `keysFunc` and invokes `iteratee` for each property.
     * Iteratee functions may exit iteration early by explicitly returning `false`.
     *
     * @private
     * @param {Object} object The object to iterate over.
     * @param {Function} iteratee The function invoked per iteration.
     * @param {Function} keysFunc The function to get the keys of `object`.
     * @returns {Object} Returns `object`.
     */var baseFor=createBaseFor();/**
     * This function is like `baseFor` except that it iterates over properties
     * in the opposite order.
     *
     * @private
     * @param {Object} object The object to iterate over.
     * @param {Function} iteratee The function invoked per iteration.
     * @param {Function} keysFunc The function to get the keys of `object`.
     * @returns {Object} Returns `object`.
     */var baseForRight=createBaseFor(true);/**
     * The base implementation of `_.forOwn` without support for iteratee shorthands.
     *
     * @private
     * @param {Object} object The object to iterate over.
     * @param {Function} iteratee The function invoked per iteration.
     * @returns {Object} Returns `object`.
     */function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys);}/**
     * The base implementation of `_.forOwnRight` without support for iteratee shorthands.
     *
     * @private
     * @param {Object} object The object to iterate over.
     * @param {Function} iteratee The function invoked per iteration.
     * @returns {Object} Returns `object`.
     */function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys);}/**
     * The base implementation of `_.functions` which creates an array of
     * `object` function property names filtered from `props`.
     *
     * @private
     * @param {Object} object The object to inspect.
     * @param {Array} props The property names to filter.
     * @returns {Array} Returns the function names.
     */function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key]);});}/**
     * The base implementation of `_.get` without support for default values.
     *
     * @private
     * @param {Object} object The object to query.
     * @param {Array|string} path The path of the property to get.
     * @returns {*} Returns the resolved value.
     */function baseGet(object,path){path=castPath(path,object);var index=0,length=path.length;while(object!=null&&index<length){object=object[toKey(path[index++])];}return index&&index==length?object:undefined;}/**
     * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
     * `keysFunc` and `symbolsFunc` to get the enumerable property names and
     * symbols of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @param {Function} keysFunc The function to get the keys of `object`.
     * @param {Function} symbolsFunc The function to get the symbols of `object`.
     * @returns {Array} Returns the array of property names and symbols.
     */function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object));}/**
     * The base implementation of `getTag` without fallbacks for buggy environments.
     *
     * @private
     * @param {*} value The value to query.
     * @returns {string} Returns the `toStringTag`.
     */function baseGetTag(value){if(value==null){return value===undefined?undefinedTag:nullTag;}return symToStringTag&&symToStringTag in Object(value)?getRawTag(value):objectToString(value);}/**
     * The base implementation of `_.gt` which doesn't coerce arguments.
     *
     * @private
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if `value` is greater than `other`,
     *  else `false`.
     */function baseGt(value,other){return value>other;}/**
     * The base implementation of `_.has` without support for deep paths.
     *
     * @private
     * @param {Object} [object] The object to query.
     * @param {Array|string} key The key to check.
     * @returns {boolean} Returns `true` if `key` exists, else `false`.
     */function baseHas(object,key){return object!=null&&hasOwnProperty.call(object,key);}/**
     * The base implementation of `_.hasIn` without support for deep paths.
     *
     * @private
     * @param {Object} [object] The object to query.
     * @param {Array|string} key The key to check.
     * @returns {boolean} Returns `true` if `key` exists, else `false`.
     */function baseHasIn(object,key){return object!=null&&key in Object(object);}/**
     * The base implementation of `_.inRange` which doesn't coerce arguments.
     *
     * @private
     * @param {number} number The number to check.
     * @param {number} start The start of the range.
     * @param {number} end The end of the range.
     * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
     */function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number<nativeMax(start,end);}/**
     * The base implementation of methods like `_.intersection`, without support
     * for iteratee shorthands, that accepts an array of arrays to inspect.
     *
     * @private
     * @param {Array} arrays The arrays to inspect.
     * @param {Function} [iteratee] The iteratee invoked per element.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new array of shared values.
     */function baseIntersection(arrays,iteratee,comparator){var includes=comparator?arrayIncludesWith:arrayIncludes,length=arrays[0].length,othLength=arrays.length,othIndex=othLength,caches=Array(othLength),maxLength=Infinity,result=[];while(othIndex--){var array=arrays[othIndex];if(othIndex&&iteratee){array=arrayMap(array,baseUnary(iteratee));}maxLength=nativeMin(array.length,maxLength);caches[othIndex]=!comparator&&(iteratee||length>=120&&array.length>=120)?new SetCache(othIndex&&array):undefined;}array=arrays[0];var index=-1,seen=caches[0];outer:while(++index<length&&result.length<maxLength){var value=array[index],computed=iteratee?iteratee(value):value;value=comparator||value!==0?value:0;if(!(seen?cacheHas(seen,computed):includes(result,computed,comparator))){othIndex=othLength;while(--othIndex){var cache=caches[othIndex];if(!(cache?cacheHas(cache,computed):includes(arrays[othIndex],computed,comparator))){continue outer;}}if(seen){seen.push(computed);}result.push(value);}}return result;}/**
     * The base implementation of `_.invert` and `_.invertBy` which inverts
     * `object` with values transformed by `iteratee` and set by `setter`.
     *
     * @private
     * @param {Object} object The object to iterate over.
     * @param {Function} setter The function to set `accumulator` values.
     * @param {Function} iteratee The iteratee to transform values.
     * @param {Object} accumulator The initial inverted object.
     * @returns {Function} Returns `accumulator`.
     */function baseInverter(object,setter,iteratee,accumulator){baseForOwn(object,function(value,key,object){setter(accumulator,iteratee(value),key,object);});return accumulator;}/**
     * The base implementation of `_.invoke` without support for individual
     * method arguments.
     *
     * @private
     * @param {Object} object The object to query.
     * @param {Array|string} path The path of the method to invoke.
     * @param {Array} args The arguments to invoke the method with.
     * @returns {*} Returns the result of the invoked method.
     */function baseInvoke(object,path,args){path=castPath(path,object);object=parent(object,path);var func=object==null?object:object[toKey(last(path))];return func==null?undefined:apply(func,object,args);}/**
     * The base implementation of `_.isArguments`.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an `arguments` object,
     */function baseIsArguments(value){return isObjectLike(value)&&baseGetTag(value)==argsTag;}/**
     * The base implementation of `_.isArrayBuffer` without Node.js optimizations.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
     */function baseIsArrayBuffer(value){return isObjectLike(value)&&baseGetTag(value)==arrayBufferTag;}/**
     * The base implementation of `_.isDate` without Node.js optimizations.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
     */function baseIsDate(value){return isObjectLike(value)&&baseGetTag(value)==dateTag;}/**
     * The base implementation of `_.isEqual` which supports partial comparisons
     * and tracks traversed objects.
     *
     * @private
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @param {boolean} bitmask The bitmask flags.
     *  1 - Unordered comparison
     *  2 - Partial comparison
     * @param {Function} [customizer] The function to customize comparisons.
     * @param {Object} [stack] Tracks traversed `value` and `other` objects.
     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
     */function baseIsEqual(value,other,bitmask,customizer,stack){if(value===other){return true;}if(value==null||other==null||!isObjectLike(value)&&!isObjectLike(other)){return value!==value&&other!==other;}return baseIsEqualDeep(value,other,bitmask,customizer,baseIsEqual,stack);}/**
     * A specialized version of `baseIsEqual` for arrays and objects which performs
     * deep comparisons and tracks traversed objects enabling objects with circular
     * references to be compared.
     *
     * @private
     * @param {Object} object The object to compare.
     * @param {Object} other The other object to compare.
     * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
     * @param {Function} customizer The function to customize comparisons.
     * @param {Function} equalFunc The function to determine equivalents of values.
     * @param {Object} [stack] Tracks traversed `object` and `other` objects.
     * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
     */function baseIsEqualDeep(object,other,bitmask,customizer,equalFunc,stack){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=objIsArr?arrayTag:getTag(object),othTag=othIsArr?arrayTag:getTag(other);objTag=objTag==argsTag?objectTag:objTag;othTag=othTag==argsTag?objectTag:othTag;var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&isBuffer(object)){if(!isBuffer(other)){return false;}objIsArr=true;objIsObj=false;}if(isSameTag&&!objIsObj){stack||(stack=new Stack());return objIsArr||isTypedArray(object)?equalArrays(object,other,bitmask,customizer,equalFunc,stack):equalByTag(object,other,objTag,bitmask,customizer,equalFunc,stack);}if(!(bitmask&COMPARE_PARTIAL_FLAG)){var objIsWrapped=objIsObj&&hasOwnProperty.call(object,'__wrapped__'),othIsWrapped=othIsObj&&hasOwnProperty.call(other,'__wrapped__');if(objIsWrapped||othIsWrapped){var objUnwrapped=objIsWrapped?object.value():object,othUnwrapped=othIsWrapped?other.value():other;stack||(stack=new Stack());return equalFunc(objUnwrapped,othUnwrapped,bitmask,customizer,stack);}}if(!isSameTag){return false;}stack||(stack=new Stack());return equalObjects(object,other,bitmask,customizer,equalFunc,stack);}/**
     * The base implementation of `_.isMap` without Node.js optimizations.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a map, else `false`.
     */function baseIsMap(value){return isObjectLike(value)&&getTag(value)==mapTag;}/**
     * The base implementation of `_.isMatch` without support for iteratee shorthands.
     *
     * @private
     * @param {Object} object The object to inspect.
     * @param {Object} source The object of property values to match.
     * @param {Array} matchData The property names, values, and compare flags to match.
     * @param {Function} [customizer] The function to customize comparisons.
     * @returns {boolean} Returns `true` if `object` is a match, else `false`.
     */function baseIsMatch(object,source,matchData,customizer){var index=matchData.length,length=index,noCustomizer=!customizer;if(object==null){return!length;}object=Object(object);while(index--){var data=matchData[index];if(noCustomizer&&data[2]?data[1]!==object[data[0]]:!(data[0]in object)){return false;}}while(++index<length){data=matchData[index];var key=data[0],objValue=object[key],srcValue=data[1];if(noCustomizer&&data[2]){if(objValue===undefined&&!(key in object)){return false;}}else{var stack=new Stack();if(customizer){var result=customizer(objValue,srcValue,key,object,source,stack);}if(!(result===undefined?baseIsEqual(srcValue,objValue,COMPARE_PARTIAL_FLAG|COMPARE_UNORDERED_FLAG,customizer,stack):result)){return false;}}}return true;}/**
     * The base implementation of `_.isNative` without bad shim checks.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a native function,
     *  else `false`.
     */function baseIsNative(value){if(!isObject(value)||isMasked(value)){return false;}var pattern=isFunction(value)?reIsNative:reIsHostCtor;return pattern.test(toSource(value));}/**
     * The base implementation of `_.isRegExp` without Node.js optimizations.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
     */function baseIsRegExp(value){return isObjectLike(value)&&baseGetTag(value)==regexpTag;}/**
     * The base implementation of `_.isSet` without Node.js optimizations.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a set, else `false`.
     */function baseIsSet(value){return isObjectLike(value)&&getTag(value)==setTag;}/**
     * The base implementation of `_.isTypedArray` without Node.js optimizations.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
     */function baseIsTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)];}/**
     * The base implementation of `_.iteratee`.
     *
     * @private
     * @param {*} [value=_.identity] The value to convert to an iteratee.
     * @returns {Function} Returns the iteratee.
     */function baseIteratee(value){// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if(typeof value=='function'){return value;}if(value==null){return identity;}if(typeof value=='object'){return isArray(value)?baseMatchesProperty(value[0],value[1]):baseMatches(value);}return property(value);}/**
     * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property names.
     */function baseKeys(object){if(!isPrototype(object)){return nativeKeys(object);}var result=[];for(var key in Object(object)){if(hasOwnProperty.call(object,key)&&key!='constructor'){result.push(key);}}return result;}/**
     * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property names.
     */function baseKeysIn(object){if(!isObject(object)){return nativeKeysIn(object);}var isProto=isPrototype(object),result=[];for(var key in object){if(!(key=='constructor'&&(isProto||!hasOwnProperty.call(object,key)))){result.push(key);}}return result;}/**
     * The base implementation of `_.lt` which doesn't coerce arguments.
     *
     * @private
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if `value` is less than `other`,
     *  else `false`.
     */function baseLt(value,other){return value<other;}/**
     * The base implementation of `_.map` without support for iteratee shorthands.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} iteratee The function invoked per iteration.
     * @returns {Array} Returns the new mapped array.
     */function baseMap(collection,iteratee){var index=-1,result=isArrayLike(collection)?Array(collection.length):[];baseEach(collection,function(value,key,collection){result[++index]=iteratee(value,key,collection);});return result;}/**
     * The base implementation of `_.matches` which doesn't clone `source`.
     *
     * @private
     * @param {Object} source The object of property values to match.
     * @returns {Function} Returns the new spec function.
     */function baseMatches(source){var matchData=getMatchData(source);if(matchData.length==1&&matchData[0][2]){return matchesStrictComparable(matchData[0][0],matchData[0][1]);}return function(object){return object===source||baseIsMatch(object,source,matchData);};}/**
     * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
     *
     * @private
     * @param {string} path The path of the property to get.
     * @param {*} srcValue The value to match.
     * @returns {Function} Returns the new spec function.
     */function baseMatchesProperty(path,srcValue){if(isKey(path)&&isStrictComparable(srcValue)){return matchesStrictComparable(toKey(path),srcValue);}return function(object){var objValue=get(object,path);return objValue===undefined&&objValue===srcValue?hasIn(object,path):baseIsEqual(srcValue,objValue,COMPARE_PARTIAL_FLAG|COMPARE_UNORDERED_FLAG);};}/**
     * The base implementation of `_.merge` without support for multiple sources.
     *
     * @private
     * @param {Object} object The destination object.
     * @param {Object} source The source object.
     * @param {number} srcIndex The index of `source`.
     * @param {Function} [customizer] The function to customize merged values.
     * @param {Object} [stack] Tracks traversed source values and their merged
     *  counterparts.
     */function baseMerge(object,source,srcIndex,customizer,stack){if(object===source){return;}baseFor(source,function(srcValue,key){stack||(stack=new Stack());if(isObject(srcValue)){baseMergeDeep(object,source,key,srcIndex,baseMerge,customizer,stack);}else{var newValue=customizer?customizer(safeGet(object,key),srcValue,key+'',object,source,stack):undefined;if(newValue===undefined){newValue=srcValue;}assignMergeValue(object,key,newValue);}},keysIn);}/**
     * A specialized version of `baseMerge` for arrays and objects which performs
     * deep merges and tracks traversed objects enabling objects with circular
     * references to be merged.
     *
     * @private
     * @param {Object} object The destination object.
     * @param {Object} source The source object.
     * @param {string} key The key of the value to merge.
     * @param {number} srcIndex The index of `source`.
     * @param {Function} mergeFunc The function to merge values.
     * @param {Function} [customizer] The function to customize assigned values.
     * @param {Object} [stack] Tracks traversed source values and their merged
     *  counterparts.
     */function baseMergeDeep(object,source,key,srcIndex,mergeFunc,customizer,stack){var objValue=safeGet(object,key),srcValue=safeGet(source,key),stacked=stack.get(srcValue);if(stacked){assignMergeValue(object,key,stacked);return;}var newValue=customizer?customizer(objValue,srcValue,key+'',object,source,stack):undefined;var isCommon=newValue===undefined;if(isCommon){var isArr=isArray(srcValue),isBuff=!isArr&&isBuffer(srcValue),isTyped=!isArr&&!isBuff&&isTypedArray(srcValue);newValue=srcValue;if(isArr||isBuff||isTyped){if(isArray(objValue)){newValue=objValue;}else if(isArrayLikeObject(objValue)){newValue=copyArray(objValue);}else if(isBuff){isCommon=false;newValue=cloneBuffer(srcValue,true);}else if(isTyped){isCommon=false;newValue=cloneTypedArray(srcValue,true);}else{newValue=[];}}else if(isPlainObject(srcValue)||isArguments(srcValue)){newValue=objValue;if(isArguments(objValue)){newValue=toPlainObject(objValue);}else if(!isObject(objValue)||isFunction(objValue)){newValue=initCloneObject(srcValue);}}else{isCommon=false;}}if(isCommon){// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue,newValue);mergeFunc(newValue,srcValue,srcIndex,customizer,stack);stack['delete'](srcValue);}assignMergeValue(object,key,newValue);}/**
     * The base implementation of `_.nth` which doesn't coerce arguments.
     *
     * @private
     * @param {Array} array The array to query.
     * @param {number} n The index of the element to return.
     * @returns {*} Returns the nth element of `array`.
     */function baseNth(array,n){var length=array.length;if(!length){return;}n+=n<0?length:0;return isIndex(n,length)?array[n]:undefined;}/**
     * The base implementation of `_.orderBy` without param guards.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
     * @param {string[]} orders The sort orders of `iteratees`.
     * @returns {Array} Returns the new sorted array.
     */function baseOrderBy(collection,iteratees,orders){if(iteratees.length){iteratees=arrayMap(iteratees,function(iteratee){if(isArray(iteratee)){return function(value){return baseGet(value,iteratee.length===1?iteratee[0]:iteratee);};}return iteratee;});}else{iteratees=[identity];}var index=-1;iteratees=arrayMap(iteratees,baseUnary(getIteratee()));var result=baseMap(collection,function(value,key,collection){var criteria=arrayMap(iteratees,function(iteratee){return iteratee(value);});return{'criteria':criteria,'index':++index,'value':value};});return baseSortBy(result,function(object,other){return compareMultiple(object,other,orders);});}/**
     * The base implementation of `_.pick` without support for individual
     * property identifiers.
     *
     * @private
     * @param {Object} object The source object.
     * @param {string[]} paths The property paths to pick.
     * @returns {Object} Returns the new object.
     */function basePick(object,paths){return basePickBy(object,paths,function(value,path){return hasIn(object,path);});}/**
     * The base implementation of  `_.pickBy` without support for iteratee shorthands.
     *
     * @private
     * @param {Object} object The source object.
     * @param {string[]} paths The property paths to pick.
     * @param {Function} predicate The function invoked per property.
     * @returns {Object} Returns the new object.
     */function basePickBy(object,paths,predicate){var index=-1,length=paths.length,result={};while(++index<length){var path=paths[index],value=baseGet(object,path);if(predicate(value,path)){baseSet(result,castPath(path,object),value);}}return result;}/**
     * A specialized version of `baseProperty` which supports deep paths.
     *
     * @private
     * @param {Array|string} path The path of the property to get.
     * @returns {Function} Returns the new accessor function.
     */function basePropertyDeep(path){return function(object){return baseGet(object,path);};}/**
     * The base implementation of `_.pullAllBy` without support for iteratee
     * shorthands.
     *
     * @private
     * @param {Array} array The array to modify.
     * @param {Array} values The values to remove.
     * @param {Function} [iteratee] The iteratee invoked per element.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns `array`.
     */function basePullAll(array,values,iteratee,comparator){var indexOf=comparator?baseIndexOfWith:baseIndexOf,index=-1,length=values.length,seen=array;if(array===values){values=copyArray(values);}if(iteratee){seen=arrayMap(array,baseUnary(iteratee));}while(++index<length){var fromIndex=0,value=values[index],computed=iteratee?iteratee(value):value;while((fromIndex=indexOf(seen,computed,fromIndex,comparator))>-1){if(seen!==array){splice.call(seen,fromIndex,1);}splice.call(array,fromIndex,1);}}return array;}/**
     * The base implementation of `_.pullAt` without support for individual
     * indexes or capturing the removed elements.
     *
     * @private
     * @param {Array} array The array to modify.
     * @param {number[]} indexes The indexes of elements to remove.
     * @returns {Array} Returns `array`.
     */function basePullAt(array,indexes){var length=array?indexes.length:0,lastIndex=length-1;while(length--){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index)){splice.call(array,index,1);}else{baseUnset(array,index);}}}return array;}/**
     * The base implementation of `_.random` without support for returning
     * floating-point numbers.
     *
     * @private
     * @param {number} lower The lower bound.
     * @param {number} upper The upper bound.
     * @returns {number} Returns the random number.
     */function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1));}/**
     * The base implementation of `_.range` and `_.rangeRight` which doesn't
     * coerce arguments.
     *
     * @private
     * @param {number} start The start of the range.
     * @param {number} end The end of the range.
     * @param {number} step The value to increment or decrement by.
     * @param {boolean} [fromRight] Specify iterating from right to left.
     * @returns {Array} Returns the range of numbers.
     */function baseRange(start,end,step,fromRight){var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);while(length--){result[fromRight?length:++index]=start;start+=step;}return result;}/**
     * The base implementation of `_.repeat` which doesn't coerce arguments.
     *
     * @private
     * @param {string} string The string to repeat.
     * @param {number} n The number of times to repeat the string.
     * @returns {string} Returns the repeated string.
     */function baseRepeat(string,n){var result='';if(!string||n<1||n>MAX_SAFE_INTEGER){return result;}// Leverage the exponentiation by squaring algorithm for a faster repeat.
// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
do{if(n%2){result+=string;}n=nativeFloor(n/2);if(n){string+=string;}}while(n);return result;}/**
     * The base implementation of `_.rest` which doesn't validate or coerce arguments.
     *
     * @private
     * @param {Function} func The function to apply a rest parameter to.
     * @param {number} [start=func.length-1] The start position of the rest parameter.
     * @returns {Function} Returns the new function.
     */function baseRest(func,start){return setToString(overRest(func,start,identity),func+'');}/**
     * The base implementation of `_.sample`.
     *
     * @private
     * @param {Array|Object} collection The collection to sample.
     * @returns {*} Returns the random element.
     */function baseSample(collection){return arraySample(values(collection));}/**
     * The base implementation of `_.sampleSize` without param guards.
     *
     * @private
     * @param {Array|Object} collection The collection to sample.
     * @param {number} n The number of elements to sample.
     * @returns {Array} Returns the random elements.
     */function baseSampleSize(collection,n){var array=values(collection);return shuffleSelf(array,baseClamp(n,0,array.length));}/**
     * The base implementation of `_.set`.
     *
     * @private
     * @param {Object} object The object to modify.
     * @param {Array|string} path The path of the property to set.
     * @param {*} value The value to set.
     * @param {Function} [customizer] The function to customize path creation.
     * @returns {Object} Returns `object`.
     */function baseSet(object,path,value,customizer){if(!isObject(object)){return object;}path=castPath(path,object);var index=-1,length=path.length,lastIndex=length-1,nested=object;while(nested!=null&&++index<length){var key=toKey(path[index]),newValue=value;if(key==='__proto__'||key==='constructor'||key==='prototype'){return object;}if(index!=lastIndex){var objValue=nested[key];newValue=customizer?customizer(objValue,key,nested):undefined;if(newValue===undefined){newValue=isObject(objValue)?objValue:isIndex(path[index+1])?[]:{};}}assignValue(nested,key,newValue);nested=nested[key];}return object;}/**
     * The base implementation of `setData` without support for hot loop shorting.
     *
     * @private
     * @param {Function} func The function to associate metadata with.
     * @param {*} data The metadata.
     * @returns {Function} Returns `func`.
     */var baseSetData=!metaMap?identity:function(func,data){metaMap.set(func,data);return func;};/**
     * The base implementation of `setToString` without support for hot loop shorting.
     *
     * @private
     * @param {Function} func The function to modify.
     * @param {Function} string The `toString` result.
     * @returns {Function} Returns `func`.
     */var baseSetToString=!defineProperty?identity:function(func,string){return defineProperty(func,'toString',{'configurable':true,'enumerable':false,'value':constant(string),'writable':true});};/**
     * The base implementation of `_.shuffle`.
     *
     * @private
     * @param {Array|Object} collection The collection to shuffle.
     * @returns {Array} Returns the new shuffled array.
     */function baseShuffle(collection){return shuffleSelf(values(collection));}/**
     * The base implementation of `_.slice` without an iteratee call guard.
     *
     * @private
     * @param {Array} array The array to slice.
     * @param {number} [start=0] The start position.
     * @param {number} [end=array.length] The end position.
     * @returns {Array} Returns the slice of `array`.
     */function baseSlice(array,start,end){var index=-1,length=array.length;if(start<0){start=-start>length?0:length+start;}end=end>length?length:end;if(end<0){end+=length;}length=start>end?0:end-start>>>0;start>>>=0;var result=Array(length);while(++index<length){result[index]=array[index+start];}return result;}/**
     * The base implementation of `_.some` without support for iteratee shorthands.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} predicate The function invoked per iteration.
     * @returns {boolean} Returns `true` if any element passes the predicate check,
     *  else `false`.
     */function baseSome(collection,predicate){var result;baseEach(collection,function(value,index,collection){result=predicate(value,index,collection);return!result;});return!!result;}/**
     * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
     * performs a binary search of `array` to determine the index at which `value`
     * should be inserted into `array` in order to maintain its sort order.
     *
     * @private
     * @param {Array} array The sorted array to inspect.
     * @param {*} value The value to evaluate.
     * @param {boolean} [retHighest] Specify returning the highest qualified index.
     * @returns {number} Returns the index at which `value` should be inserted
     *  into `array`.
     */function baseSortedIndex(array,value,retHighest){var low=0,high=array==null?low:array.length;if(typeof value=='number'&&value===value&&high<=HALF_MAX_ARRAY_LENGTH){while(low<high){var mid=low+high>>>1,computed=array[mid];if(computed!==null&&!isSymbol(computed)&&(retHighest?computed<=value:computed<value)){low=mid+1;}else{high=mid;}}return high;}return baseSortedIndexBy(array,value,identity,retHighest);}/**
     * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
     * which invokes `iteratee` for `value` and each element of `array` to compute
     * their sort ranking. The iteratee is invoked with one argument; (value).
     *
     * @private
     * @param {Array} array The sorted array to inspect.
     * @param {*} value The value to evaluate.
     * @param {Function} iteratee The iteratee invoked per element.
     * @param {boolean} [retHighest] Specify returning the highest qualified index.
     * @returns {number} Returns the index at which `value` should be inserted
     *  into `array`.
     */function baseSortedIndexBy(array,value,iteratee,retHighest){var low=0,high=array==null?0:array.length;if(high===0){return 0;}value=iteratee(value);var valIsNaN=value!==value,valIsNull=value===null,valIsSymbol=isSymbol(value),valIsUndefined=value===undefined;while(low<high){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=computed!==undefined,othIsNull=computed===null,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN){var setLow=retHighest||othIsReflexive;}else if(valIsUndefined){setLow=othIsReflexive&&(retHighest||othIsDefined);}else if(valIsNull){setLow=othIsReflexive&&othIsDefined&&(retHighest||!othIsNull);}else if(valIsSymbol){setLow=othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol);}else if(othIsNull||othIsSymbol){setLow=false;}else{setLow=retHighest?computed<=value:computed<value;}if(setLow){low=mid+1;}else{high=mid;}}return nativeMin(high,MAX_ARRAY_INDEX);}/**
     * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
     * support for iteratee shorthands.
     *
     * @private
     * @param {Array} array The array to inspect.
     * @param {Function} [iteratee] The iteratee invoked per element.
     * @returns {Array} Returns the new duplicate free array.
     */function baseSortedUniq(array,iteratee){var index=-1,length=array.length,resIndex=0,result=[];while(++index<length){var value=array[index],computed=iteratee?iteratee(value):value;if(!index||!eq(computed,seen)){var seen=computed;result[resIndex++]=value===0?0:value;}}return result;}/**
     * The base implementation of `_.toNumber` which doesn't ensure correct
     * conversions of binary, hexadecimal, or octal string values.
     *
     * @private
     * @param {*} value The value to process.
     * @returns {number} Returns the number.
     */function baseToNumber(value){if(typeof value=='number'){return value;}if(isSymbol(value)){return NAN;}return+value;}/**
     * The base implementation of `_.toString` which doesn't convert nullish
     * values to empty strings.
     *
     * @private
     * @param {*} value The value to process.
     * @returns {string} Returns the string.
     */function baseToString(value){// Exit early for strings to avoid a performance hit in some environments.
if(typeof value=='string'){return value;}if(isArray(value)){// Recursively convert values (susceptible to call stack limits).
return arrayMap(value,baseToString)+'';}if(isSymbol(value)){return symbolToString?symbolToString.call(value):'';}var result=value+'';return result=='0'&&1/value==-INFINITY?'-0':result;}/**
     * The base implementation of `_.uniqBy` without support for iteratee shorthands.
     *
     * @private
     * @param {Array} array The array to inspect.
     * @param {Function} [iteratee] The iteratee invoked per element.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new duplicate free array.
     */function baseUniq(array,iteratee,comparator){var index=-1,includes=arrayIncludes,length=array.length,isCommon=true,result=[],seen=result;if(comparator){isCommon=false;includes=arrayIncludesWith;}else if(length>=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set){return setToArray(set);}isCommon=false;includes=cacheHas;seen=new SetCache();}else{seen=iteratee?[]:result;}outer:while(++index<length){var value=array[index],computed=iteratee?iteratee(value):value;value=comparator||value!==0?value:0;if(isCommon&&computed===computed){var seenIndex=seen.length;while(seenIndex--){if(seen[seenIndex]===computed){continue outer;}}if(iteratee){seen.push(computed);}result.push(value);}else if(!includes(seen,computed,comparator)){if(seen!==result){seen.push(computed);}result.push(value);}}return result;}/**
     * The base implementation of `_.unset`.
     *
     * @private
     * @param {Object} object The object to modify.
     * @param {Array|string} path The property path to unset.
     * @returns {boolean} Returns `true` if the property is deleted, else `false`.
     */function baseUnset(object,path){path=castPath(path,object);object=parent(object,path);return object==null||delete object[toKey(last(path))];}/**
     * The base implementation of `_.update`.
     *
     * @private
     * @param {Object} object The object to modify.
     * @param {Array|string} path The path of the property to update.
     * @param {Function} updater The function to produce the updated value.
     * @param {Function} [customizer] The function to customize path creation.
     * @returns {Object} Returns `object`.
     */function baseUpdate(object,path,updater,customizer){return baseSet(object,path,updater(baseGet(object,path)),customizer);}/**
     * The base implementation of methods like `_.dropWhile` and `_.takeWhile`
     * without support for iteratee shorthands.
     *
     * @private
     * @param {Array} array The array to query.
     * @param {Function} predicate The function invoked per iteration.
     * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
     * @param {boolean} [fromRight] Specify iterating from right to left.
     * @returns {Array} Returns the slice of `array`.
     */function baseWhile(array,predicate,isDrop,fromRight){var length=array.length,index=fromRight?length:-1;while((fromRight?index--:++index<length)&&predicate(array[index],index,array)){}return isDrop?baseSlice(array,fromRight?0:index,fromRight?index+1:length):baseSlice(array,fromRight?index+1:0,fromRight?length:index);}/**
     * The base implementation of `wrapperValue` which returns the result of
     * performing a sequence of actions on the unwrapped `value`, where each
     * successive action is supplied the return value of the previous.
     *
     * @private
     * @param {*} value The unwrapped value.
     * @param {Array} actions Actions to perform to resolve the unwrapped value.
     * @returns {*} Returns the resolved value.
     */function baseWrapperValue(value,actions){var result=value;if(result instanceof LazyWrapper){result=result.value();}return arrayReduce(actions,function(result,action){return action.func.apply(action.thisArg,arrayPush([result],action.args));},result);}/**
     * The base implementation of methods like `_.xor`, without support for
     * iteratee shorthands, that accepts an array of arrays to inspect.
     *
     * @private
     * @param {Array} arrays The arrays to inspect.
     * @param {Function} [iteratee] The iteratee invoked per element.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new array of values.
     */function baseXor(arrays,iteratee,comparator){var length=arrays.length;if(length<2){return length?baseUniq(arrays[0]):[];}var index=-1,result=Array(length);while(++index<length){var array=arrays[index],othIndex=-1;while(++othIndex<length){if(othIndex!=index){result[index]=baseDifference(result[index]||array,arrays[othIndex],iteratee,comparator);}}}return baseUniq(baseFlatten(result,1),iteratee,comparator);}/**
     * This base implementation of `_.zipObject` which assigns values using `assignFunc`.
     *
     * @private
     * @param {Array} props The property identifiers.
     * @param {Array} values The property values.
     * @param {Function} assignFunc The function to assign values.
     * @returns {Object} Returns the new object.
     */function baseZipObject(props,values,assignFunc){var index=-1,length=props.length,valsLength=values.length,result={};while(++index<length){var value=index<valsLength?values[index]:undefined;assignFunc(result,props[index],value);}return result;}/**
     * Casts `value` to an empty array if it's not an array like object.
     *
     * @private
     * @param {*} value The value to inspect.
     * @returns {Array|Object} Returns the cast array-like object.
     */function castArrayLikeObject(value){return isArrayLikeObject(value)?value:[];}/**
     * Casts `value` to `identity` if it's not a function.
     *
     * @private
     * @param {*} value The value to inspect.
     * @returns {Function} Returns cast function.
     */function castFunction(value){return typeof value=='function'?value:identity;}/**
     * Casts `value` to a path array if it's not one.
     *
     * @private
     * @param {*} value The value to inspect.
     * @param {Object} [object] The object to query keys on.
     * @returns {Array} Returns the cast property path array.
     */function castPath(value,object){if(isArray(value)){return value;}return isKey(value,object)?[value]:stringToPath(toString(value));}/**
     * A `baseRest` alias which can be replaced with `identity` by module
     * replacement plugins.
     *
     * @private
     * @type {Function}
     * @param {Function} func The function to apply a rest parameter to.
     * @returns {Function} Returns the new function.
     */var castRest=baseRest;/**
     * Casts `array` to a slice if it's needed.
     *
     * @private
     * @param {Array} array The array to inspect.
     * @param {number} start The start position.
     * @param {number} [end=array.length] The end position.
     * @returns {Array} Returns the cast slice.
     */function castSlice(array,start,end){var length=array.length;end=end===undefined?length:end;return!start&&end>=length?array:baseSlice(array,start,end);}/**
     * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).
     *
     * @private
     * @param {number|Object} id The timer id or timeout object of the timer to clear.
     */var clearTimeout=ctxClearTimeout||function(id){return root.clearTimeout(id);};/**
     * Creates a clone of  `buffer`.
     *
     * @private
     * @param {Buffer} buffer The buffer to clone.
     * @param {boolean} [isDeep] Specify a deep clone.
     * @returns {Buffer} Returns the cloned buffer.
     */function cloneBuffer(buffer,isDeep){if(isDeep){return buffer.slice();}var length=buffer.length,result=allocUnsafe?allocUnsafe(length):new buffer.constructor(length);buffer.copy(result);return result;}/**
     * Creates a clone of `arrayBuffer`.
     *
     * @private
     * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
     * @returns {ArrayBuffer} Returns the cloned array buffer.
     */function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);new Uint8Array(result).set(new Uint8Array(arrayBuffer));return result;}/**
     * Creates a clone of `dataView`.
     *
     * @private
     * @param {Object} dataView The data view to clone.
     * @param {boolean} [isDeep] Specify a deep clone.
     * @returns {Object} Returns the cloned data view.
     */function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength);}/**
     * Creates a clone of `regexp`.
     *
     * @private
     * @param {Object} regexp The regexp to clone.
     * @returns {Object} Returns the cloned regexp.
     */function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));result.lastIndex=regexp.lastIndex;return result;}/**
     * Creates a clone of the `symbol` object.
     *
     * @private
     * @param {Object} symbol The symbol object to clone.
     * @returns {Object} Returns the cloned symbol object.
     */function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{};}/**
     * Creates a clone of `typedArray`.
     *
     * @private
     * @param {Object} typedArray The typed array to clone.
     * @param {boolean} [isDeep] Specify a deep clone.
     * @returns {Object} Returns the cloned typed array.
     */function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length);}/**
     * Compares values to sort them in ascending order.
     *
     * @private
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {number} Returns the sort order indicator for `value`.
     */function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=value===null,valIsReflexive=value===value,valIsSymbol=isSymbol(value);var othIsDefined=other!==undefined,othIsNull=other===null,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive){return 1;}if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&value<other||othIsSymbol&&valIsDefined&&valIsReflexive&&!valIsNull&&!valIsSymbol||othIsNull&&valIsDefined&&valIsReflexive||!othIsDefined&&valIsReflexive||!othIsReflexive){return-1;}}return 0;}/**
     * Used by `_.orderBy` to compare multiple properties of a value to another
     * and stable sort them.
     *
     * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
     * specify an order of "desc" for descending or "asc" for ascending sort order
     * of corresponding values.
     *
     * @private
     * @param {Object} object The object to compare.
     * @param {Object} other The other object to compare.
     * @param {boolean[]|string[]} orders The order to sort by for each property.
     * @returns {number} Returns the sort order indicator for `object`.
     */function compareMultiple(object,other,orders){var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length,ordersLength=orders.length;while(++index<length){var result=compareAscending(objCriteria[index],othCriteria[index]);if(result){if(index>=ordersLength){return result;}var order=orders[index];return result*(order=='desc'?-1:1);}}// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index-other.index;}/**
     * Creates an array that is the composition of partially applied arguments,
     * placeholders, and provided arguments into a single array of arguments.
     *
     * @private
     * @param {Array} args The provided arguments.
     * @param {Array} partials The arguments to prepend to those provided.
     * @param {Array} holders The `partials` placeholder indexes.
     * @params {boolean} [isCurried] Specify composing for a curried function.
     * @returns {Array} Returns the new array of composed arguments.
     */function composeArgs(args,partials,holders,isCurried){var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;while(++leftIndex<leftLength){result[leftIndex]=partials[leftIndex];}while(++argsIndex<holdersLength){if(isUncurried||argsIndex<argsLength){result[holders[argsIndex]]=args[argsIndex];}}while(rangeLength--){result[leftIndex++]=args[argsIndex++];}return result;}/**
     * This function is like `composeArgs` except that the arguments composition
     * is tailored for `_.partialRight`.
     *
     * @private
     * @param {Array} args The provided arguments.
     * @param {Array} partials The arguments to append to those provided.
     * @param {Array} holders The `partials` placeholder indexes.
     * @params {boolean} [isCurried] Specify composing for a curried function.
     * @returns {Array} Returns the new array of composed arguments.
     */function composeArgsRight(args,partials,holders,isCurried){var argsIndex=-1,argsLength=args.length,holdersIndex=-1,holdersLength=holders.length,rightIndex=-1,rightLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(rangeLength+rightLength),isUncurried=!isCurried;while(++argsIndex<rangeLength){result[argsIndex]=args[argsIndex];}var offset=argsIndex;while(++rightIndex<rightLength){result[offset+rightIndex]=partials[rightIndex];}while(++holdersIndex<holdersLength){if(isUncurried||argsIndex<argsLength){result[offset+holders[holdersIndex]]=args[argsIndex++];}}return result;}/**
     * Copies the values of `source` to `array`.
     *
     * @private
     * @param {Array} source The array to copy values from.
     * @param {Array} [array=[]] The array to copy values to.
     * @returns {Array} Returns `array`.
     */function copyArray(source,array){var index=-1,length=source.length;array||(array=Array(length));while(++index<length){array[index]=source[index];}return array;}/**
     * Copies properties of `source` to `object`.
     *
     * @private
     * @param {Object} source The object to copy properties from.
     * @param {Array} props The property identifiers to copy.
     * @param {Object} [object={}] The object to copy properties to.
     * @param {Function} [customizer] The function to customize copied values.
     * @returns {Object} Returns `object`.
     */function copyObject(source,props,object,customizer){var isNew=!object;object||(object={});var index=-1,length=props.length;while(++index<length){var key=props[index];var newValue=customizer?customizer(object[key],source[key],key,object,source):undefined;if(newValue===undefined){newValue=source[key];}if(isNew){baseAssignValue(object,key,newValue);}else{assignValue(object,key,newValue);}}return object;}/**
     * Copies own symbols of `source` to `object`.
     *
     * @private
     * @param {Object} source The object to copy symbols from.
     * @param {Object} [object={}] The object to copy symbols to.
     * @returns {Object} Returns `object`.
     */function copySymbols(source,object){return copyObject(source,getSymbols(source),object);}/**
     * Copies own and inherited symbols of `source` to `object`.
     *
     * @private
     * @param {Object} source The object to copy symbols from.
     * @param {Object} [object={}] The object to copy symbols to.
     * @returns {Object} Returns `object`.
     */function copySymbolsIn(source,object){return copyObject(source,getSymbolsIn(source),object);}/**
     * Creates a function like `_.groupBy`.
     *
     * @private
     * @param {Function} setter The function to set accumulator values.
     * @param {Function} [initializer] The accumulator object initializer.
     * @returns {Function} Returns the new aggregator function.
     */function createAggregator(setter,initializer){return function(collection,iteratee){var func=isArray(collection)?arrayAggregator:baseAggregator,accumulator=initializer?initializer():{};return func(collection,setter,getIteratee(iteratee,2),accumulator);};}/**
     * Creates a function like `_.assign`.
     *
     * @private
     * @param {Function} assigner The function to assign values.
     * @returns {Function} Returns the new assigner function.
     */function createAssigner(assigner){return baseRest(function(object,sources){var index=-1,length=sources.length,customizer=length>1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;customizer=assigner.length>3&&typeof customizer=='function'?(length--,customizer):undefined;if(guard&&isIterateeCall(sources[0],sources[1],guard)){customizer=length<3?undefined:customizer;length=1;}object=Object(object);while(++index<length){var source=sources[index];if(source){assigner(object,source,index,customizer);}}return object;});}/**
     * Creates a `baseEach` or `baseEachRight` function.
     *
     * @private
     * @param {Function} eachFunc The function to iterate over a collection.
     * @param {boolean} [fromRight] Specify iterating from right to left.
     * @returns {Function} Returns the new base function.
     */function createBaseEach(eachFunc,fromRight){return function(collection,iteratee){if(collection==null){return collection;}if(!isArrayLike(collection)){return eachFunc(collection,iteratee);}var length=collection.length,index=fromRight?length:-1,iterable=Object(collection);while(fromRight?index--:++index<length){if(iteratee(iterable[index],index,iterable)===false){break;}}return collection;};}/**
     * Creates a base function for methods like `_.forIn` and `_.forOwn`.
     *
     * @private
     * @param {boolean} [fromRight] Specify iterating from right to left.
     * @returns {Function} Returns the new base function.
     */function createBaseFor(fromRight){return function(object,iteratee,keysFunc){var index=-1,iterable=Object(object),props=keysFunc(object),length=props.length;while(length--){var key=props[fromRight?length:++index];if(iteratee(iterable[key],key,iterable)===false){break;}}return object;};}/**
     * Creates a function that wraps `func` to invoke it with the optional `this`
     * binding of `thisArg`.
     *
     * @private
     * @param {Function} func The function to wrap.
     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
     * @param {*} [thisArg] The `this` binding of `func`.
     * @returns {Function} Returns the new wrapped function.
     */function createBind(func,bitmask,thisArg){var isBind=bitmask&WRAP_BIND_FLAG,Ctor=createCtor(func);function wrapper(){var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return fn.apply(isBind?thisArg:this,arguments);}return wrapper;}/**
     * Creates a function like `_.lowerFirst`.
     *
     * @private
     * @param {string} methodName The name of the `String` case method to use.
     * @returns {Function} Returns the new case function.
     */function createCaseFirst(methodName){return function(string){string=toString(string);var strSymbols=hasUnicode(string)?stringToArray(string):undefined;var chr=strSymbols?strSymbols[0]:string.charAt(0);var trailing=strSymbols?castSlice(strSymbols,1).join(''):string.slice(1);return chr[methodName]()+trailing;};}/**
     * Creates a function like `_.camelCase`.
     *
     * @private
     * @param {Function} callback The function to combine each word.
     * @returns {Function} Returns the new compounder function.
     */function createCompounder(callback){return function(string){return arrayReduce(words(deburr(string).replace(reApos,'')),callback,'');};}/**
     * Creates a function that produces an instance of `Ctor` regardless of
     * whether it was invoked as part of a `new` expression or by `call` or `apply`.
     *
     * @private
     * @param {Function} Ctor The constructor to wrap.
     * @returns {Function} Returns the new wrapped function.
     */function createCtor(Ctor){return function(){// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args=arguments;switch(args.length){case 0:return new Ctor();case 1:return new Ctor(args[0]);case 2:return new Ctor(args[0],args[1]);case 3:return new Ctor(args[0],args[1],args[2]);case 4:return new Ctor(args[0],args[1],args[2],args[3]);case 5:return new Ctor(args[0],args[1],args[2],args[3],args[4]);case 6:return new Ctor(args[0],args[1],args[2],args[3],args[4],args[5]);case 7:return new Ctor(args[0],args[1],args[2],args[3],args[4],args[5],args[6]);}var thisBinding=baseCreate(Ctor.prototype),result=Ctor.apply(thisBinding,args);// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result)?result:thisBinding;};}/**
     * Creates a function that wraps `func` to enable currying.
     *
     * @private
     * @param {Function} func The function to wrap.
     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
     * @param {number} arity The arity of `func`.
     * @returns {Function} Returns the new wrapped function.
     */function createCurry(func,bitmask,arity){var Ctor=createCtor(func);function wrapper(){var length=arguments.length,args=Array(length),index=length,placeholder=getHolder(wrapper);while(index--){args[index]=arguments[index];}var holders=length<3&&args[0]!==placeholder&&args[length-1]!==placeholder?[]:replaceHolders(args,placeholder);length-=holders.length;if(length<arity){return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,undefined,args,holders,undefined,undefined,arity-length);}var fn=this&&this!==root&&this instanceof wrapper?Ctor:func;return apply(fn,this,args);}return wrapper;}/**
     * Creates a `_.find` or `_.findLast` function.
     *
     * @private
     * @param {Function} findIndexFunc The function to find the collection index.
     * @returns {Function} Returns the new find function.
     */function createFind(findIndexFunc){return function(collection,predicate,fromIndex){var iterable=Object(collection);if(!isArrayLike(collection)){var iteratee=getIteratee(predicate,3);collection=keys(collection);predicate=function(key){return iteratee(iterable[key],key,iterable);};}var index=findIndexFunc(collection,predicate,fromIndex);return index>-1?iterable[iteratee?collection[index]:index]:undefined;};}/**
     * Creates a `_.flow` or `_.flowRight` function.
     *
     * @private
     * @param {boolean} [fromRight] Specify iterating from right to left.
     * @returns {Function} Returns the new flow function.
     */function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;if(fromRight){funcs.reverse();}while(index--){var func=funcs[index];if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}if(prereq&&!wrapper&&getFuncName(func)=='wrapper'){var wrapper=new LodashWrapper([],true);}}index=wrapper?index:length;while(++index<length){func=funcs[index];var funcName=getFuncName(func),data=funcName=='wrapper'?getData(func):undefined;if(data&&isLaziable(data[0])&&data[1]==(WRAP_ARY_FLAG|WRAP_CURRY_FLAG|WRAP_PARTIAL_FLAG|WRAP_REARG_FLAG)&&!data[4].length&&data[9]==1){wrapper=wrapper[getFuncName(data[0])].apply(wrapper,data[3]);}else{wrapper=func.length==1&&isLaziable(func)?wrapper[funcName]():wrapper.thru(func);}}return function(){var args=arguments,value=args[0];if(wrapper&&args.length==1&&isArray(value)){return wrapper.plant(value).value();}var index=0,result=length?funcs[index].apply(this,args):value;while(++index<length){result=funcs[index].call(this,result);}return result;};});}/**
     * Creates a function that wraps `func` to invoke it with optional `this`
     * binding of `thisArg`, partial application, and currying.
     *
     * @private
     * @param {Function|string} func The function or method name to wrap.
     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
     * @param {*} [thisArg] The `this` binding of `func`.
     * @param {Array} [partials] The arguments to prepend to those provided to
     *  the new function.
     * @param {Array} [holders] The `partials` placeholder indexes.
     * @param {Array} [partialsRight] The arguments to append to those provided
     *  to the new function.
     * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
     * @param {Array} [argPos] The argument positions of the new function.
     * @param {number} [ary] The arity cap of `func`.
     * @param {number} [arity] The arity of `func`.
     * @returns {Function} Returns the new wrapped function.
     */function createHybrid(func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity){var isAry=bitmask&WRAP_ARY_FLAG,isBind=bitmask&WRAP_BIND_FLAG,isBindKey=bitmask&WRAP_BIND_KEY_FLAG,isCurried=bitmask&(WRAP_CURRY_FLAG|WRAP_CURRY_RIGHT_FLAG),isFlip=bitmask&WRAP_FLIP_FLAG,Ctor=isBindKey?undefined:createCtor(func);function wrapper(){var length=arguments.length,args=Array(length),index=length;while(index--){args[index]=arguments[index];}if(isCurried){var placeholder=getHolder(wrapper),holdersCount=countHolders(args,placeholder);}if(partials){args=composeArgs(args,partials,holders,isCurried);}if(partialsRight){args=composeArgsRight(args,partialsRight,holdersRight,isCurried);}length-=holdersCount;if(isCurried&&length<arity){var newHolders=replaceHolders(args,placeholder);return createRecurry(func,bitmask,createHybrid,wrapper.placeholder,thisArg,args,newHolders,argPos,ary,arity-length);}var thisBinding=isBind?thisArg:this,fn=isBindKey?thisBinding[func]:func;length=args.length;if(argPos){args=reorder(args,argPos);}else if(isFlip&&length>1){args.reverse();}if(isAry&&ary<length){args.length=ary;}if(this&&this!==root&&this instanceof wrapper){fn=Ctor||createCtor(fn);}return fn.apply(thisBinding,args);}return wrapper;}/**
     * Creates a function like `_.invertBy`.
     *
     * @private
     * @param {Function} setter The function to set accumulator values.
     * @param {Function} toIteratee The function to resolve iteratees.
     * @returns {Function} Returns the new inverter function.
     */function createInverter(setter,toIteratee){return function(object,iteratee){return baseInverter(object,setter,toIteratee(iteratee),{});};}/**
     * Creates a function that performs a mathematical operation on two values.
     *
     * @private
     * @param {Function} operator The function to perform the operation.
     * @param {number} [defaultValue] The value used for `undefined` arguments.
     * @returns {Function} Returns the new mathematical operation function.
     */function createMathOperation(operator,defaultValue){return function(value,other){var result;if(value===undefined&&other===undefined){return defaultValue;}if(value!==undefined){result=value;}if(other!==undefined){if(result===undefined){return other;}if(typeof value=='string'||typeof other=='string'){value=baseToString(value);other=baseToString(other);}else{value=baseToNumber(value);other=baseToNumber(other);}result=operator(value,other);}return result;};}/**
     * Creates a function like `_.over`.
     *
     * @private
     * @param {Function} arrayFunc The function to iterate over iteratees.
     * @returns {Function} Returns the new over function.
     */function createOver(arrayFunc){return flatRest(function(iteratees){iteratees=arrayMap(iteratees,baseUnary(getIteratee()));return baseRest(function(args){var thisArg=this;return arrayFunc(iteratees,function(iteratee){return apply(iteratee,thisArg,args);});});});}/**
     * Creates the padding for `string` based on `length`. The `chars` string
     * is truncated if the number of characters exceeds `length`.
     *
     * @private
     * @param {number} length The padding length.
     * @param {string} [chars=' '] The string used as padding.
     * @returns {string} Returns the padding for `string`.
     */function createPadding(length,chars){chars=chars===undefined?' ':baseToString(chars);var charsLength=chars.length;if(charsLength<2){return charsLength?baseRepeat(chars,length):chars;}var result=baseRepeat(chars,nativeCeil(length/stringSize(chars)));return hasUnicode(chars)?castSlice(stringToArray(result),0,length).join(''):result.slice(0,length);}/**
     * Creates a function that wraps `func` to invoke it with the `this` binding
     * of `thisArg` and `partials` prepended to the arguments it receives.
     *
     * @private
     * @param {Function} func The function to wrap.
     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
     * @param {*} thisArg The `this` binding of `func`.
     * @param {Array} partials The arguments to prepend to those provided to
     *  the new function.
     * @returns {Function} Returns the new wrapped function.
     */function createPartial(func,bitmask,thisArg,partials){var isBind=bitmask&WRAP_BIND_FLAG,Ctor=createCtor(func);function wrapper(){var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(leftLength+argsLength),fn=this&&this!==root&&this instanceof wrapper?Ctor:func;while(++leftIndex<leftLength){args[leftIndex]=partials[leftIndex];}while(argsLength--){args[leftIndex++]=arguments[++argsIndex];}return apply(fn,isBind?thisArg:this,args);}return wrapper;}/**
     * Creates a `_.range` or `_.rangeRight` function.
     *
     * @private
     * @param {boolean} [fromRight] Specify iterating from right to left.
     * @returns {Function} Returns the new range function.
     */function createRange(fromRight){return function(start,end,step){if(step&&typeof step!='number'&&isIterateeCall(start,end,step)){end=step=undefined;}// Ensure the sign of `-0` is preserved.
start=toFinite(start);if(end===undefined){end=start;start=0;}else{end=toFinite(end);}step=step===undefined?start<end?1:-1:toFinite(step);return baseRange(start,end,step,fromRight);};}/**
     * Creates a function that performs a relational operation on two values.
     *
     * @private
     * @param {Function} operator The function to perform the operation.
     * @returns {Function} Returns the new relational operation function.
     */function createRelationalOperation(operator){return function(value,other){if(!(typeof value=='string'&&typeof other=='string')){value=toNumber(value);other=toNumber(other);}return operator(value,other);};}/**
     * Creates a function that wraps `func` to continue currying.
     *
     * @private
     * @param {Function} func The function to wrap.
     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
     * @param {Function} wrapFunc The function to create the `func` wrapper.
     * @param {*} placeholder The placeholder value.
     * @param {*} [thisArg] The `this` binding of `func`.
     * @param {Array} [partials] The arguments to prepend to those provided to
     *  the new function.
     * @param {Array} [holders] The `partials` placeholder indexes.
     * @param {Array} [argPos] The argument positions of the new function.
     * @param {number} [ary] The arity cap of `func`.
     * @param {number} [arity] The arity of `func`.
     * @returns {Function} Returns the new wrapped function.
     */function createRecurry(func,bitmask,wrapFunc,placeholder,thisArg,partials,holders,argPos,ary,arity){var isCurry=bitmask&WRAP_CURRY_FLAG,newHolders=isCurry?holders:undefined,newHoldersRight=isCurry?undefined:holders,newPartials=isCurry?partials:undefined,newPartialsRight=isCurry?undefined:partials;bitmask|=isCurry?WRAP_PARTIAL_FLAG:WRAP_PARTIAL_RIGHT_FLAG;bitmask&=~(isCurry?WRAP_PARTIAL_RIGHT_FLAG:WRAP_PARTIAL_FLAG);if(!(bitmask&WRAP_CURRY_BOUND_FLAG)){bitmask&=~(WRAP_BIND_FLAG|WRAP_BIND_KEY_FLAG);}var newData=[func,bitmask,thisArg,newPartials,newHolders,newPartialsRight,newHoldersRight,argPos,ary,arity];var result=wrapFunc.apply(undefined,newData);if(isLaziable(func)){setData(result,newData);}result.placeholder=placeholder;return setWrapToString(result,func,bitmask);}/**
     * Creates a function like `_.round`.
     *
     * @private
     * @param {string} methodName The name of the `Math` method to use when rounding.
     * @returns {Function} Returns the new round function.
     */function createRound(methodName){var func=Math[methodName];return function(number,precision){number=toNumber(number);precision=precision==null?0:nativeMin(toInteger(precision),292);if(precision&&nativeIsFinite(number)){// Shift with exponential notation to avoid floating-point issues.
// See [MDN](https://mdn.io/round#Examples) for more details.
var pair=(toString(number)+'e').split('e'),value=func(pair[0]+'e'+(+pair[1]+precision));pair=(toString(value)+'e').split('e');return+(pair[0]+'e'+(+pair[1]-precision));}return func(number);};}/**
     * Creates a set object of `values`.
     *
     * @private
     * @param {Array} values The values to add to the set.
     * @returns {Object} Returns the new set.
     */var createSet=!(Set&&1/setToArray(new Set([,-0]))[1]==INFINITY)?noop:function(values){return new Set(values);};/**
     * Creates a `_.toPairs` or `_.toPairsIn` function.
     *
     * @private
     * @param {Function} keysFunc The function to get the keys of a given object.
     * @returns {Function} Returns the new pairs function.
     */function createToPairs(keysFunc){return function(object){var tag=getTag(object);if(tag==mapTag){return mapToArray(object);}if(tag==setTag){return setToPairs(object);}return baseToPairs(object,keysFunc(object));};}/**
     * Creates a function that either curries or invokes `func` with optional
     * `this` binding and partially applied arguments.
     *
     * @private
     * @param {Function|string} func The function or method name to wrap.
     * @param {number} bitmask The bitmask flags.
     *    1 - `_.bind`
     *    2 - `_.bindKey`
     *    4 - `_.curry` or `_.curryRight` of a bound function
     *    8 - `_.curry`
     *   16 - `_.curryRight`
     *   32 - `_.partial`
     *   64 - `_.partialRight`
     *  128 - `_.rearg`
     *  256 - `_.ary`
     *  512 - `_.flip`
     * @param {*} [thisArg] The `this` binding of `func`.
     * @param {Array} [partials] The arguments to be partially applied.
     * @param {Array} [holders] The `partials` placeholder indexes.
     * @param {Array} [argPos] The argument positions of the new function.
     * @param {number} [ary] The arity cap of `func`.
     * @param {number} [arity] The arity of `func`.
     * @returns {Function} Returns the new wrapped function.
     */function createWrap(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&WRAP_BIND_KEY_FLAG;if(!isBindKey&&typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}var length=partials?partials.length:0;if(!length){bitmask&=~(WRAP_PARTIAL_FLAG|WRAP_PARTIAL_RIGHT_FLAG);partials=holders=undefined;}ary=ary===undefined?ary:nativeMax(toInteger(ary),0);arity=arity===undefined?arity:toInteger(arity);length-=holders?holders.length:0;if(bitmask&WRAP_PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=undefined;}var data=isBindKey?undefined:getData(func);var newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data){mergeData(newData,data);}func=newData[0];bitmask=newData[1];thisArg=newData[2];partials=newData[3];holders=newData[4];arity=newData[9]=newData[9]===undefined?isBindKey?0:func.length:nativeMax(newData[9]-length,0);if(!arity&&bitmask&(WRAP_CURRY_FLAG|WRAP_CURRY_RIGHT_FLAG)){bitmask&=~(WRAP_CURRY_FLAG|WRAP_CURRY_RIGHT_FLAG);}if(!bitmask||bitmask==WRAP_BIND_FLAG){var result=createBind(func,bitmask,thisArg);}else if(bitmask==WRAP_CURRY_FLAG||bitmask==WRAP_CURRY_RIGHT_FLAG){result=createCurry(func,bitmask,arity);}else if((bitmask==WRAP_PARTIAL_FLAG||bitmask==(WRAP_BIND_FLAG|WRAP_PARTIAL_FLAG))&&!holders.length){result=createPartial(func,bitmask,thisArg,partials);}else{result=createHybrid.apply(undefined,newData);}var setter=data?baseSetData:setData;return setWrapToString(setter(result,newData),func,bitmask);}/**
     * Used by `_.defaults` to customize its `_.assignIn` use to assign properties
     * of source objects to the destination object for all destination properties
     * that resolve to `undefined`.
     *
     * @private
     * @param {*} objValue The destination value.
     * @param {*} srcValue The source value.
     * @param {string} key The key of the property to assign.
     * @param {Object} object The parent object of `objValue`.
     * @returns {*} Returns the value to assign.
     */function customDefaultsAssignIn(objValue,srcValue,key,object){if(objValue===undefined||eq(objValue,objectProto[key])&&!hasOwnProperty.call(object,key)){return srcValue;}return objValue;}/**
     * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source
     * objects into destination objects that are passed thru.
     *
     * @private
     * @param {*} objValue The destination value.
     * @param {*} srcValue The source value.
     * @param {string} key The key of the property to merge.
     * @param {Object} object The parent object of `objValue`.
     * @param {Object} source The parent object of `srcValue`.
     * @param {Object} [stack] Tracks traversed source values and their merged
     *  counterparts.
     * @returns {*} Returns the value to assign.
     */function customDefaultsMerge(objValue,srcValue,key,object,source,stack){if(isObject(objValue)&&isObject(srcValue)){// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue,objValue);baseMerge(objValue,srcValue,undefined,customDefaultsMerge,stack);stack['delete'](srcValue);}return objValue;}/**
     * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
     * objects.
     *
     * @private
     * @param {*} value The value to inspect.
     * @param {string} key The key of the property to inspect.
     * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
     */function customOmitClone(value){return isPlainObject(value)?undefined:value;}/**
     * A specialized version of `baseIsEqualDeep` for arrays with support for
     * partial deep comparisons.
     *
     * @private
     * @param {Array} array The array to compare.
     * @param {Array} other The other array to compare.
     * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
     * @param {Function} customizer The function to customize comparisons.
     * @param {Function} equalFunc The function to determine equivalents of values.
     * @param {Object} stack Tracks traversed `array` and `other` objects.
     * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
     */function equalArrays(array,other,bitmask,customizer,equalFunc,stack){var isPartial=bitmask&COMPARE_PARTIAL_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength)){return false;}// Check that cyclic values are equal.
var arrStacked=stack.get(array);var othStacked=stack.get(other);if(arrStacked&&othStacked){return arrStacked==other&&othStacked==array;}var index=-1,result=true,seen=bitmask&COMPARE_UNORDERED_FLAG?new SetCache():undefined;stack.set(array,other);stack.set(other,array);// Ignore non-index properties.
while(++index<arrLength){var arrValue=array[index],othValue=other[index];if(customizer){var compared=isPartial?customizer(othValue,arrValue,index,other,array,stack):customizer(arrValue,othValue,index,array,other,stack);}if(compared!==undefined){if(compared){continue;}result=false;break;}// Recursively compare arrays (susceptible to call stack limits).
if(seen){if(!arraySome(other,function(othValue,othIndex){if(!cacheHas(seen,othIndex)&&(arrValue===othValue||equalFunc(arrValue,othValue,bitmask,customizer,stack))){return seen.push(othIndex);}})){result=false;break;}}else if(!(arrValue===othValue||equalFunc(arrValue,othValue,bitmask,customizer,stack))){result=false;break;}}stack['delete'](array);stack['delete'](other);return result;}/**
     * A specialized version of `baseIsEqualDeep` for comparing objects of
     * the same `toStringTag`.
     *
     * **Note:** This function only supports comparing values with tags of
     * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
     *
     * @private
     * @param {Object} object The object to compare.
     * @param {Object} other The other object to compare.
     * @param {string} tag The `toStringTag` of the objects to compare.
     * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
     * @param {Function} customizer The function to customize comparisons.
     * @param {Function} equalFunc The function to determine equivalents of values.
     * @param {Object} stack Tracks traversed `object` and `other` objects.
     * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
     */function equalByTag(object,other,tag,bitmask,customizer,equalFunc,stack){switch(tag){case dataViewTag:if(object.byteLength!=other.byteLength||object.byteOffset!=other.byteOffset){return false;}object=object.buffer;other=other.buffer;case arrayBufferTag:if(object.byteLength!=other.byteLength||!equalFunc(new Uint8Array(object),new Uint8Array(other))){return false;}return true;case boolTag:case dateTag:case numberTag:// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object,+other);case errorTag:return object.name==other.name&&object.message==other.message;case regexpTag:case stringTag:// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object==other+'';case mapTag:var convert=mapToArray;case setTag:var isPartial=bitmask&COMPARE_PARTIAL_FLAG;convert||(convert=setToArray);if(object.size!=other.size&&!isPartial){return false;}// Assume cyclic values are equal.
var stacked=stack.get(object);if(stacked){return stacked==other;}bitmask|=COMPARE_UNORDERED_FLAG;// Recursively compare objects (susceptible to call stack limits).
stack.set(object,other);var result=equalArrays(convert(object),convert(other),bitmask,customizer,equalFunc,stack);stack['delete'](object);return result;case symbolTag:if(symbolValueOf){return symbolValueOf.call(object)==symbolValueOf.call(other);}}return false;}/**
     * A specialized version of `baseIsEqualDeep` for objects with support for
     * partial deep comparisons.
     *
     * @private
     * @param {Object} object The object to compare.
     * @param {Object} other The other object to compare.
     * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
     * @param {Function} customizer The function to customize comparisons.
     * @param {Function} equalFunc The function to determine equivalents of values.
     * @param {Object} stack Tracks traversed `object` and `other` objects.
     * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
     */function equalObjects(object,other,bitmask,customizer,equalFunc,stack){var isPartial=bitmask&COMPARE_PARTIAL_FLAG,objProps=getAllKeys(object),objLength=objProps.length,othProps=getAllKeys(other),othLength=othProps.length;if(objLength!=othLength&&!isPartial){return false;}var index=objLength;while(index--){var key=objProps[index];if(!(isPartial?key in other:hasOwnProperty.call(other,key))){return false;}}// Check that cyclic values are equal.
var objStacked=stack.get(object);var othStacked=stack.get(other);if(objStacked&&othStacked){return objStacked==other&&othStacked==object;}var result=true;stack.set(object,other);stack.set(other,object);var skipCtor=isPartial;while(++index<objLength){key=objProps[index];var objValue=object[key],othValue=other[key];if(customizer){var compared=isPartial?customizer(othValue,objValue,key,other,object,stack):customizer(objValue,othValue,key,object,other,stack);}// Recursively compare objects (susceptible to call stack limits).
if(!(compared===undefined?objValue===othValue||equalFunc(objValue,othValue,bitmask,customizer,stack):compared)){result=false;break;}skipCtor||(skipCtor=key=='constructor');}if(result&&!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;// Non `Object` object instances with different constructors are not equal.
if(objCtor!=othCtor&&'constructor'in object&&'constructor'in other&&!(typeof objCtor=='function'&&objCtor instanceof objCtor&&typeof othCtor=='function'&&othCtor instanceof othCtor)){result=false;}}stack['delete'](object);stack['delete'](other);return result;}/**
     * A specialized version of `baseRest` which flattens the rest array.
     *
     * @private
     * @param {Function} func The function to apply a rest parameter to.
     * @returns {Function} Returns the new function.
     */function flatRest(func){return setToString(overRest(func,undefined,flatten),func+'');}/**
     * Creates an array of own enumerable property names and symbols of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property names and symbols.
     */function getAllKeys(object){return baseGetAllKeys(object,keys,getSymbols);}/**
     * Creates an array of own and inherited enumerable property names and
     * symbols of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property names and symbols.
     */function getAllKeysIn(object){return baseGetAllKeys(object,keysIn,getSymbolsIn);}/**
     * Gets metadata for `func`.
     *
     * @private
     * @param {Function} func The function to query.
     * @returns {*} Returns the metadata for `func`.
     */var getData=!metaMap?noop:function(func){return metaMap.get(func);};/**
     * Gets the name of `func`.
     *
     * @private
     * @param {Function} func The function to query.
     * @returns {string} Returns the function name.
     */function getFuncName(func){var result=func.name+'',array=realNames[result],length=hasOwnProperty.call(realNames,result)?array.length:0;while(length--){var data=array[length],otherFunc=data.func;if(otherFunc==null||otherFunc==func){return data.name;}}return result;}/**
     * Gets the argument placeholder value for `func`.
     *
     * @private
     * @param {Function} func The function to inspect.
     * @returns {*} Returns the placeholder value.
     */function getHolder(func){var object=hasOwnProperty.call(lodash,'placeholder')?lodash:func;return object.placeholder;}/**
     * Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
     * this function returns the custom method, otherwise it returns `baseIteratee`.
     * If arguments are provided, the chosen function is invoked with them and
     * its result is returned.
     *
     * @private
     * @param {*} [value] The value to convert to an iteratee.
     * @param {number} [arity] The arity of the created iteratee.
     * @returns {Function} Returns the chosen function or its result.
     */function getIteratee(){var result=lodash.iteratee||iteratee;result=result===iteratee?baseIteratee:result;return arguments.length?result(arguments[0],arguments[1]):result;}/**
     * Gets the data for `map`.
     *
     * @private
     * @param {Object} map The map to query.
     * @param {string} key The reference key.
     * @returns {*} Returns the map data.
     */function getMapData(map,key){var data=map.__data__;return isKeyable(key)?data[typeof key=='string'?'string':'hash']:data.map;}/**
     * Gets the property names, values, and compare flags of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the match data of `object`.
     */function getMatchData(object){var result=keys(object),length=result.length;while(length--){var key=result[length],value=object[key];result[length]=[key,value,isStrictComparable(value)];}return result;}/**
     * Gets the native function at `key` of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @param {string} key The key of the method to get.
     * @returns {*} Returns the function if it's native, else `undefined`.
     */function getNative(object,key){var value=getValue(object,key);return baseIsNative(value)?value:undefined;}/**
     * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
     *
     * @private
     * @param {*} value The value to query.
     * @returns {string} Returns the raw `toStringTag`.
     */function getRawTag(value){var isOwn=hasOwnProperty.call(value,symToStringTag),tag=value[symToStringTag];try{value[symToStringTag]=undefined;var unmasked=true;}catch(e){}var result=nativeObjectToString.call(value);if(unmasked){if(isOwn){value[symToStringTag]=tag;}else{delete value[symToStringTag];}}return result;}/**
     * Creates an array of the own enumerable symbols of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of symbols.
     */var getSymbols=!nativeGetSymbols?stubArray:function(object){if(object==null){return[];}object=Object(object);return arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable.call(object,symbol);});};/**
     * Creates an array of the own and inherited enumerable symbols of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of symbols.
     */var getSymbolsIn=!nativeGetSymbols?stubArray:function(object){var result=[];while(object){arrayPush(result,getSymbols(object));object=getPrototype(object);}return result;};/**
     * Gets the `toStringTag` of `value`.
     *
     * @private
     * @param {*} value The value to query.
     * @returns {string} Returns the `toStringTag`.
     */var getTag=baseGetTag;// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if(DataView&&getTag(new DataView(new ArrayBuffer(1)))!=dataViewTag||Map&&getTag(new Map())!=mapTag||Promise&&getTag(Promise.resolve())!=promiseTag||Set&&getTag(new Set())!=setTag||WeakMap&&getTag(new WeakMap())!=weakMapTag){getTag=function(value){var result=baseGetTag(value),Ctor=result==objectTag?value.constructor:undefined,ctorString=Ctor?toSource(Ctor):'';if(ctorString){switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return promiseTag;case setCtorString:return setTag;case weakMapCtorString:return weakMapTag;}}return result;};}/**
     * Gets the view, applying any `transforms` to the `start` and `end` positions.
     *
     * @private
     * @param {number} start The start of the view.
     * @param {number} end The end of the view.
     * @param {Array} transforms The transformations to apply to the view.
     * @returns {Object} Returns an object containing the `start` and `end`
     *  positions of the view.
     */function getView(start,end,transforms){var index=-1,length=transforms.length;while(++index<length){var data=transforms[index],size=data.size;switch(data.type){case'drop':start+=size;break;case'dropRight':end-=size;break;case'take':end=nativeMin(end,start+size);break;case'takeRight':start=nativeMax(start,end-size);break;}}return{'start':start,'end':end};}/**
     * Extracts wrapper details from the `source` body comment.
     *
     * @private
     * @param {string} source The source to inspect.
     * @returns {Array} Returns the wrapper details.
     */function getWrapDetails(source){var match=source.match(reWrapDetails);return match?match[1].split(reSplitDetails):[];}/**
     * Checks if `path` exists on `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @param {Array|string} path The path to check.
     * @param {Function} hasFunc The function to check properties.
     * @returns {boolean} Returns `true` if `path` exists, else `false`.
     */function hasPath(object,path,hasFunc){path=castPath(path,object);var index=-1,length=path.length,result=false;while(++index<length){var key=toKey(path[index]);if(!(result=object!=null&&hasFunc(object,key))){break;}object=object[key];}if(result||++index!=length){return result;}length=object==null?0:object.length;return!!length&&isLength(length)&&isIndex(key,length)&&(isArray(object)||isArguments(object));}/**
     * Initializes an array clone.
     *
     * @private
     * @param {Array} array The array to clone.
     * @returns {Array} Returns the initialized clone.
     */function initCloneArray(array){var length=array.length,result=new array.constructor(length);// Add properties assigned by `RegExp#exec`.
if(length&&typeof array[0]=='string'&&hasOwnProperty.call(array,'index')){result.index=array.index;result.input=array.input;}return result;}/**
     * Initializes an object clone.
     *
     * @private
     * @param {Object} object The object to clone.
     * @returns {Object} Returns the initialized clone.
     */function initCloneObject(object){return typeof object.constructor=='function'&&!isPrototype(object)?baseCreate(getPrototype(object)):{};}/**
     * Initializes an object clone based on its `toStringTag`.
     *
     * **Note:** This function only supports cloning values with tags of
     * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
     *
     * @private
     * @param {Object} object The object to clone.
     * @param {string} tag The `toStringTag` of the object to clone.
     * @param {boolean} [isDeep] Specify a deep clone.
     * @returns {Object} Returns the initialized clone.
     */function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return cloneArrayBuffer(object);case boolTag:case dateTag:return new Ctor(+object);case dataViewTag:return cloneDataView(object,isDeep);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:return cloneTypedArray(object,isDeep);case mapTag:return new Ctor();case numberTag:case stringTag:return new Ctor(object);case regexpTag:return cloneRegExp(object);case setTag:return new Ctor();case symbolTag:return cloneSymbol(object);}}/**
     * Inserts wrapper `details` in a comment at the top of the `source` body.
     *
     * @private
     * @param {string} source The source to modify.
     * @returns {Array} details The details to insert.
     * @returns {string} Returns the modified source.
     */function insertWrapDetails(source,details){var length=details.length;if(!length){return source;}var lastIndex=length-1;details[lastIndex]=(length>1?'& ':'')+details[lastIndex];details=details.join(length>2?', ':' ');return source.replace(reWrapComment,'{\n/* [wrapped with '+details+'] */\n');}/**
     * Checks if `value` is a flattenable `arguments` object or array.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
     */function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol]);}/**
     * Checks if `value` is a valid array-like index.
     *
     * @private
     * @param {*} value The value to check.
     * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
     * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
     */function isIndex(value,length){var type=typeof value;length=length==null?MAX_SAFE_INTEGER:length;return!!length&&(type=='number'||type!='symbol'&&reIsUint.test(value))&&value>-1&&value%1==0&&value<length;}/**
     * Checks if the given arguments are from an iteratee call.
     *
     * @private
     * @param {*} value The potential iteratee value argument.
     * @param {*} index The potential iteratee index or key argument.
     * @param {*} object The potential iteratee object argument.
     * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
     *  else `false`.
     */function isIterateeCall(value,index,object){if(!isObject(object)){return false;}var type=typeof index;if(type=='number'?isArrayLike(object)&&isIndex(index,object.length):type=='string'&&index in object){return eq(object[index],value);}return false;}/**
     * Checks if `value` is a property name and not a property path.
     *
     * @private
     * @param {*} value The value to check.
     * @param {Object} [object] The object to query keys on.
     * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
     */function isKey(value,object){if(isArray(value)){return false;}var type=typeof value;if(type=='number'||type=='symbol'||type=='boolean'||value==null||isSymbol(value)){return true;}return reIsPlainProp.test(value)||!reIsDeepProp.test(value)||object!=null&&value in Object(object);}/**
     * Checks if `value` is suitable for use as unique object key.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
     */function isKeyable(value){var type=typeof value;return type=='string'||type=='number'||type=='symbol'||type=='boolean'?value!=='__proto__':value===null;}/**
     * Checks if `func` has a lazy counterpart.
     *
     * @private
     * @param {Function} func The function to check.
     * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
     *  else `false`.
     */function isLaziable(func){var funcName=getFuncName(func),other=lodash[funcName];if(typeof other!='function'||!(funcName in LazyWrapper.prototype)){return false;}if(func===other){return true;}var data=getData(other);return!!data&&func===data[0];}/**
     * Checks if `func` has its source masked.
     *
     * @private
     * @param {Function} func The function to check.
     * @returns {boolean} Returns `true` if `func` is masked, else `false`.
     */function isMasked(func){return!!maskSrcKey&&maskSrcKey in func;}/**
     * Checks if `func` is capable of being masked.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `func` is maskable, else `false`.
     */var isMaskable=coreJsData?isFunction:stubFalse;/**
     * Checks if `value` is likely a prototype object.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
     */function isPrototype(value){var Ctor=value&&value.constructor,proto=typeof Ctor=='function'&&Ctor.prototype||objectProto;return value===proto;}/**
     * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` if suitable for strict
     *  equality comparisons, else `false`.
     */function isStrictComparable(value){return value===value&&!isObject(value);}/**
     * A specialized version of `matchesProperty` for source values suitable
     * for strict equality comparisons, i.e. `===`.
     *
     * @private
     * @param {string} key The key of the property to get.
     * @param {*} srcValue The value to match.
     * @returns {Function} Returns the new spec function.
     */function matchesStrictComparable(key,srcValue){return function(object){if(object==null){return false;}return object[key]===srcValue&&(srcValue!==undefined||key in Object(object));};}/**
     * A specialized version of `_.memoize` which clears the memoized function's
     * cache when it exceeds `MAX_MEMOIZE_SIZE`.
     *
     * @private
     * @param {Function} func The function to have its output memoized.
     * @returns {Function} Returns the new memoized function.
     */function memoizeCapped(func){var result=memoize(func,function(key){if(cache.size===MAX_MEMOIZE_SIZE){cache.clear();}return key;});var cache=result.cache;return result;}/**
     * Merges the function metadata of `source` into `data`.
     *
     * Merging metadata reduces the number of wrappers used to invoke a function.
     * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
     * may be applied regardless of execution order. Methods like `_.ary` and
     * `_.rearg` modify function arguments, making the order in which they are
     * executed important, preventing the merging of metadata. However, we make
     * an exception for a safe combined case where curried functions have `_.ary`
     * and or `_.rearg` applied.
     *
     * @private
     * @param {Array} data The destination metadata.
     * @param {Array} source The source metadata.
     * @returns {Array} Returns `data`.
     */function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask,isCommon=newBitmask<(WRAP_BIND_FLAG|WRAP_BIND_KEY_FLAG|WRAP_ARY_FLAG);var isCombo=srcBitmask==WRAP_ARY_FLAG&&bitmask==WRAP_CURRY_FLAG||srcBitmask==WRAP_ARY_FLAG&&bitmask==WRAP_REARG_FLAG&&data[7].length<=source[8]||srcBitmask==(WRAP_ARY_FLAG|WRAP_REARG_FLAG)&&source[7].length<=source[8]&&bitmask==WRAP_CURRY_FLAG;// Exit early if metadata can't be merged.
if(!(isCommon||isCombo)){return data;}// Use source `thisArg` if available.
if(srcBitmask&WRAP_BIND_FLAG){data[2]=source[2];// Set when currying a bound function.
newBitmask|=bitmask&WRAP_BIND_FLAG?0:WRAP_CURRY_BOUND_FLAG;}// Compose partial arguments.
var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):value;data[4]=partials?replaceHolders(data[3],PLACEHOLDER):source[4];}// Compose partial right arguments.
value=source[5];if(value){partials=data[5];data[5]=partials?composeArgsRight(partials,value,source[6]):value;data[6]=partials?replaceHolders(data[5],PLACEHOLDER):source[6];}// Use source `argPos` if available.
value=source[7];if(value){data[7]=value;}// Use source `ary` if it's smaller.
if(srcBitmask&WRAP_ARY_FLAG){data[8]=data[8]==null?source[8]:nativeMin(data[8],source[8]);}// Use source `arity` if one is not provided.
if(data[9]==null){data[9]=source[9];}// Use source `func` and merge bitmasks.
data[0]=source[0];data[1]=newBitmask;return data;}/**
     * This function is like
     * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
     * except that it includes inherited enumerable properties.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property names.
     */function nativeKeysIn(object){var result=[];if(object!=null){for(var key in Object(object)){result.push(key);}}return result;}/**
     * Converts `value` to a string using `Object.prototype.toString`.
     *
     * @private
     * @param {*} value The value to convert.
     * @returns {string} Returns the converted string.
     */function objectToString(value){return nativeObjectToString.call(value);}/**
     * A specialized version of `baseRest` which transforms the rest array.
     *
     * @private
     * @param {Function} func The function to apply a rest parameter to.
     * @param {number} [start=func.length-1] The start position of the rest parameter.
     * @param {Function} transform The rest array transform.
     * @returns {Function} Returns the new function.
     */function overRest(func,start,transform){start=nativeMax(start===undefined?func.length-1:start,0);return function(){var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);while(++index<length){array[index]=args[start+index];}index=-1;var otherArgs=Array(start+1);while(++index<start){otherArgs[index]=args[index];}otherArgs[start]=transform(array);return apply(func,this,otherArgs);};}/**
     * Gets the parent value at `path` of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @param {Array} path The path to get the parent value of.
     * @returns {*} Returns the parent value.
     */function parent(object,path){return path.length<2?object:baseGet(object,baseSlice(path,0,-1));}/**
     * Reorder `array` according to the specified indexes where the element at
     * the first index is assigned as the first element, the element at
     * the second index is assigned as the second element, and so on.
     *
     * @private
     * @param {Array} array The array to reorder.
     * @param {Array} indexes The arranged array indexes.
     * @returns {Array} Returns `array`.
     */function reorder(array,indexes){var arrLength=array.length,length=nativeMin(indexes.length,arrLength),oldArray=copyArray(array);while(length--){var index=indexes[length];array[length]=isIndex(index,arrLength)?oldArray[index]:undefined;}return array;}/**
     * Gets the value at `key`, unless `key` is "__proto__" or "constructor".
     *
     * @private
     * @param {Object} object The object to query.
     * @param {string} key The key of the property to get.
     * @returns {*} Returns the property value.
     */function safeGet(object,key){if(key==='constructor'&&typeof object[key]==='function'){return;}if(key=='__proto__'){return;}return object[key];}/**
     * Sets metadata for `func`.
     *
     * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
     * period of time, it will trip its breaker and transition to an identity
     * function to avoid garbage collection pauses in V8. See
     * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
     * for more details.
     *
     * @private
     * @param {Function} func The function to associate metadata with.
     * @param {*} data The metadata.
     * @returns {Function} Returns `func`.
     */var setData=shortOut(baseSetData);/**
     * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).
     *
     * @private
     * @param {Function} func The function to delay.
     * @param {number} wait The number of milliseconds to delay invocation.
     * @returns {number|Object} Returns the timer id or timeout object.
     */var setTimeout=ctxSetTimeout||function(func,wait){return root.setTimeout(func,wait);};/**
     * Sets the `toString` method of `func` to return `string`.
     *
     * @private
     * @param {Function} func The function to modify.
     * @param {Function} string The `toString` result.
     * @returns {Function} Returns `func`.
     */var setToString=shortOut(baseSetToString);/**
     * Sets the `toString` method of `wrapper` to mimic the source of `reference`
     * with wrapper details in a comment at the top of the source body.
     *
     * @private
     * @param {Function} wrapper The function to modify.
     * @param {Function} reference The reference function.
     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
     * @returns {Function} Returns `wrapper`.
     */function setWrapToString(wrapper,reference,bitmask){var source=reference+'';return setToString(wrapper,insertWrapDetails(source,updateWrapDetails(getWrapDetails(source),bitmask)));}/**
     * Creates a function that'll short out and invoke `identity` instead
     * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
     * milliseconds.
     *
     * @private
     * @param {Function} func The function to restrict.
     * @returns {Function} Returns the new shortable function.
     */function shortOut(func){var count=0,lastCalled=0;return function(){var stamp=nativeNow(),remaining=HOT_SPAN-(stamp-lastCalled);lastCalled=stamp;if(remaining>0){if(++count>=HOT_COUNT){return arguments[0];}}else{count=0;}return func.apply(undefined,arguments);};}/**
     * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
     *
     * @private
     * @param {Array} array The array to shuffle.
     * @param {number} [size=array.length] The size of `array`.
     * @returns {Array} Returns `array`.
     */function shuffleSelf(array,size){var index=-1,length=array.length,lastIndex=length-1;size=size===undefined?length:size;while(++index<size){var rand=baseRandom(index,lastIndex),value=array[rand];array[rand]=array[index];array[index]=value;}array.length=size;return array;}/**
     * Converts `string` to a property path array.
     *
     * @private
     * @param {string} string The string to convert.
     * @returns {Array} Returns the property path array.
     */var stringToPath=memoizeCapped(function(string){var result=[];if(string.charCodeAt(0)===46/* . */){result.push('');}string.replace(rePropName,function(match,number,quote,subString){result.push(quote?subString.replace(reEscapeChar,'$1'):number||match);});return result;});/**
     * Converts `value` to a string key if it's not a string or symbol.
     *
     * @private
     * @param {*} value The value to inspect.
     * @returns {string|symbol} Returns the key.
     */function toKey(value){if(typeof value=='string'||isSymbol(value)){return value;}var result=value+'';return result=='0'&&1/value==-INFINITY?'-0':result;}/**
     * Converts `func` to its source code.
     *
     * @private
     * @param {Function} func The function to convert.
     * @returns {string} Returns the source code.
     */function toSource(func){if(func!=null){try{return funcToString.call(func);}catch(e){}try{return func+'';}catch(e){}}return'';}/**
     * Updates wrapper `details` based on `bitmask` flags.
     *
     * @private
     * @returns {Array} details The details to modify.
     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
     * @returns {Array} Returns `details`.
     */function updateWrapDetails(details,bitmask){arrayEach(wrapFlags,function(pair){var value='_.'+pair[0];if(bitmask&pair[1]&&!arrayIncludes(details,value)){details.push(value);}});return details.sort();}/**
     * Creates a clone of `wrapper`.
     *
     * @private
     * @param {Object} wrapper The wrapper to clone.
     * @returns {Object} Returns the cloned wrapper.
     */function wrapperClone(wrapper){if(wrapper instanceof LazyWrapper){return wrapper.clone();}var result=new LodashWrapper(wrapper.__wrapped__,wrapper.__chain__);result.__actions__=copyArray(wrapper.__actions__);result.__index__=wrapper.__index__;result.__values__=wrapper.__values__;return result;}/*------------------------------------------------------------------------*/ /**
     * Creates an array of elements split into groups the length of `size`.
     * If `array` can't be split evenly, the final chunk will be the remaining
     * elements.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to process.
     * @param {number} [size=1] The length of each chunk
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Array} Returns the new array of chunks.
     * @example
     *
     * _.chunk(['a', 'b', 'c', 'd'], 2);
     * // => [['a', 'b'], ['c', 'd']]
     *
     * _.chunk(['a', 'b', 'c', 'd'], 3);
     * // => [['a', 'b', 'c'], ['d']]
     */function chunk(array,size,guard){if(guard?isIterateeCall(array,size,guard):size===undefined){size=1;}else{size=nativeMax(toInteger(size),0);}var length=array==null?0:array.length;if(!length||size<1){return[];}var index=0,resIndex=0,result=Array(nativeCeil(length/size));while(index<length){result[resIndex++]=baseSlice(array,index,index+=size);}return result;}/**
     * Creates an array with all falsey values removed. The values `false`, `null`,
     * `0`, `""`, `undefined`, and `NaN` are falsey.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to compact.
     * @returns {Array} Returns the new array of filtered values.
     * @example
     *
     * _.compact([0, 1, false, 2, '', 3]);
     * // => [1, 2, 3]
     */function compact(array){var index=-1,length=array==null?0:array.length,resIndex=0,result=[];while(++index<length){var value=array[index];if(value){result[resIndex++]=value;}}return result;}/**
     * Creates a new array concatenating `array` with any additional arrays
     * and/or values.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to concatenate.
     * @param {...*} [values] The values to concatenate.
     * @returns {Array} Returns the new concatenated array.
     * @example
     *
     * var array = [1];
     * var other = _.concat(array, 2, [3], [[4]]);
     *
     * console.log(other);
     * // => [1, 2, 3, [4]]
     *
     * console.log(array);
     * // => [1]
     */function concat(){var length=arguments.length;if(!length){return[];}var args=Array(length-1),array=arguments[0],index=length;while(index--){args[index-1]=arguments[index];}return arrayPush(isArray(array)?copyArray(array):[array],baseFlatten(args,1));}/**
     * Creates an array of `array` values not included in the other given arrays
     * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons. The order and references of result values are
     * determined by the first array.
     *
     * **Note:** Unlike `_.pullAll`, this method returns a new array.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {...Array} [values] The values to exclude.
     * @returns {Array} Returns the new array of filtered values.
     * @see _.without, _.xor
     * @example
     *
     * _.difference([2, 1], [2, 3]);
     * // => [1]
     */var difference=baseRest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,true)):[];});/**
     * This method is like `_.difference` except that it accepts `iteratee` which
     * is invoked for each element of `array` and `values` to generate the criterion
     * by which they're compared. The order and references of result values are
     * determined by the first array. The iteratee is invoked with one argument:
     * (value).
     *
     * **Note:** Unlike `_.pullAllBy`, this method returns a new array.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {...Array} [values] The values to exclude.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {Array} Returns the new array of filtered values.
     * @example
     *
     * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
     * // => [1.2]
     *
     * // The `_.property` iteratee shorthand.
     * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
     * // => [{ 'x': 2 }]
     */var differenceBy=baseRest(function(array,values){var iteratee=last(values);if(isArrayLikeObject(iteratee)){iteratee=undefined;}return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,true),getIteratee(iteratee,2)):[];});/**
     * This method is like `_.difference` except that it accepts `comparator`
     * which is invoked to compare elements of `array` to `values`. The order and
     * references of result values are determined by the first array. The comparator
     * is invoked with two arguments: (arrVal, othVal).
     *
     * **Note:** Unlike `_.pullAllWith`, this method returns a new array.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {...Array} [values] The values to exclude.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new array of filtered values.
     * @example
     *
     * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
     *
     * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
     * // => [{ 'x': 2, 'y': 1 }]
     */var differenceWith=baseRest(function(array,values){var comparator=last(values);if(isArrayLikeObject(comparator)){comparator=undefined;}return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,true),undefined,comparator):[];});/**
     * Creates a slice of `array` with `n` elements dropped from the beginning.
     *
     * @static
     * @memberOf _
     * @since 0.5.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {number} [n=1] The number of elements to drop.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * _.drop([1, 2, 3]);
     * // => [2, 3]
     *
     * _.drop([1, 2, 3], 2);
     * // => [3]
     *
     * _.drop([1, 2, 3], 5);
     * // => []
     *
     * _.drop([1, 2, 3], 0);
     * // => [1, 2, 3]
     */function drop(array,n,guard){var length=array==null?0:array.length;if(!length){return[];}n=guard||n===undefined?1:toInteger(n);return baseSlice(array,n<0?0:n,length);}/**
     * Creates a slice of `array` with `n` elements dropped from the end.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {number} [n=1] The number of elements to drop.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * _.dropRight([1, 2, 3]);
     * // => [1, 2]
     *
     * _.dropRight([1, 2, 3], 2);
     * // => [1]
     *
     * _.dropRight([1, 2, 3], 5);
     * // => []
     *
     * _.dropRight([1, 2, 3], 0);
     * // => [1, 2, 3]
     */function dropRight(array,n,guard){var length=array==null?0:array.length;if(!length){return[];}n=guard||n===undefined?1:toInteger(n);n=length-n;return baseSlice(array,0,n<0?0:n);}/**
     * Creates a slice of `array` excluding elements dropped from the end.
     * Elements are dropped until `predicate` returns falsey. The predicate is
     * invoked with three arguments: (value, index, array).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'active': true },
     *   { 'user': 'fred',    'active': false },
     *   { 'user': 'pebbles', 'active': false }
     * ];
     *
     * _.dropRightWhile(users, function(o) { return !o.active; });
     * // => objects for ['barney']
     *
     * // The `_.matches` iteratee shorthand.
     * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
     * // => objects for ['barney', 'fred']
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.dropRightWhile(users, ['active', false]);
     * // => objects for ['barney']
     *
     * // The `_.property` iteratee shorthand.
     * _.dropRightWhile(users, 'active');
     * // => objects for ['barney', 'fred', 'pebbles']
     */function dropRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),true,true):[];}/**
     * Creates a slice of `array` excluding elements dropped from the beginning.
     * Elements are dropped until `predicate` returns falsey. The predicate is
     * invoked with three arguments: (value, index, array).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'active': false },
     *   { 'user': 'fred',    'active': false },
     *   { 'user': 'pebbles', 'active': true }
     * ];
     *
     * _.dropWhile(users, function(o) { return !o.active; });
     * // => objects for ['pebbles']
     *
     * // The `_.matches` iteratee shorthand.
     * _.dropWhile(users, { 'user': 'barney', 'active': false });
     * // => objects for ['fred', 'pebbles']
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.dropWhile(users, ['active', false]);
     * // => objects for ['pebbles']
     *
     * // The `_.property` iteratee shorthand.
     * _.dropWhile(users, 'active');
     * // => objects for ['barney', 'fred', 'pebbles']
     */function dropWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),true):[];}/**
     * Fills elements of `array` with `value` from `start` up to, but not
     * including, `end`.
     *
     * **Note:** This method mutates `array`.
     *
     * @static
     * @memberOf _
     * @since 3.2.0
     * @category Array
     * @param {Array} array The array to fill.
     * @param {*} value The value to fill `array` with.
     * @param {number} [start=0] The start position.
     * @param {number} [end=array.length] The end position.
     * @returns {Array} Returns `array`.
     * @example
     *
     * var array = [1, 2, 3];
     *
     * _.fill(array, 'a');
     * console.log(array);
     * // => ['a', 'a', 'a']
     *
     * _.fill(Array(3), 2);
     * // => [2, 2, 2]
     *
     * _.fill([4, 6, 8, 10], '*', 1, 3);
     * // => [4, '*', '*', 10]
     */function fill(array,value,start,end){var length=array==null?0:array.length;if(!length){return[];}if(start&&typeof start!='number'&&isIterateeCall(array,value,start)){start=0;end=length;}return baseFill(array,value,start,end);}/**
     * This method is like `_.find` except that it returns the index of the first
     * element `predicate` returns truthy for instead of the element itself.
     *
     * @static
     * @memberOf _
     * @since 1.1.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @param {number} [fromIndex=0] The index to search from.
     * @returns {number} Returns the index of the found element, else `-1`.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'active': false },
     *   { 'user': 'fred',    'active': false },
     *   { 'user': 'pebbles', 'active': true }
     * ];
     *
     * _.findIndex(users, function(o) { return o.user == 'barney'; });
     * // => 0
     *
     * // The `_.matches` iteratee shorthand.
     * _.findIndex(users, { 'user': 'fred', 'active': false });
     * // => 1
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.findIndex(users, ['active', false]);
     * // => 0
     *
     * // The `_.property` iteratee shorthand.
     * _.findIndex(users, 'active');
     * // => 2
     */function findIndex(array,predicate,fromIndex){var length=array==null?0:array.length;if(!length){return-1;}var index=fromIndex==null?0:toInteger(fromIndex);if(index<0){index=nativeMax(length+index,0);}return baseFindIndex(array,getIteratee(predicate,3),index);}/**
     * This method is like `_.findIndex` except that it iterates over elements
     * of `collection` from right to left.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @param {number} [fromIndex=array.length-1] The index to search from.
     * @returns {number} Returns the index of the found element, else `-1`.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'active': true },
     *   { 'user': 'fred',    'active': false },
     *   { 'user': 'pebbles', 'active': false }
     * ];
     *
     * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
     * // => 2
     *
     * // The `_.matches` iteratee shorthand.
     * _.findLastIndex(users, { 'user': 'barney', 'active': true });
     * // => 0
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.findLastIndex(users, ['active', false]);
     * // => 2
     *
     * // The `_.property` iteratee shorthand.
     * _.findLastIndex(users, 'active');
     * // => 0
     */function findLastIndex(array,predicate,fromIndex){var length=array==null?0:array.length;if(!length){return-1;}var index=length-1;if(fromIndex!==undefined){index=toInteger(fromIndex);index=fromIndex<0?nativeMax(length+index,0):nativeMin(index,length-1);}return baseFindIndex(array,getIteratee(predicate,3),index,true);}/**
     * Flattens `array` a single level deep.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to flatten.
     * @returns {Array} Returns the new flattened array.
     * @example
     *
     * _.flatten([1, [2, [3, [4]], 5]]);
     * // => [1, 2, [3, [4]], 5]
     */function flatten(array){var length=array==null?0:array.length;return length?baseFlatten(array,1):[];}/**
     * Recursively flattens `array`.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to flatten.
     * @returns {Array} Returns the new flattened array.
     * @example
     *
     * _.flattenDeep([1, [2, [3, [4]], 5]]);
     * // => [1, 2, 3, 4, 5]
     */function flattenDeep(array){var length=array==null?0:array.length;return length?baseFlatten(array,INFINITY):[];}/**
     * Recursively flatten `array` up to `depth` times.
     *
     * @static
     * @memberOf _
     * @since 4.4.0
     * @category Array
     * @param {Array} array The array to flatten.
     * @param {number} [depth=1] The maximum recursion depth.
     * @returns {Array} Returns the new flattened array.
     * @example
     *
     * var array = [1, [2, [3, [4]], 5]];
     *
     * _.flattenDepth(array, 1);
     * // => [1, 2, [3, [4]], 5]
     *
     * _.flattenDepth(array, 2);
     * // => [1, 2, 3, [4], 5]
     */function flattenDepth(array,depth){var length=array==null?0:array.length;if(!length){return[];}depth=depth===undefined?1:toInteger(depth);return baseFlatten(array,depth);}/**
     * The inverse of `_.toPairs`; this method returns an object composed
     * from key-value `pairs`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} pairs The key-value pairs.
     * @returns {Object} Returns the new object.
     * @example
     *
     * _.fromPairs([['a', 1], ['b', 2]]);
     * // => { 'a': 1, 'b': 2 }
     */function fromPairs(pairs){var index=-1,length=pairs==null?0:pairs.length,result={};while(++index<length){var pair=pairs[index];result[pair[0]]=pair[1];}return result;}/**
     * Gets the first element of `array`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @alias first
     * @category Array
     * @param {Array} array The array to query.
     * @returns {*} Returns the first element of `array`.
     * @example
     *
     * _.head([1, 2, 3]);
     * // => 1
     *
     * _.head([]);
     * // => undefined
     */function head(array){return array&&array.length?array[0]:undefined;}/**
     * Gets the index at which the first occurrence of `value` is found in `array`
     * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons. If `fromIndex` is negative, it's used as the
     * offset from the end of `array`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {*} value The value to search for.
     * @param {number} [fromIndex=0] The index to search from.
     * @returns {number} Returns the index of the matched value, else `-1`.
     * @example
     *
     * _.indexOf([1, 2, 1, 2], 2);
     * // => 1
     *
     * // Search from the `fromIndex`.
     * _.indexOf([1, 2, 1, 2], 2, 2);
     * // => 3
     */function indexOf(array,value,fromIndex){var length=array==null?0:array.length;if(!length){return-1;}var index=fromIndex==null?0:toInteger(fromIndex);if(index<0){index=nativeMax(length+index,0);}return baseIndexOf(array,value,index);}/**
     * Gets all but the last element of `array`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to query.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * _.initial([1, 2, 3]);
     * // => [1, 2]
     */function initial(array){var length=array==null?0:array.length;return length?baseSlice(array,0,-1):[];}/**
     * Creates an array of unique values that are included in all given arrays
     * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons. The order and references of result values are
     * determined by the first array.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @returns {Array} Returns the new array of intersecting values.
     * @example
     *
     * _.intersection([2, 1], [2, 3]);
     * // => [2]
     */var intersection=baseRest(function(arrays){var mapped=arrayMap(arrays,castArrayLikeObject);return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped):[];});/**
     * This method is like `_.intersection` except that it accepts `iteratee`
     * which is invoked for each element of each `arrays` to generate the criterion
     * by which they're compared. The order and references of result values are
     * determined by the first array. The iteratee is invoked with one argument:
     * (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {Array} Returns the new array of intersecting values.
     * @example
     *
     * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
     * // => [2.1]
     *
     * // The `_.property` iteratee shorthand.
     * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
     * // => [{ 'x': 1 }]
     */var intersectionBy=baseRest(function(arrays){var iteratee=last(arrays),mapped=arrayMap(arrays,castArrayLikeObject);if(iteratee===last(mapped)){iteratee=undefined;}else{mapped.pop();}return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped,getIteratee(iteratee,2)):[];});/**
     * This method is like `_.intersection` except that it accepts `comparator`
     * which is invoked to compare elements of `arrays`. The order and references
     * of result values are determined by the first array. The comparator is
     * invoked with two arguments: (arrVal, othVal).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new array of intersecting values.
     * @example
     *
     * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
     * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
     *
     * _.intersectionWith(objects, others, _.isEqual);
     * // => [{ 'x': 1, 'y': 2 }]
     */var intersectionWith=baseRest(function(arrays){var comparator=last(arrays),mapped=arrayMap(arrays,castArrayLikeObject);comparator=typeof comparator=='function'?comparator:undefined;if(comparator){mapped.pop();}return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped,undefined,comparator):[];});/**
     * Converts all elements in `array` into a string separated by `separator`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to convert.
     * @param {string} [separator=','] The element separator.
     * @returns {string} Returns the joined string.
     * @example
     *
     * _.join(['a', 'b', 'c'], '~');
     * // => 'a~b~c'
     */function join(array,separator){return array==null?'':nativeJoin.call(array,separator);}/**
     * Gets the last element of `array`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to query.
     * @returns {*} Returns the last element of `array`.
     * @example
     *
     * _.last([1, 2, 3]);
     * // => 3
     */function last(array){var length=array==null?0:array.length;return length?array[length-1]:undefined;}/**
     * This method is like `_.indexOf` except that it iterates over elements of
     * `array` from right to left.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {*} value The value to search for.
     * @param {number} [fromIndex=array.length-1] The index to search from.
     * @returns {number} Returns the index of the matched value, else `-1`.
     * @example
     *
     * _.lastIndexOf([1, 2, 1, 2], 2);
     * // => 3
     *
     * // Search from the `fromIndex`.
     * _.lastIndexOf([1, 2, 1, 2], 2, 2);
     * // => 1
     */function lastIndexOf(array,value,fromIndex){var length=array==null?0:array.length;if(!length){return-1;}var index=length;if(fromIndex!==undefined){index=toInteger(fromIndex);index=index<0?nativeMax(length+index,0):nativeMin(index,length-1);}return value===value?strictLastIndexOf(array,value,index):baseFindIndex(array,baseIsNaN,index,true);}/**
     * Gets the element at index `n` of `array`. If `n` is negative, the nth
     * element from the end is returned.
     *
     * @static
     * @memberOf _
     * @since 4.11.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {number} [n=0] The index of the element to return.
     * @returns {*} Returns the nth element of `array`.
     * @example
     *
     * var array = ['a', 'b', 'c', 'd'];
     *
     * _.nth(array, 1);
     * // => 'b'
     *
     * _.nth(array, -2);
     * // => 'c';
     */function nth(array,n){return array&&array.length?baseNth(array,toInteger(n)):undefined;}/**
     * Removes all given values from `array` using
     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons.
     *
     * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
     * to remove elements from an array by predicate.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Array
     * @param {Array} array The array to modify.
     * @param {...*} [values] The values to remove.
     * @returns {Array} Returns `array`.
     * @example
     *
     * var array = ['a', 'b', 'c', 'a', 'b', 'c'];
     *
     * _.pull(array, 'a', 'c');
     * console.log(array);
     * // => ['b', 'b']
     */var pull=baseRest(pullAll);/**
     * This method is like `_.pull` except that it accepts an array of values to remove.
     *
     * **Note:** Unlike `_.difference`, this method mutates `array`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to modify.
     * @param {Array} values The values to remove.
     * @returns {Array} Returns `array`.
     * @example
     *
     * var array = ['a', 'b', 'c', 'a', 'b', 'c'];
     *
     * _.pullAll(array, ['a', 'c']);
     * console.log(array);
     * // => ['b', 'b']
     */function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array;}/**
     * This method is like `_.pullAll` except that it accepts `iteratee` which is
     * invoked for each element of `array` and `values` to generate the criterion
     * by which they're compared. The iteratee is invoked with one argument: (value).
     *
     * **Note:** Unlike `_.differenceBy`, this method mutates `array`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to modify.
     * @param {Array} values The values to remove.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {Array} Returns `array`.
     * @example
     *
     * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
     *
     * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
     * console.log(array);
     * // => [{ 'x': 2 }]
     */function pullAllBy(array,values,iteratee){return array&&array.length&&values&&values.length?basePullAll(array,values,getIteratee(iteratee,2)):array;}/**
     * This method is like `_.pullAll` except that it accepts `comparator` which
     * is invoked to compare elements of `array` to `values`. The comparator is
     * invoked with two arguments: (arrVal, othVal).
     *
     * **Note:** Unlike `_.differenceWith`, this method mutates `array`.
     *
     * @static
     * @memberOf _
     * @since 4.6.0
     * @category Array
     * @param {Array} array The array to modify.
     * @param {Array} values The values to remove.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns `array`.
     * @example
     *
     * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
     *
     * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
     * console.log(array);
     * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
     */function pullAllWith(array,values,comparator){return array&&array.length&&values&&values.length?basePullAll(array,values,undefined,comparator):array;}/**
     * Removes elements from `array` corresponding to `indexes` and returns an
     * array of removed elements.
     *
     * **Note:** Unlike `_.at`, this method mutates `array`.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to modify.
     * @param {...(number|number[])} [indexes] The indexes of elements to remove.
     * @returns {Array} Returns the new array of removed elements.
     * @example
     *
     * var array = ['a', 'b', 'c', 'd'];
     * var pulled = _.pullAt(array, [1, 3]);
     *
     * console.log(array);
     * // => ['a', 'c']
     *
     * console.log(pulled);
     * // => ['b', 'd']
     */var pullAt=flatRest(function(array,indexes){var length=array==null?0:array.length,result=baseAt(array,indexes);basePullAt(array,arrayMap(indexes,function(index){return isIndex(index,length)?+index:index;}).sort(compareAscending));return result;});/**
     * Removes all elements from `array` that `predicate` returns truthy for
     * and returns an array of the removed elements. The predicate is invoked
     * with three arguments: (value, index, array).
     *
     * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
     * to pull elements from an array by value.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Array
     * @param {Array} array The array to modify.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the new array of removed elements.
     * @example
     *
     * var array = [1, 2, 3, 4];
     * var evens = _.remove(array, function(n) {
     *   return n % 2 == 0;
     * });
     *
     * console.log(array);
     * // => [1, 3]
     *
     * console.log(evens);
     * // => [2, 4]
     */function remove(array,predicate){var result=[];if(!(array&&array.length)){return result;}var index=-1,indexes=[],length=array.length;predicate=getIteratee(predicate,3);while(++index<length){var value=array[index];if(predicate(value,index,array)){result.push(value);indexes.push(index);}}basePullAt(array,indexes);return result;}/**
     * Reverses `array` so that the first element becomes the last, the second
     * element becomes the second to last, and so on.
     *
     * **Note:** This method mutates `array` and is based on
     * [`Array#reverse`](https://mdn.io/Array/reverse).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to modify.
     * @returns {Array} Returns `array`.
     * @example
     *
     * var array = [1, 2, 3];
     *
     * _.reverse(array);
     * // => [3, 2, 1]
     *
     * console.log(array);
     * // => [3, 2, 1]
     */function reverse(array){return array==null?array:nativeReverse.call(array);}/**
     * Creates a slice of `array` from `start` up to, but not including, `end`.
     *
     * **Note:** This method is used instead of
     * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
     * returned.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to slice.
     * @param {number} [start=0] The start position.
     * @param {number} [end=array.length] The end position.
     * @returns {Array} Returns the slice of `array`.
     */function slice(array,start,end){var length=array==null?0:array.length;if(!length){return[];}if(end&&typeof end!='number'&&isIterateeCall(array,start,end)){start=0;end=length;}else{start=start==null?0:toInteger(start);end=end===undefined?length:toInteger(end);}return baseSlice(array,start,end);}/**
     * Uses a binary search to determine the lowest index at which `value`
     * should be inserted into `array` in order to maintain its sort order.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The sorted array to inspect.
     * @param {*} value The value to evaluate.
     * @returns {number} Returns the index at which `value` should be inserted
     *  into `array`.
     * @example
     *
     * _.sortedIndex([30, 50], 40);
     * // => 1
     */function sortedIndex(array,value){return baseSortedIndex(array,value);}/**
     * This method is like `_.sortedIndex` except that it accepts `iteratee`
     * which is invoked for `value` and each element of `array` to compute their
     * sort ranking. The iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The sorted array to inspect.
     * @param {*} value The value to evaluate.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {number} Returns the index at which `value` should be inserted
     *  into `array`.
     * @example
     *
     * var objects = [{ 'x': 4 }, { 'x': 5 }];
     *
     * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
     * // => 0
     *
     * // The `_.property` iteratee shorthand.
     * _.sortedIndexBy(objects, { 'x': 4 }, 'x');
     * // => 0
     */function sortedIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2));}/**
     * This method is like `_.indexOf` except that it performs a binary
     * search on a sorted `array`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {*} value The value to search for.
     * @returns {number} Returns the index of the matched value, else `-1`.
     * @example
     *
     * _.sortedIndexOf([4, 5, 5, 5, 6], 5);
     * // => 1
     */function sortedIndexOf(array,value){var length=array==null?0:array.length;if(length){var index=baseSortedIndex(array,value);if(index<length&&eq(array[index],value)){return index;}}return-1;}/**
     * This method is like `_.sortedIndex` except that it returns the highest
     * index at which `value` should be inserted into `array` in order to
     * maintain its sort order.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The sorted array to inspect.
     * @param {*} value The value to evaluate.
     * @returns {number} Returns the index at which `value` should be inserted
     *  into `array`.
     * @example
     *
     * _.sortedLastIndex([4, 5, 5, 5, 6], 5);
     * // => 4
     */function sortedLastIndex(array,value){return baseSortedIndex(array,value,true);}/**
     * This method is like `_.sortedLastIndex` except that it accepts `iteratee`
     * which is invoked for `value` and each element of `array` to compute their
     * sort ranking. The iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The sorted array to inspect.
     * @param {*} value The value to evaluate.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {number} Returns the index at which `value` should be inserted
     *  into `array`.
     * @example
     *
     * var objects = [{ 'x': 4 }, { 'x': 5 }];
     *
     * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
     * // => 1
     *
     * // The `_.property` iteratee shorthand.
     * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');
     * // => 1
     */function sortedLastIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,getIteratee(iteratee,2),true);}/**
     * This method is like `_.lastIndexOf` except that it performs a binary
     * search on a sorted `array`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {*} value The value to search for.
     * @returns {number} Returns the index of the matched value, else `-1`.
     * @example
     *
     * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
     * // => 3
     */function sortedLastIndexOf(array,value){var length=array==null?0:array.length;if(length){var index=baseSortedIndex(array,value,true)-1;if(eq(array[index],value)){return index;}}return-1;}/**
     * This method is like `_.uniq` except that it's designed and optimized
     * for sorted arrays.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @returns {Array} Returns the new duplicate free array.
     * @example
     *
     * _.sortedUniq([1, 1, 2]);
     * // => [1, 2]
     */function sortedUniq(array){return array&&array.length?baseSortedUniq(array):[];}/**
     * This method is like `_.uniqBy` except that it's designed and optimized
     * for sorted arrays.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {Function} [iteratee] The iteratee invoked per element.
     * @returns {Array} Returns the new duplicate free array.
     * @example
     *
     * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
     * // => [1.1, 2.3]
     */function sortedUniqBy(array,iteratee){return array&&array.length?baseSortedUniq(array,getIteratee(iteratee,2)):[];}/**
     * Gets all but the first element of `array`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to query.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * _.tail([1, 2, 3]);
     * // => [2, 3]
     */function tail(array){var length=array==null?0:array.length;return length?baseSlice(array,1,length):[];}/**
     * Creates a slice of `array` with `n` elements taken from the beginning.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {number} [n=1] The number of elements to take.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * _.take([1, 2, 3]);
     * // => [1]
     *
     * _.take([1, 2, 3], 2);
     * // => [1, 2]
     *
     * _.take([1, 2, 3], 5);
     * // => [1, 2, 3]
     *
     * _.take([1, 2, 3], 0);
     * // => []
     */function take(array,n,guard){if(!(array&&array.length)){return[];}n=guard||n===undefined?1:toInteger(n);return baseSlice(array,0,n<0?0:n);}/**
     * Creates a slice of `array` with `n` elements taken from the end.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {number} [n=1] The number of elements to take.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * _.takeRight([1, 2, 3]);
     * // => [3]
     *
     * _.takeRight([1, 2, 3], 2);
     * // => [2, 3]
     *
     * _.takeRight([1, 2, 3], 5);
     * // => [1, 2, 3]
     *
     * _.takeRight([1, 2, 3], 0);
     * // => []
     */function takeRight(array,n,guard){var length=array==null?0:array.length;if(!length){return[];}n=guard||n===undefined?1:toInteger(n);n=length-n;return baseSlice(array,n<0?0:n,length);}/**
     * Creates a slice of `array` with elements taken from the end. Elements are
     * taken until `predicate` returns falsey. The predicate is invoked with
     * three arguments: (value, index, array).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'active': true },
     *   { 'user': 'fred',    'active': false },
     *   { 'user': 'pebbles', 'active': false }
     * ];
     *
     * _.takeRightWhile(users, function(o) { return !o.active; });
     * // => objects for ['fred', 'pebbles']
     *
     * // The `_.matches` iteratee shorthand.
     * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
     * // => objects for ['pebbles']
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.takeRightWhile(users, ['active', false]);
     * // => objects for ['fred', 'pebbles']
     *
     * // The `_.property` iteratee shorthand.
     * _.takeRightWhile(users, 'active');
     * // => []
     */function takeRightWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3),false,true):[];}/**
     * Creates a slice of `array` with elements taken from the beginning. Elements
     * are taken until `predicate` returns falsey. The predicate is invoked with
     * three arguments: (value, index, array).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'active': false },
     *   { 'user': 'fred',    'active': false },
     *   { 'user': 'pebbles', 'active': true }
     * ];
     *
     * _.takeWhile(users, function(o) { return !o.active; });
     * // => objects for ['barney', 'fred']
     *
     * // The `_.matches` iteratee shorthand.
     * _.takeWhile(users, { 'user': 'barney', 'active': false });
     * // => objects for ['barney']
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.takeWhile(users, ['active', false]);
     * // => objects for ['barney', 'fred']
     *
     * // The `_.property` iteratee shorthand.
     * _.takeWhile(users, 'active');
     * // => []
     */function takeWhile(array,predicate){return array&&array.length?baseWhile(array,getIteratee(predicate,3)):[];}/**
     * Creates an array of unique values, in order, from all given arrays using
     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @returns {Array} Returns the new array of combined values.
     * @example
     *
     * _.union([2], [1, 2]);
     * // => [2, 1]
     */var union=baseRest(function(arrays){return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,true));});/**
     * This method is like `_.union` except that it accepts `iteratee` which is
     * invoked for each element of each `arrays` to generate the criterion by
     * which uniqueness is computed. Result values are chosen from the first
     * array in which the value occurs. The iteratee is invoked with one argument:
     * (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {Array} Returns the new array of combined values.
     * @example
     *
     * _.unionBy([2.1], [1.2, 2.3], Math.floor);
     * // => [2.1, 1.2]
     *
     * // The `_.property` iteratee shorthand.
     * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
     * // => [{ 'x': 1 }, { 'x': 2 }]
     */var unionBy=baseRest(function(arrays){var iteratee=last(arrays);if(isArrayLikeObject(iteratee)){iteratee=undefined;}return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,true),getIteratee(iteratee,2));});/**
     * This method is like `_.union` except that it accepts `comparator` which
     * is invoked to compare elements of `arrays`. Result values are chosen from
     * the first array in which the value occurs. The comparator is invoked
     * with two arguments: (arrVal, othVal).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new array of combined values.
     * @example
     *
     * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
     * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
     *
     * _.unionWith(objects, others, _.isEqual);
     * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
     */var unionWith=baseRest(function(arrays){var comparator=last(arrays);comparator=typeof comparator=='function'?comparator:undefined;return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,true),undefined,comparator);});/**
     * Creates a duplicate-free version of an array, using
     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons, in which only the first occurrence of each element
     * is kept. The order of result values is determined by the order they occur
     * in the array.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @returns {Array} Returns the new duplicate free array.
     * @example
     *
     * _.uniq([2, 1, 2]);
     * // => [2, 1]
     */function uniq(array){return array&&array.length?baseUniq(array):[];}/**
     * This method is like `_.uniq` except that it accepts `iteratee` which is
     * invoked for each element in `array` to generate the criterion by which
     * uniqueness is computed. The order of result values is determined by the
     * order they occur in the array. The iteratee is invoked with one argument:
     * (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {Array} Returns the new duplicate free array.
     * @example
     *
     * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
     * // => [2.1, 1.2]
     *
     * // The `_.property` iteratee shorthand.
     * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
     * // => [{ 'x': 1 }, { 'x': 2 }]
     */function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,getIteratee(iteratee,2)):[];}/**
     * This method is like `_.uniq` except that it accepts `comparator` which
     * is invoked to compare elements of `array`. The order of result values is
     * determined by the order they occur in the array.The comparator is invoked
     * with two arguments: (arrVal, othVal).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new duplicate free array.
     * @example
     *
     * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
     *
     * _.uniqWith(objects, _.isEqual);
     * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
     */function uniqWith(array,comparator){comparator=typeof comparator=='function'?comparator:undefined;return array&&array.length?baseUniq(array,undefined,comparator):[];}/**
     * This method is like `_.zip` except that it accepts an array of grouped
     * elements and creates an array regrouping the elements to their pre-zip
     * configuration.
     *
     * @static
     * @memberOf _
     * @since 1.2.0
     * @category Array
     * @param {Array} array The array of grouped elements to process.
     * @returns {Array} Returns the new array of regrouped elements.
     * @example
     *
     * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
     * // => [['a', 1, true], ['b', 2, false]]
     *
     * _.unzip(zipped);
     * // => [['a', 'b'], [1, 2], [true, false]]
     */function unzip(array){if(!(array&&array.length)){return[];}var length=0;array=arrayFilter(array,function(group){if(isArrayLikeObject(group)){length=nativeMax(group.length,length);return true;}});return baseTimes(length,function(index){return arrayMap(array,baseProperty(index));});}/**
     * This method is like `_.unzip` except that it accepts `iteratee` to specify
     * how regrouped values should be combined. The iteratee is invoked with the
     * elements of each group: (...group).
     *
     * @static
     * @memberOf _
     * @since 3.8.0
     * @category Array
     * @param {Array} array The array of grouped elements to process.
     * @param {Function} [iteratee=_.identity] The function to combine
     *  regrouped values.
     * @returns {Array} Returns the new array of regrouped elements.
     * @example
     *
     * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
     * // => [[1, 10, 100], [2, 20, 200]]
     *
     * _.unzipWith(zipped, _.add);
     * // => [3, 30, 300]
     */function unzipWith(array,iteratee){if(!(array&&array.length)){return[];}var result=unzip(array);if(iteratee==null){return result;}return arrayMap(result,function(group){return apply(iteratee,undefined,group);});}/**
     * Creates an array excluding all given values using
     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons.
     *
     * **Note:** Unlike `_.pull`, this method returns a new array.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {...*} [values] The values to exclude.
     * @returns {Array} Returns the new array of filtered values.
     * @see _.difference, _.xor
     * @example
     *
     * _.without([2, 1, 2, 3], 1, 2);
     * // => [3]
     */var without=baseRest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,values):[];});/**
     * Creates an array of unique values that is the
     * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
     * of the given arrays. The order of result values is determined by the order
     * they occur in the arrays.
     *
     * @static
     * @memberOf _
     * @since 2.4.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @returns {Array} Returns the new array of filtered values.
     * @see _.difference, _.without
     * @example
     *
     * _.xor([2, 1], [2, 3]);
     * // => [1, 3]
     */var xor=baseRest(function(arrays){return baseXor(arrayFilter(arrays,isArrayLikeObject));});/**
     * This method is like `_.xor` except that it accepts `iteratee` which is
     * invoked for each element of each `arrays` to generate the criterion by
     * which by which they're compared. The order of result values is determined
     * by the order they occur in the arrays. The iteratee is invoked with one
     * argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {Array} Returns the new array of filtered values.
     * @example
     *
     * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
     * // => [1.2, 3.4]
     *
     * // The `_.property` iteratee shorthand.
     * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
     * // => [{ 'x': 2 }]
     */var xorBy=baseRest(function(arrays){var iteratee=last(arrays);if(isArrayLikeObject(iteratee)){iteratee=undefined;}return baseXor(arrayFilter(arrays,isArrayLikeObject),getIteratee(iteratee,2));});/**
     * This method is like `_.xor` except that it accepts `comparator` which is
     * invoked to compare elements of `arrays`. The order of result values is
     * determined by the order they occur in the arrays. The comparator is invoked
     * with two arguments: (arrVal, othVal).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new array of filtered values.
     * @example
     *
     * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
     * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
     *
     * _.xorWith(objects, others, _.isEqual);
     * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
     */var xorWith=baseRest(function(arrays){var comparator=last(arrays);comparator=typeof comparator=='function'?comparator:undefined;return baseXor(arrayFilter(arrays,isArrayLikeObject),undefined,comparator);});/**
     * Creates an array of grouped elements, the first of which contains the
     * first elements of the given arrays, the second of which contains the
     * second elements of the given arrays, and so on.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {...Array} [arrays] The arrays to process.
     * @returns {Array} Returns the new array of grouped elements.
     * @example
     *
     * _.zip(['a', 'b'], [1, 2], [true, false]);
     * // => [['a', 1, true], ['b', 2, false]]
     */var zip=baseRest(unzip);/**
     * This method is like `_.fromPairs` except that it accepts two arrays,
     * one of property identifiers and one of corresponding values.
     *
     * @static
     * @memberOf _
     * @since 0.4.0
     * @category Array
     * @param {Array} [props=[]] The property identifiers.
     * @param {Array} [values=[]] The property values.
     * @returns {Object} Returns the new object.
     * @example
     *
     * _.zipObject(['a', 'b'], [1, 2]);
     * // => { 'a': 1, 'b': 2 }
     */function zipObject(props,values){return baseZipObject(props||[],values||[],assignValue);}/**
     * This method is like `_.zipObject` except that it supports property paths.
     *
     * @static
     * @memberOf _
     * @since 4.1.0
     * @category Array
     * @param {Array} [props=[]] The property identifiers.
     * @param {Array} [values=[]] The property values.
     * @returns {Object} Returns the new object.
     * @example
     *
     * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
     * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
     */function zipObjectDeep(props,values){return baseZipObject(props||[],values||[],baseSet);}/**
     * This method is like `_.zip` except that it accepts `iteratee` to specify
     * how grouped values should be combined. The iteratee is invoked with the
     * elements of each group: (...group).
     *
     * @static
     * @memberOf _
     * @since 3.8.0
     * @category Array
     * @param {...Array} [arrays] The arrays to process.
     * @param {Function} [iteratee=_.identity] The function to combine
     *  grouped values.
     * @returns {Array} Returns the new array of grouped elements.
     * @example
     *
     * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
     *   return a + b + c;
     * });
     * // => [111, 222]
     */var zipWith=baseRest(function(arrays){var length=arrays.length,iteratee=length>1?arrays[length-1]:undefined;iteratee=typeof iteratee=='function'?(arrays.pop(),iteratee):undefined;return unzipWith(arrays,iteratee);});/*------------------------------------------------------------------------*/ /**
     * Creates a `lodash` wrapper instance that wraps `value` with explicit method
     * chain sequences enabled. The result of such sequences must be unwrapped
     * with `_#value`.
     *
     * @static
     * @memberOf _
     * @since 1.3.0
     * @category Seq
     * @param {*} value The value to wrap.
     * @returns {Object} Returns the new `lodash` wrapper instance.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'age': 36 },
     *   { 'user': 'fred',    'age': 40 },
     *   { 'user': 'pebbles', 'age': 1 }
     * ];
     *
     * var youngest = _
     *   .chain(users)
     *   .sortBy('age')
     *   .map(function(o) {
     *     return o.user + ' is ' + o.age;
     *   })
     *   .head()
     *   .value();
     * // => 'pebbles is 1'
     */function chain(value){var result=lodash(value);result.__chain__=true;return result;}/**
     * This method invokes `interceptor` and returns `value`. The interceptor
     * is invoked with one argument; (value). The purpose of this method is to
     * "tap into" a method chain sequence in order to modify intermediate results.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Seq
     * @param {*} value The value to provide to `interceptor`.
     * @param {Function} interceptor The function to invoke.
     * @returns {*} Returns `value`.
     * @example
     *
     * _([1, 2, 3])
     *  .tap(function(array) {
     *    // Mutate input array.
     *    array.pop();
     *  })
     *  .reverse()
     *  .value();
     * // => [2, 1]
     */function tap(value,interceptor){interceptor(value);return value;}/**
     * This method is like `_.tap` except that it returns the result of `interceptor`.
     * The purpose of this method is to "pass thru" values replacing intermediate
     * results in a method chain sequence.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Seq
     * @param {*} value The value to provide to `interceptor`.
     * @param {Function} interceptor The function to invoke.
     * @returns {*} Returns the result of `interceptor`.
     * @example
     *
     * _('  abc  ')
     *  .chain()
     *  .trim()
     *  .thru(function(value) {
     *    return [value];
     *  })
     *  .value();
     * // => ['abc']
     */function thru(value,interceptor){return interceptor(value);}/**
     * This method is the wrapper version of `_.at`.
     *
     * @name at
     * @memberOf _
     * @since 1.0.0
     * @category Seq
     * @param {...(string|string[])} [paths] The property paths to pick.
     * @returns {Object} Returns the new `lodash` wrapper instance.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
     *
     * _(object).at(['a[0].b.c', 'a[1]']).value();
     * // => [3, 4]
     */var wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths);};if(length>1||this.__actions__.length||!(value instanceof LazyWrapper)||!isIndex(start)){return this.thru(interceptor);}value=value.slice(start,+start+(length?1:0));value.__actions__.push({'func':thru,'args':[interceptor],'thisArg':undefined});return new LodashWrapper(value,this.__chain__).thru(function(array){if(length&&!array.length){array.push(undefined);}return array;});});/**
     * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
     *
     * @name chain
     * @memberOf _
     * @since 0.1.0
     * @category Seq
     * @returns {Object} Returns the new `lodash` wrapper instance.
     * @example
     *
     * var users = [
     *   { 'user': 'barney', 'age': 36 },
     *   { 'user': 'fred',   'age': 40 }
     * ];
     *
     * // A sequence without explicit chaining.
     * _(users).head();
     * // => { 'user': 'barney', 'age': 36 }
     *
     * // A sequence with explicit chaining.
     * _(users)
     *   .chain()
     *   .head()
     *   .pick('user')
     *   .value();
     * // => { 'user': 'barney' }
     */function wrapperChain(){return chain(this);}/**
     * Executes the chain sequence and returns the wrapped result.
     *
     * @name commit
     * @memberOf _
     * @since 3.2.0
     * @category Seq
     * @returns {Object} Returns the new `lodash` wrapper instance.
     * @example
     *
     * var array = [1, 2];
     * var wrapped = _(array).push(3);
     *
     * console.log(array);
     * // => [1, 2]
     *
     * wrapped = wrapped.commit();
     * console.log(array);
     * // => [1, 2, 3]
     *
     * wrapped.last();
     * // => 3
     *
     * console.log(array);
     * // => [1, 2, 3]
     */function wrapperCommit(){return new LodashWrapper(this.value(),this.__chain__);}/**
     * Gets the next value on a wrapped object following the
     * [iterator protocol](https://mdn.io/iteration_protocols#iterator).
     *
     * @name next
     * @memberOf _
     * @since 4.0.0
     * @category Seq
     * @returns {Object} Returns the next iterator value.
     * @example
     *
     * var wrapped = _([1, 2]);
     *
     * wrapped.next();
     * // => { 'done': false, 'value': 1 }
     *
     * wrapped.next();
     * // => { 'done': false, 'value': 2 }
     *
     * wrapped.next();
     * // => { 'done': true, 'value': undefined }
     */function wrapperNext(){if(this.__values__===undefined){this.__values__=toArray(this.value());}var done=this.__index__>=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{'done':done,'value':value};}/**
     * Enables the wrapper to be iterable.
     *
     * @name Symbol.iterator
     * @memberOf _
     * @since 4.0.0
     * @category Seq
     * @returns {Object} Returns the wrapper object.
     * @example
     *
     * var wrapped = _([1, 2]);
     *
     * wrapped[Symbol.iterator]() === wrapped;
     * // => true
     *
     * Array.from(wrapped);
     * // => [1, 2]
     */function wrapperToIterator(){return this;}/**
     * Creates a clone of the chain sequence planting `value` as the wrapped value.
     *
     * @name plant
     * @memberOf _
     * @since 3.2.0
     * @category Seq
     * @param {*} value The value to plant.
     * @returns {Object} Returns the new `lodash` wrapper instance.
     * @example
     *
     * function square(n) {
     *   return n * n;
     * }
     *
     * var wrapped = _([1, 2]).map(square);
     * var other = wrapped.plant([3, 4]);
     *
     * other.value();
     * // => [9, 16]
     *
     * wrapped.value();
     * // => [1, 4]
     */function wrapperPlant(value){var result,parent=this;while(parent instanceof baseLodash){var clone=wrapperClone(parent);clone.__index__=0;clone.__values__=undefined;if(result){previous.__wrapped__=clone;}else{result=clone;}var previous=clone;parent=parent.__wrapped__;}previous.__wrapped__=value;return result;}/**
     * This method is the wrapper version of `_.reverse`.
     *
     * **Note:** This method mutates the wrapped array.
     *
     * @name reverse
     * @memberOf _
     * @since 0.1.0
     * @category Seq
     * @returns {Object} Returns the new `lodash` wrapper instance.
     * @example
     *
     * var array = [1, 2, 3];
     *
     * _(array).reverse().value()
     * // => [3, 2, 1]
     *
     * console.log(array);
     * // => [3, 2, 1]
     */function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;if(this.__actions__.length){wrapped=new LazyWrapper(this);}wrapped=wrapped.reverse();wrapped.__actions__.push({'func':thru,'args':[reverse],'thisArg':undefined});return new LodashWrapper(wrapped,this.__chain__);}return this.thru(reverse);}/**
     * Executes the chain sequence to resolve the unwrapped value.
     *
     * @name value
     * @memberOf _
     * @since 0.1.0
     * @alias toJSON, valueOf
     * @category Seq
     * @returns {*} Returns the resolved unwrapped value.
     * @example
     *
     * _([1, 2, 3]).value();
     * // => [1, 2, 3]
     */function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__);}/*------------------------------------------------------------------------*/ /**
     * Creates an object composed of keys generated from the results of running
     * each element of `collection` thru `iteratee`. The corresponding value of
     * each key is the number of times the key was returned by `iteratee`. The
     * iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 0.5.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
     * @returns {Object} Returns the composed aggregate object.
     * @example
     *
     * _.countBy([6.1, 4.2, 6.3], Math.floor);
     * // => { '4': 1, '6': 2 }
     *
     * // The `_.property` iteratee shorthand.
     * _.countBy(['one', 'two', 'three'], 'length');
     * // => { '3': 2, '5': 1 }
     */var countBy=createAggregator(function(result,value,key){if(hasOwnProperty.call(result,key)){++result[key];}else{baseAssignValue(result,key,1);}});/**
     * Checks if `predicate` returns truthy for **all** elements of `collection`.
     * Iteration is stopped once `predicate` returns falsey. The predicate is
     * invoked with three arguments: (value, index|key, collection).
     *
     * **Note:** This method returns `true` for
     * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
     * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
     * elements of empty collections.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {boolean} Returns `true` if all elements pass the predicate check,
     *  else `false`.
     * @example
     *
     * _.every([true, 1, null, 'yes'], Boolean);
     * // => false
     *
     * var users = [
     *   { 'user': 'barney', 'age': 36, 'active': false },
     *   { 'user': 'fred',   'age': 40, 'active': false }
     * ];
     *
     * // The `_.matches` iteratee shorthand.
     * _.every(users, { 'user': 'barney', 'active': false });
     * // => false
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.every(users, ['active', false]);
     * // => true
     *
     * // The `_.property` iteratee shorthand.
     * _.every(users, 'active');
     * // => false
     */function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;if(guard&&isIterateeCall(collection,predicate,guard)){predicate=undefined;}return func(collection,getIteratee(predicate,3));}/**
     * Iterates over elements of `collection`, returning an array of all elements
     * `predicate` returns truthy for. The predicate is invoked with three
     * arguments: (value, index|key, collection).
     *
     * **Note:** Unlike `_.remove`, this method returns a new array.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the new filtered array.
     * @see _.reject
     * @example
     *
     * var users = [
     *   { 'user': 'barney', 'age': 36, 'active': true },
     *   { 'user': 'fred',   'age': 40, 'active': false }
     * ];
     *
     * _.filter(users, function(o) { return !o.active; });
     * // => objects for ['fred']
     *
     * // The `_.matches` iteratee shorthand.
     * _.filter(users, { 'age': 36, 'active': true });
     * // => objects for ['barney']
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.filter(users, ['active', false]);
     * // => objects for ['fred']
     *
     * // The `_.property` iteratee shorthand.
     * _.filter(users, 'active');
     * // => objects for ['barney']
     *
     * // Combining several predicates using `_.overEvery` or `_.overSome`.
     * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
     * // => objects for ['fred', 'barney']
     */function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3));}/**
     * Iterates over elements of `collection`, returning the first element
     * `predicate` returns truthy for. The predicate is invoked with three
     * arguments: (value, index|key, collection).
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to inspect.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @param {number} [fromIndex=0] The index to search from.
     * @returns {*} Returns the matched element, else `undefined`.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'age': 36, 'active': true },
     *   { 'user': 'fred',    'age': 40, 'active': false },
     *   { 'user': 'pebbles', 'age': 1,  'active': true }
     * ];
     *
     * _.find(users, function(o) { return o.age < 40; });
     * // => object for 'barney'
     *
     * // The `_.matches` iteratee shorthand.
     * _.find(users, { 'age': 1, 'active': true });
     * // => object for 'pebbles'
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.find(users, ['active', false]);
     * // => object for 'fred'
     *
     * // The `_.property` iteratee shorthand.
     * _.find(users, 'active');
     * // => object for 'barney'
     */var find=createFind(findIndex);/**
     * This method is like `_.find` except that it iterates over elements of
     * `collection` from right to left.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to inspect.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @param {number} [fromIndex=collection.length-1] The index to search from.
     * @returns {*} Returns the matched element, else `undefined`.
     * @example
     *
     * _.findLast([1, 2, 3, 4], function(n) {
     *   return n % 2 == 1;
     * });
     * // => 3
     */var findLast=createFind(findLastIndex);/**
     * Creates a flattened array of values by running each element in `collection`
     * thru `iteratee` and flattening the mapped results. The iteratee is invoked
     * with three arguments: (value, index|key, collection).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the new flattened array.
     * @example
     *
     * function duplicate(n) {
     *   return [n, n];
     * }
     *
     * _.flatMap([1, 2], duplicate);
     * // => [1, 1, 2, 2]
     */function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1);}/**
     * This method is like `_.flatMap` except that it recursively flattens the
     * mapped results.
     *
     * @static
     * @memberOf _
     * @since 4.7.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the new flattened array.
     * @example
     *
     * function duplicate(n) {
     *   return [[[n, n]]];
     * }
     *
     * _.flatMapDeep([1, 2], duplicate);
     * // => [1, 1, 2, 2]
     */function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY);}/**
     * This method is like `_.flatMap` except that it recursively flattens the
     * mapped results up to `depth` times.
     *
     * @static
     * @memberOf _
     * @since 4.7.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @param {number} [depth=1] The maximum recursion depth.
     * @returns {Array} Returns the new flattened array.
     * @example
     *
     * function duplicate(n) {
     *   return [[[n, n]]];
     * }
     *
     * _.flatMapDepth([1, 2], duplicate, 2);
     * // => [[1, 1], [2, 2]]
     */function flatMapDepth(collection,iteratee,depth){depth=depth===undefined?1:toInteger(depth);return baseFlatten(map(collection,iteratee),depth);}/**
     * Iterates over elements of `collection` and invokes `iteratee` for each element.
     * The iteratee is invoked with three arguments: (value, index|key, collection).
     * Iteratee functions may exit iteration early by explicitly returning `false`.
     *
     * **Note:** As with other "Collections" methods, objects with a "length"
     * property are iterated like arrays. To avoid this behavior use `_.forIn`
     * or `_.forOwn` for object iteration.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @alias each
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Array|Object} Returns `collection`.
     * @see _.forEachRight
     * @example
     *
     * _.forEach([1, 2], function(value) {
     *   console.log(value);
     * });
     * // => Logs `1` then `2`.
     *
     * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
     *   console.log(key);
     * });
     * // => Logs 'a' then 'b' (iteration order is not guaranteed).
     */function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3));}/**
     * This method is like `_.forEach` except that it iterates over elements of
     * `collection` from right to left.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @alias eachRight
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Array|Object} Returns `collection`.
     * @see _.forEach
     * @example
     *
     * _.forEachRight([1, 2], function(value) {
     *   console.log(value);
     * });
     * // => Logs `2` then `1`.
     */function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3));}/**
     * Creates an object composed of keys generated from the results of running
     * each element of `collection` thru `iteratee`. The order of grouped values
     * is determined by the order they occur in `collection`. The corresponding
     * value of each key is an array of elements responsible for generating the
     * key. The iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
     * @returns {Object} Returns the composed aggregate object.
     * @example
     *
     * _.groupBy([6.1, 4.2, 6.3], Math.floor);
     * // => { '4': [4.2], '6': [6.1, 6.3] }
     *
     * // The `_.property` iteratee shorthand.
     * _.groupBy(['one', 'two', 'three'], 'length');
     * // => { '3': ['one', 'two'], '5': ['three'] }
     */var groupBy=createAggregator(function(result,value,key){if(hasOwnProperty.call(result,key)){result[key].push(value);}else{baseAssignValue(result,key,[value]);}});/**
     * Checks if `value` is in `collection`. If `collection` is a string, it's
     * checked for a substring of `value`, otherwise
     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * is used for equality comparisons. If `fromIndex` is negative, it's used as
     * the offset from the end of `collection`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object|string} collection The collection to inspect.
     * @param {*} value The value to search for.
     * @param {number} [fromIndex=0] The index to search from.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
     * @returns {boolean} Returns `true` if `value` is found, else `false`.
     * @example
     *
     * _.includes([1, 2, 3], 1);
     * // => true
     *
     * _.includes([1, 2, 3], 1, 2);
     * // => false
     *
     * _.includes({ 'a': 1, 'b': 2 }, 1);
     * // => true
     *
     * _.includes('abcd', 'bc');
     * // => true
     */function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection);fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;if(fromIndex<0){fromIndex=nativeMax(length+fromIndex,0);}return isString(collection)?fromIndex<=length&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1;}/**
     * Invokes the method at `path` of each element in `collection`, returning
     * an array of the results of each invoked method. Any additional arguments
     * are provided to each invoked method. If `path` is a function, it's invoked
     * for, and `this` bound to, each element in `collection`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Array|Function|string} path The path of the method to invoke or
     *  the function invoked per iteration.
     * @param {...*} [args] The arguments to invoke each method with.
     * @returns {Array} Returns the array of results.
     * @example
     *
     * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
     * // => [[1, 5, 7], [1, 2, 3]]
     *
     * _.invokeMap([123, 456], String.prototype.split, '');
     * // => [['1', '2', '3'], ['4', '5', '6']]
     */var invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc=typeof path=='function',result=isArrayLike(collection)?Array(collection.length):[];baseEach(collection,function(value){result[++index]=isFunc?apply(path,value,args):baseInvoke(value,path,args);});return result;});/**
     * Creates an object composed of keys generated from the results of running
     * each element of `collection` thru `iteratee`. The corresponding value of
     * each key is the last element responsible for generating the key. The
     * iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
     * @returns {Object} Returns the composed aggregate object.
     * @example
     *
     * var array = [
     *   { 'dir': 'left', 'code': 97 },
     *   { 'dir': 'right', 'code': 100 }
     * ];
     *
     * _.keyBy(array, function(o) {
     *   return String.fromCharCode(o.code);
     * });
     * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
     *
     * _.keyBy(array, 'dir');
     * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
     */var keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value);});/**
     * Creates an array of values by running each element in `collection` thru
     * `iteratee`. The iteratee is invoked with three arguments:
     * (value, index|key, collection).
     *
     * Many lodash methods are guarded to work as iteratees for methods like
     * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
     *
     * The guarded methods are:
     * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
     * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
     * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
     * `template`, `trim`, `trimEnd`, `trimStart`, and `words`
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the new mapped array.
     * @example
     *
     * function square(n) {
     *   return n * n;
     * }
     *
     * _.map([4, 8], square);
     * // => [16, 64]
     *
     * _.map({ 'a': 4, 'b': 8 }, square);
     * // => [16, 64] (iteration order is not guaranteed)
     *
     * var users = [
     *   { 'user': 'barney' },
     *   { 'user': 'fred' }
     * ];
     *
     * // The `_.property` iteratee shorthand.
     * _.map(users, 'user');
     * // => ['barney', 'fred']
     */function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3));}/**
     * This method is like `_.sortBy` except that it allows specifying the sort
     * orders of the iteratees to sort by. If `orders` is unspecified, all values
     * are sorted in ascending order. Otherwise, specify an order of "desc" for
     * descending or "asc" for ascending sort order of corresponding values.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
     *  The iteratees to sort by.
     * @param {string[]} [orders] The sort orders of `iteratees`.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
     * @returns {Array} Returns the new sorted array.
     * @example
     *
     * var users = [
     *   { 'user': 'fred',   'age': 48 },
     *   { 'user': 'barney', 'age': 34 },
     *   { 'user': 'fred',   'age': 40 },
     *   { 'user': 'barney', 'age': 36 }
     * ];
     *
     * // Sort by `user` in ascending order and by `age` in descending order.
     * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
     * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
     */function orderBy(collection,iteratees,orders,guard){if(collection==null){return[];}if(!isArray(iteratees)){iteratees=iteratees==null?[]:[iteratees];}orders=guard?undefined:orders;if(!isArray(orders)){orders=orders==null?[]:[orders];}return baseOrderBy(collection,iteratees,orders);}/**
     * Creates an array of elements split into two groups, the first of which
     * contains elements `predicate` returns truthy for, the second of which
     * contains elements `predicate` returns falsey for. The predicate is
     * invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the array of grouped elements.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'age': 36, 'active': false },
     *   { 'user': 'fred',    'age': 40, 'active': true },
     *   { 'user': 'pebbles', 'age': 1,  'active': false }
     * ];
     *
     * _.partition(users, function(o) { return o.active; });
     * // => objects for [['fred'], ['barney', 'pebbles']]
     *
     * // The `_.matches` iteratee shorthand.
     * _.partition(users, { 'age': 1, 'active': false });
     * // => objects for [['pebbles'], ['barney', 'fred']]
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.partition(users, ['active', false]);
     * // => objects for [['barney', 'pebbles'], ['fred']]
     *
     * // The `_.property` iteratee shorthand.
     * _.partition(users, 'active');
     * // => objects for [['fred'], ['barney', 'pebbles']]
     */var partition=createAggregator(function(result,value,key){result[key?0:1].push(value);},function(){return[[],[]];});/**
     * Reduces `collection` to a value which is the accumulated result of running
     * each element in `collection` thru `iteratee`, where each successive
     * invocation is supplied the return value of the previous. If `accumulator`
     * is not given, the first element of `collection` is used as the initial
     * value. The iteratee is invoked with four arguments:
     * (accumulator, value, index|key, collection).
     *
     * Many lodash methods are guarded to work as iteratees for methods like
     * `_.reduce`, `_.reduceRight`, and `_.transform`.
     *
     * The guarded methods are:
     * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
     * and `sortBy`
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @param {*} [accumulator] The initial value.
     * @returns {*} Returns the accumulated value.
     * @see _.reduceRight
     * @example
     *
     * _.reduce([1, 2], function(sum, n) {
     *   return sum + n;
     * }, 0);
     * // => 3
     *
     * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
     *   (result[value] || (result[value] = [])).push(key);
     *   return result;
     * }, {});
     * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
     */function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach);}/**
     * This method is like `_.reduce` except that it iterates over elements of
     * `collection` from right to left.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @param {*} [accumulator] The initial value.
     * @returns {*} Returns the accumulated value.
     * @see _.reduce
     * @example
     *
     * var array = [[0, 1], [2, 3], [4, 5]];
     *
     * _.reduceRight(array, function(flattened, other) {
     *   return flattened.concat(other);
     * }, []);
     * // => [4, 5, 2, 3, 0, 1]
     */function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight);}/**
     * The opposite of `_.filter`; this method returns the elements of `collection`
     * that `predicate` does **not** return truthy for.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the new filtered array.
     * @see _.filter
     * @example
     *
     * var users = [
     *   { 'user': 'barney', 'age': 36, 'active': false },
     *   { 'user': 'fred',   'age': 40, 'active': true }
     * ];
     *
     * _.reject(users, function(o) { return !o.active; });
     * // => objects for ['fred']
     *
     * // The `_.matches` iteratee shorthand.
     * _.reject(users, { 'age': 40, 'active': true });
     * // => objects for ['barney']
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.reject(users, ['active', false]);
     * // => objects for ['fred']
     *
     * // The `_.property` iteratee shorthand.
     * _.reject(users, 'active');
     * // => objects for ['barney']
     */function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,negate(getIteratee(predicate,3)));}/**
     * Gets a random element from `collection`.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to sample.
     * @returns {*} Returns the random element.
     * @example
     *
     * _.sample([1, 2, 3, 4]);
     * // => 2
     */function sample(collection){var func=isArray(collection)?arraySample:baseSample;return func(collection);}/**
     * Gets `n` random elements at unique keys from `collection` up to the
     * size of `collection`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to sample.
     * @param {number} [n=1] The number of elements to sample.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Array} Returns the random elements.
     * @example
     *
     * _.sampleSize([1, 2, 3], 2);
     * // => [3, 1]
     *
     * _.sampleSize([1, 2, 3], 4);
     * // => [2, 3, 1]
     */function sampleSize(collection,n,guard){if(guard?isIterateeCall(collection,n,guard):n===undefined){n=1;}else{n=toInteger(n);}var func=isArray(collection)?arraySampleSize:baseSampleSize;return func(collection,n);}/**
     * Creates an array of shuffled values, using a version of the
     * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to shuffle.
     * @returns {Array} Returns the new shuffled array.
     * @example
     *
     * _.shuffle([1, 2, 3, 4]);
     * // => [4, 1, 3, 2]
     */function shuffle(collection){var func=isArray(collection)?arrayShuffle:baseShuffle;return func(collection);}/**
     * Gets the size of `collection` by returning its length for array-like
     * values or the number of own enumerable string keyed properties for objects.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object|string} collection The collection to inspect.
     * @returns {number} Returns the collection size.
     * @example
     *
     * _.size([1, 2, 3]);
     * // => 3
     *
     * _.size({ 'a': 1, 'b': 2 });
     * // => 2
     *
     * _.size('pebbles');
     * // => 7
     */function size(collection){if(collection==null){return 0;}if(isArrayLike(collection)){return isString(collection)?stringSize(collection):collection.length;}var tag=getTag(collection);if(tag==mapTag||tag==setTag){return collection.size;}return baseKeys(collection).length;}/**
     * Checks if `predicate` returns truthy for **any** element of `collection`.
     * Iteration is stopped once `predicate` returns truthy. The predicate is
     * invoked with three arguments: (value, index|key, collection).
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {boolean} Returns `true` if any element passes the predicate check,
     *  else `false`.
     * @example
     *
     * _.some([null, 0, 'yes', false], Boolean);
     * // => true
     *
     * var users = [
     *   { 'user': 'barney', 'active': true },
     *   { 'user': 'fred',   'active': false }
     * ];
     *
     * // The `_.matches` iteratee shorthand.
     * _.some(users, { 'user': 'barney', 'active': false });
     * // => false
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.some(users, ['active', false]);
     * // => true
     *
     * // The `_.property` iteratee shorthand.
     * _.some(users, 'active');
     * // => true
     */function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;if(guard&&isIterateeCall(collection,predicate,guard)){predicate=undefined;}return func(collection,getIteratee(predicate,3));}/**
     * Creates an array of elements, sorted in ascending order by the results of
     * running each element in a collection thru each iteratee. This method
     * performs a stable sort, that is, it preserves the original sort order of
     * equal elements. The iteratees are invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {...(Function|Function[])} [iteratees=[_.identity]]
     *  The iteratees to sort by.
     * @returns {Array} Returns the new sorted array.
     * @example
     *
     * var users = [
     *   { 'user': 'fred',   'age': 48 },
     *   { 'user': 'barney', 'age': 36 },
     *   { 'user': 'fred',   'age': 30 },
     *   { 'user': 'barney', 'age': 34 }
     * ];
     *
     * _.sortBy(users, [function(o) { return o.user; }]);
     * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
     *
     * _.sortBy(users, ['user', 'age']);
     * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
     */var sortBy=baseRest(function(collection,iteratees){if(collection==null){return[];}var length=iteratees.length;if(length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])){iteratees=[];}else if(length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])){iteratees=[iteratees[0]];}return baseOrderBy(collection,baseFlatten(iteratees,1),[]);});/*------------------------------------------------------------------------*/ /**
     * Gets the timestamp of the number of milliseconds that have elapsed since
     * the Unix epoch (1 January 1970 00:00:00 UTC).
     *
     * @static
     * @memberOf _
     * @since 2.4.0
     * @category Date
     * @returns {number} Returns the timestamp.
     * @example
     *
     * _.defer(function(stamp) {
     *   console.log(_.now() - stamp);
     * }, _.now());
     * // => Logs the number of milliseconds it took for the deferred invocation.
     */var now=ctxNow||function(){return root.Date.now();};/*------------------------------------------------------------------------*/ /**
     * The opposite of `_.before`; this method creates a function that invokes
     * `func` once it's called `n` or more times.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {number} n The number of calls before `func` is invoked.
     * @param {Function} func The function to restrict.
     * @returns {Function} Returns the new restricted function.
     * @example
     *
     * var saves = ['profile', 'settings'];
     *
     * var done = _.after(saves.length, function() {
     *   console.log('done saving!');
     * });
     *
     * _.forEach(saves, function(type) {
     *   asyncSave({ 'type': type, 'complete': done });
     * });
     * // => Logs 'done saving!' after the two async saves have completed.
     */function after(n,func){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}n=toInteger(n);return function(){if(--n<1){return func.apply(this,arguments);}};}/**
     * Creates a function that invokes `func`, with up to `n` arguments,
     * ignoring any additional arguments.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Function
     * @param {Function} func The function to cap arguments for.
     * @param {number} [n=func.length] The arity cap.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Function} Returns the new capped function.
     * @example
     *
     * _.map(['6', '8', '10'], _.ary(parseInt, 1));
     * // => [6, 8, 10]
     */function ary(func,n,guard){n=guard?undefined:n;n=func&&n==null?func.length:n;return createWrap(func,WRAP_ARY_FLAG,undefined,undefined,undefined,undefined,n);}/**
     * Creates a function that invokes `func`, with the `this` binding and arguments
     * of the created function, while it's called less than `n` times. Subsequent
     * calls to the created function return the result of the last `func` invocation.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Function
     * @param {number} n The number of calls at which `func` is no longer invoked.
     * @param {Function} func The function to restrict.
     * @returns {Function} Returns the new restricted function.
     * @example
     *
     * jQuery(element).on('click', _.before(5, addContactToList));
     * // => Allows adding up to 4 contacts to the list.
     */function before(n,func){var result;if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}n=toInteger(n);return function(){if(--n>0){result=func.apply(this,arguments);}if(n<=1){func=undefined;}return result;};}/**
     * Creates a function that invokes `func` with the `this` binding of `thisArg`
     * and `partials` prepended to the arguments it receives.
     *
     * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
     * may be used as a placeholder for partially applied arguments.
     *
     * **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
     * property of bound functions.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {Function} func The function to bind.
     * @param {*} thisArg The `this` binding of `func`.
     * @param {...*} [partials] The arguments to be partially applied.
     * @returns {Function} Returns the new bound function.
     * @example
     *
     * function greet(greeting, punctuation) {
     *   return greeting + ' ' + this.user + punctuation;
     * }
     *
     * var object = { 'user': 'fred' };
     *
     * var bound = _.bind(greet, object, 'hi');
     * bound('!');
     * // => 'hi fred!'
     *
     * // Bound with placeholders.
     * var bound = _.bind(greet, object, _, '!');
     * bound('hi');
     * // => 'hi fred!'
     */var bind=baseRest(function(func,thisArg,partials){var bitmask=WRAP_BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=WRAP_PARTIAL_FLAG;}return createWrap(func,bitmask,thisArg,partials,holders);});/**
     * Creates a function that invokes the method at `object[key]` with `partials`
     * prepended to the arguments it receives.
     *
     * This method differs from `_.bind` by allowing bound functions to reference
     * methods that may be redefined or don't yet exist. See
     * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
     * for more details.
     *
     * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
     * builds, may be used as a placeholder for partially applied arguments.
     *
     * @static
     * @memberOf _
     * @since 0.10.0
     * @category Function
     * @param {Object} object The object to invoke the method on.
     * @param {string} key The key of the method.
     * @param {...*} [partials] The arguments to be partially applied.
     * @returns {Function} Returns the new bound function.
     * @example
     *
     * var object = {
     *   'user': 'fred',
     *   'greet': function(greeting, punctuation) {
     *     return greeting + ' ' + this.user + punctuation;
     *   }
     * };
     *
     * var bound = _.bindKey(object, 'greet', 'hi');
     * bound('!');
     * // => 'hi fred!'
     *
     * object.greet = function(greeting, punctuation) {
     *   return greeting + 'ya ' + this.user + punctuation;
     * };
     *
     * bound('!');
     * // => 'hiya fred!'
     *
     * // Bound with placeholders.
     * var bound = _.bindKey(object, 'greet', _, '!');
     * bound('hi');
     * // => 'hiya fred!'
     */var bindKey=baseRest(function(object,key,partials){var bitmask=WRAP_BIND_FLAG|WRAP_BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=WRAP_PARTIAL_FLAG;}return createWrap(key,bitmask,object,partials,holders);});/**
     * Creates a function that accepts arguments of `func` and either invokes
     * `func` returning its result, if at least `arity` number of arguments have
     * been provided, or returns a function that accepts the remaining `func`
     * arguments, and so on. The arity of `func` may be specified if `func.length`
     * is not sufficient.
     *
     * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
     * may be used as a placeholder for provided arguments.
     *
     * **Note:** This method doesn't set the "length" property of curried functions.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Function
     * @param {Function} func The function to curry.
     * @param {number} [arity=func.length] The arity of `func`.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Function} Returns the new curried function.
     * @example
     *
     * var abc = function(a, b, c) {
     *   return [a, b, c];
     * };
     *
     * var curried = _.curry(abc);
     *
     * curried(1)(2)(3);
     * // => [1, 2, 3]
     *
     * curried(1, 2)(3);
     * // => [1, 2, 3]
     *
     * curried(1, 2, 3);
     * // => [1, 2, 3]
     *
     * // Curried with placeholders.
     * curried(1)(_, 3)(2);
     * // => [1, 2, 3]
     */function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,WRAP_CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);result.placeholder=curry.placeholder;return result;}/**
     * This method is like `_.curry` except that arguments are applied to `func`
     * in the manner of `_.partialRight` instead of `_.partial`.
     *
     * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
     * builds, may be used as a placeholder for provided arguments.
     *
     * **Note:** This method doesn't set the "length" property of curried functions.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Function
     * @param {Function} func The function to curry.
     * @param {number} [arity=func.length] The arity of `func`.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Function} Returns the new curried function.
     * @example
     *
     * var abc = function(a, b, c) {
     *   return [a, b, c];
     * };
     *
     * var curried = _.curryRight(abc);
     *
     * curried(3)(2)(1);
     * // => [1, 2, 3]
     *
     * curried(2, 3)(1);
     * // => [1, 2, 3]
     *
     * curried(1, 2, 3);
     * // => [1, 2, 3]
     *
     * // Curried with placeholders.
     * curried(3)(1, _)(2);
     * // => [1, 2, 3]
     */function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,WRAP_CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);result.placeholder=curryRight.placeholder;return result;}/**
     * Creates a debounced function that delays invoking `func` until after `wait`
     * milliseconds have elapsed since the last time the debounced function was
     * invoked. The debounced function comes with a `cancel` method to cancel
     * delayed `func` invocations and a `flush` method to immediately invoke them.
     * Provide `options` to indicate whether `func` should be invoked on the
     * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
     * with the last arguments provided to the debounced function. Subsequent
     * calls to the debounced function return the result of the last `func`
     * invocation.
     *
     * **Note:** If `leading` and `trailing` options are `true`, `func` is
     * invoked on the trailing edge of the timeout only if the debounced function
     * is invoked more than once during the `wait` timeout.
     *
     * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
     * until to the next tick, similar to `setTimeout` with a timeout of `0`.
     *
     * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
     * for details over the differences between `_.debounce` and `_.throttle`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {Function} func The function to debounce.
     * @param {number} [wait=0] The number of milliseconds to delay.
     * @param {Object} [options={}] The options object.
     * @param {boolean} [options.leading=false]
     *  Specify invoking on the leading edge of the timeout.
     * @param {number} [options.maxWait]
     *  The maximum time `func` is allowed to be delayed before it's invoked.
     * @param {boolean} [options.trailing=true]
     *  Specify invoking on the trailing edge of the timeout.
     * @returns {Function} Returns the new debounced function.
     * @example
     *
     * // Avoid costly calculations while the window size is in flux.
     * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
     *
     * // Invoke `sendMail` when clicked, debouncing subsequent calls.
     * jQuery(element).on('click', _.debounce(sendMail, 300, {
     *   'leading': true,
     *   'trailing': false
     * }));
     *
     * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
     * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
     * var source = new EventSource('/stream');
     * jQuery(source).on('message', debounced);
     *
     * // Cancel the trailing debounced invocation.
     * jQuery(window).on('popstate', debounced.cancel);
     */function debounce(func,wait,options){var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=false,maxing=false,trailing=true;if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}wait=toNumber(wait)||0;if(isObject(options)){leading=!!options.leading;maxing='maxWait'in options;maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait;trailing='trailing'in options?!!options.trailing:trailing;}function invokeFunc(time){var args=lastArgs,thisArg=lastThis;lastArgs=lastThis=undefined;lastInvokeTime=time;result=func.apply(thisArg,args);return result;}function leadingEdge(time){// Reset any `maxWait` timer.
lastInvokeTime=time;// Start the timer for the trailing edge.
timerId=setTimeout(timerExpired,wait);// Invoke the leading edge.
return leading?invokeFunc(time):result;}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,timeWaiting=wait-timeSinceLastCall;return maxing?nativeMin(timeWaiting,maxWait-timeSinceLastInvoke):timeWaiting;}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return lastCallTime===undefined||timeSinceLastCall>=wait||timeSinceLastCall<0||maxing&&timeSinceLastInvoke>=maxWait;}function timerExpired(){var time=now();if(shouldInvoke(time)){return trailingEdge(time);}// Restart the timer.
timerId=setTimeout(timerExpired,remainingWait(time));}function trailingEdge(time){timerId=undefined;// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if(trailing&&lastArgs){return invokeFunc(time);}lastArgs=lastThis=undefined;return result;}function cancel(){if(timerId!==undefined){clearTimeout(timerId);}lastInvokeTime=0;lastArgs=lastCallTime=lastThis=timerId=undefined;}function flush(){return timerId===undefined?result:trailingEdge(now());}function debounced(){var time=now(),isInvoking=shouldInvoke(time);lastArgs=arguments;lastThis=this;lastCallTime=time;if(isInvoking){if(timerId===undefined){return leadingEdge(lastCallTime);}if(maxing){// Handle invocations in a tight loop.
clearTimeout(timerId);timerId=setTimeout(timerExpired,wait);return invokeFunc(lastCallTime);}}if(timerId===undefined){timerId=setTimeout(timerExpired,wait);}return result;}debounced.cancel=cancel;debounced.flush=flush;return debounced;}/**
     * Defers invoking the `func` until the current call stack has cleared. Any
     * additional arguments are provided to `func` when it's invoked.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {Function} func The function to defer.
     * @param {...*} [args] The arguments to invoke `func` with.
     * @returns {number} Returns the timer id.
     * @example
     *
     * _.defer(function(text) {
     *   console.log(text);
     * }, 'deferred');
     * // => Logs 'deferred' after one millisecond.
     */var defer=baseRest(function(func,args){return baseDelay(func,1,args);});/**
     * Invokes `func` after `wait` milliseconds. Any additional arguments are
     * provided to `func` when it's invoked.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {Function} func The function to delay.
     * @param {number} wait The number of milliseconds to delay invocation.
     * @param {...*} [args] The arguments to invoke `func` with.
     * @returns {number} Returns the timer id.
     * @example
     *
     * _.delay(function(text) {
     *   console.log(text);
     * }, 1000, 'later');
     * // => Logs 'later' after one second.
     */var delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args);});/**
     * Creates a function that invokes `func` with arguments reversed.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Function
     * @param {Function} func The function to flip arguments for.
     * @returns {Function} Returns the new flipped function.
     * @example
     *
     * var flipped = _.flip(function() {
     *   return _.toArray(arguments);
     * });
     *
     * flipped('a', 'b', 'c', 'd');
     * // => ['d', 'c', 'b', 'a']
     */function flip(func){return createWrap(func,WRAP_FLIP_FLAG);}/**
     * Creates a function that memoizes the result of `func`. If `resolver` is
     * provided, it determines the cache key for storing the result based on the
     * arguments provided to the memoized function. By default, the first argument
     * provided to the memoized function is used as the map cache key. The `func`
     * is invoked with the `this` binding of the memoized function.
     *
     * **Note:** The cache is exposed as the `cache` property on the memoized
     * function. Its creation may be customized by replacing the `_.memoize.Cache`
     * constructor with one whose instances implement the
     * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
     * method interface of `clear`, `delete`, `get`, `has`, and `set`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {Function} func The function to have its output memoized.
     * @param {Function} [resolver] The function to resolve the cache key.
     * @returns {Function} Returns the new memoized function.
     * @example
     *
     * var object = { 'a': 1, 'b': 2 };
     * var other = { 'c': 3, 'd': 4 };
     *
     * var values = _.memoize(_.values);
     * values(object);
     * // => [1, 2]
     *
     * values(other);
     * // => [3, 4]
     *
     * object.a = 2;
     * values(object);
     * // => [1, 2]
     *
     * // Modify the result cache.
     * values.cache.set(object, ['a', 'b']);
     * values(object);
     * // => ['a', 'b']
     *
     * // Replace `_.memoize.Cache`.
     * _.memoize.Cache = WeakMap;
     */function memoize(func,resolver){if(typeof func!='function'||resolver!=null&&typeof resolver!='function'){throw new TypeError(FUNC_ERROR_TEXT);}var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key)){return cache.get(key);}var result=func.apply(this,args);memoized.cache=cache.set(key,result)||cache;return result;};memoized.cache=new(memoize.Cache||MapCache)();return memoized;}// Expose `MapCache`.
memoize.Cache=MapCache;/**
     * Creates a function that negates the result of the predicate `func`. The
     * `func` predicate is invoked with the `this` binding and arguments of the
     * created function.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Function
     * @param {Function} predicate The predicate to negate.
     * @returns {Function} Returns the new negated function.
     * @example
     *
     * function isEven(n) {
     *   return n % 2 == 0;
     * }
     *
     * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
     * // => [1, 3, 5]
     */function negate(predicate){if(typeof predicate!='function'){throw new TypeError(FUNC_ERROR_TEXT);}return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2]);}return!predicate.apply(this,args);};}/**
     * Creates a function that is restricted to invoking `func` once. Repeat calls
     * to the function return the value of the first invocation. The `func` is
     * invoked with the `this` binding and arguments of the created function.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {Function} func The function to restrict.
     * @returns {Function} Returns the new restricted function.
     * @example
     *
     * var initialize = _.once(createApplication);
     * initialize();
     * initialize();
     * // => `createApplication` is invoked once
     */function once(func){return before(2,func);}/**
     * Creates a function that invokes `func` with its arguments transformed.
     *
     * @static
     * @since 4.0.0
     * @memberOf _
     * @category Function
     * @param {Function} func The function to wrap.
     * @param {...(Function|Function[])} [transforms=[_.identity]]
     *  The argument transforms.
     * @returns {Function} Returns the new function.
     * @example
     *
     * function doubled(n) {
     *   return n * 2;
     * }
     *
     * function square(n) {
     *   return n * n;
     * }
     *
     * var func = _.overArgs(function(x, y) {
     *   return [x, y];
     * }, [square, doubled]);
     *
     * func(9, 3);
     * // => [81, 6]
     *
     * func(10, 5);
     * // => [100, 10]
     */var overArgs=castRest(function(func,transforms){transforms=transforms.length==1&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){var index=-1,length=nativeMin(args.length,funcsLength);while(++index<length){args[index]=transforms[index].call(this,args[index]);}return apply(func,this,args);});});/**
     * Creates a function that invokes `func` with `partials` prepended to the
     * arguments it receives. This method is like `_.bind` except it does **not**
     * alter the `this` binding.
     *
     * The `_.partial.placeholder` value, which defaults to `_` in monolithic
     * builds, may be used as a placeholder for partially applied arguments.
     *
     * **Note:** This method doesn't set the "length" property of partially
     * applied functions.
     *
     * @static
     * @memberOf _
     * @since 0.2.0
     * @category Function
     * @param {Function} func The function to partially apply arguments to.
     * @param {...*} [partials] The arguments to be partially applied.
     * @returns {Function} Returns the new partially applied function.
     * @example
     *
     * function greet(greeting, name) {
     *   return greeting + ' ' + name;
     * }
     *
     * var sayHelloTo = _.partial(greet, 'hello');
     * sayHelloTo('fred');
     * // => 'hello fred'
     *
     * // Partially applied with placeholders.
     * var greetFred = _.partial(greet, _, 'fred');
     * greetFred('hi');
     * // => 'hi fred'
     */var partial=baseRest(function(func,partials){var holders=replaceHolders(partials,getHolder(partial));return createWrap(func,WRAP_PARTIAL_FLAG,undefined,partials,holders);});/**
     * This method is like `_.partial` except that partially applied arguments
     * are appended to the arguments it receives.
     *
     * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
     * builds, may be used as a placeholder for partially applied arguments.
     *
     * **Note:** This method doesn't set the "length" property of partially
     * applied functions.
     *
     * @static
     * @memberOf _
     * @since 1.0.0
     * @category Function
     * @param {Function} func The function to partially apply arguments to.
     * @param {...*} [partials] The arguments to be partially applied.
     * @returns {Function} Returns the new partially applied function.
     * @example
     *
     * function greet(greeting, name) {
     *   return greeting + ' ' + name;
     * }
     *
     * var greetFred = _.partialRight(greet, 'fred');
     * greetFred('hi');
     * // => 'hi fred'
     *
     * // Partially applied with placeholders.
     * var sayHelloTo = _.partialRight(greet, 'hello', _);
     * sayHelloTo('fred');
     * // => 'hello fred'
     */var partialRight=baseRest(function(func,partials){var holders=replaceHolders(partials,getHolder(partialRight));return createWrap(func,WRAP_PARTIAL_RIGHT_FLAG,undefined,partials,holders);});/**
     * Creates a function that invokes `func` with arguments arranged according
     * to the specified `indexes` where the argument value at the first index is
     * provided as the first argument, the argument value at the second index is
     * provided as the second argument, and so on.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Function
     * @param {Function} func The function to rearrange arguments for.
     * @param {...(number|number[])} indexes The arranged argument indexes.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var rearged = _.rearg(function(a, b, c) {
     *   return [a, b, c];
     * }, [2, 0, 1]);
     *
     * rearged('b', 'c', 'a')
     * // => ['a', 'b', 'c']
     */var rearg=flatRest(function(func,indexes){return createWrap(func,WRAP_REARG_FLAG,undefined,undefined,undefined,indexes);});/**
     * Creates a function that invokes `func` with the `this` binding of the
     * created function and arguments from `start` and beyond provided as
     * an array.
     *
     * **Note:** This method is based on the
     * [rest parameter](https://mdn.io/rest_parameters).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Function
     * @param {Function} func The function to apply a rest parameter to.
     * @param {number} [start=func.length-1] The start position of the rest parameter.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var say = _.rest(function(what, names) {
     *   return what + ' ' + _.initial(names).join(', ') +
     *     (_.size(names) > 1 ? ', & ' : '') + _.last(names);
     * });
     *
     * say('hello', 'fred', 'barney', 'pebbles');
     * // => 'hello fred, barney, & pebbles'
     */function rest(func,start){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}start=start===undefined?start:toInteger(start);return baseRest(func,start);}/**
     * Creates a function that invokes `func` with the `this` binding of the
     * create function and an array of arguments much like
     * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).
     *
     * **Note:** This method is based on the
     * [spread operator](https://mdn.io/spread_operator).
     *
     * @static
     * @memberOf _
     * @since 3.2.0
     * @category Function
     * @param {Function} func The function to spread arguments over.
     * @param {number} [start=0] The start position of the spread.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var say = _.spread(function(who, what) {
     *   return who + ' says ' + what;
     * });
     *
     * say(['fred', 'hello']);
     * // => 'fred says hello'
     *
     * var numbers = Promise.all([
     *   Promise.resolve(40),
     *   Promise.resolve(36)
     * ]);
     *
     * numbers.then(_.spread(function(x, y) {
     *   return x + y;
     * }));
     * // => a Promise of 76
     */function spread(func,start){if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}start=start==null?0:nativeMax(toInteger(start),0);return baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);if(array){arrayPush(otherArgs,array);}return apply(func,this,otherArgs);});}/**
     * Creates a throttled function that only invokes `func` at most once per
     * every `wait` milliseconds. The throttled function comes with a `cancel`
     * method to cancel delayed `func` invocations and a `flush` method to
     * immediately invoke them. Provide `options` to indicate whether `func`
     * should be invoked on the leading and/or trailing edge of the `wait`
     * timeout. The `func` is invoked with the last arguments provided to the
     * throttled function. Subsequent calls to the throttled function return the
     * result of the last `func` invocation.
     *
     * **Note:** If `leading` and `trailing` options are `true`, `func` is
     * invoked on the trailing edge of the timeout only if the throttled function
     * is invoked more than once during the `wait` timeout.
     *
     * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
     * until to the next tick, similar to `setTimeout` with a timeout of `0`.
     *
     * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
     * for details over the differences between `_.throttle` and `_.debounce`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {Function} func The function to throttle.
     * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
     * @param {Object} [options={}] The options object.
     * @param {boolean} [options.leading=true]
     *  Specify invoking on the leading edge of the timeout.
     * @param {boolean} [options.trailing=true]
     *  Specify invoking on the trailing edge of the timeout.
     * @returns {Function} Returns the new throttled function.
     * @example
     *
     * // Avoid excessively updating the position while scrolling.
     * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
     *
     * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
     * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
     * jQuery(element).on('click', throttled);
     *
     * // Cancel the trailing throttled invocation.
     * jQuery(window).on('popstate', throttled.cancel);
     */function throttle(func,wait,options){var leading=true,trailing=true;if(typeof func!='function'){throw new TypeError(FUNC_ERROR_TEXT);}if(isObject(options)){leading='leading'in options?!!options.leading:leading;trailing='trailing'in options?!!options.trailing:trailing;}return debounce(func,wait,{'leading':leading,'maxWait':wait,'trailing':trailing});}/**
     * Creates a function that accepts up to one argument, ignoring any
     * additional arguments.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Function
     * @param {Function} func The function to cap arguments for.
     * @returns {Function} Returns the new capped function.
     * @example
     *
     * _.map(['6', '8', '10'], _.unary(parseInt));
     * // => [6, 8, 10]
     */function unary(func){return ary(func,1);}/**
     * Creates a function that provides `value` to `wrapper` as its first
     * argument. Any additional arguments provided to the function are appended
     * to those provided to the `wrapper`. The wrapper is invoked with the `this`
     * binding of the created function.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {*} value The value to wrap.
     * @param {Function} [wrapper=identity] The wrapper function.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var p = _.wrap(_.escape, function(func, text) {
     *   return '<p>' + func(text) + '</p>';
     * });
     *
     * p('fred, barney, & pebbles');
     * // => '<p>fred, barney, &amp; pebbles</p>'
     */function wrap(value,wrapper){return partial(castFunction(wrapper),value);}/*------------------------------------------------------------------------*/ /**
     * Casts `value` as an array if it's not one.
     *
     * @static
     * @memberOf _
     * @since 4.4.0
     * @category Lang
     * @param {*} value The value to inspect.
     * @returns {Array} Returns the cast array.
     * @example
     *
     * _.castArray(1);
     * // => [1]
     *
     * _.castArray({ 'a': 1 });
     * // => [{ 'a': 1 }]
     *
     * _.castArray('abc');
     * // => ['abc']
     *
     * _.castArray(null);
     * // => [null]
     *
     * _.castArray(undefined);
     * // => [undefined]
     *
     * _.castArray();
     * // => []
     *
     * var array = [1, 2, 3];
     * console.log(_.castArray(array) === array);
     * // => true
     */function castArray(){if(!arguments.length){return[];}var value=arguments[0];return isArray(value)?value:[value];}/**
     * Creates a shallow clone of `value`.
     *
     * **Note:** This method is loosely based on the
     * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
     * and supports cloning arrays, array buffers, booleans, date objects, maps,
     * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
     * arrays. The own enumerable properties of `arguments` objects are cloned
     * as plain objects. An empty object is returned for uncloneable values such
     * as error objects, functions, DOM nodes, and WeakMaps.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to clone.
     * @returns {*} Returns the cloned value.
     * @see _.cloneDeep
     * @example
     *
     * var objects = [{ 'a': 1 }, { 'b': 2 }];
     *
     * var shallow = _.clone(objects);
     * console.log(shallow[0] === objects[0]);
     * // => true
     */function clone(value){return baseClone(value,CLONE_SYMBOLS_FLAG);}/**
     * This method is like `_.clone` except that it accepts `customizer` which
     * is invoked to produce the cloned value. If `customizer` returns `undefined`,
     * cloning is handled by the method instead. The `customizer` is invoked with
     * up to four arguments; (value [, index|key, object, stack]).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to clone.
     * @param {Function} [customizer] The function to customize cloning.
     * @returns {*} Returns the cloned value.
     * @see _.cloneDeepWith
     * @example
     *
     * function customizer(value) {
     *   if (_.isElement(value)) {
     *     return value.cloneNode(false);
     *   }
     * }
     *
     * var el = _.cloneWith(document.body, customizer);
     *
     * console.log(el === document.body);
     * // => false
     * console.log(el.nodeName);
     * // => 'BODY'
     * console.log(el.childNodes.length);
     * // => 0
     */function cloneWith(value,customizer){customizer=typeof customizer=='function'?customizer:undefined;return baseClone(value,CLONE_SYMBOLS_FLAG,customizer);}/**
     * This method is like `_.clone` except that it recursively clones `value`.
     *
     * @static
     * @memberOf _
     * @since 1.0.0
     * @category Lang
     * @param {*} value The value to recursively clone.
     * @returns {*} Returns the deep cloned value.
     * @see _.clone
     * @example
     *
     * var objects = [{ 'a': 1 }, { 'b': 2 }];
     *
     * var deep = _.cloneDeep(objects);
     * console.log(deep[0] === objects[0]);
     * // => false
     */function cloneDeep(value){return baseClone(value,CLONE_DEEP_FLAG|CLONE_SYMBOLS_FLAG);}/**
     * This method is like `_.cloneWith` except that it recursively clones `value`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to recursively clone.
     * @param {Function} [customizer] The function to customize cloning.
     * @returns {*} Returns the deep cloned value.
     * @see _.cloneWith
     * @example
     *
     * function customizer(value) {
     *   if (_.isElement(value)) {
     *     return value.cloneNode(true);
     *   }
     * }
     *
     * var el = _.cloneDeepWith(document.body, customizer);
     *
     * console.log(el === document.body);
     * // => false
     * console.log(el.nodeName);
     * // => 'BODY'
     * console.log(el.childNodes.length);
     * // => 20
     */function cloneDeepWith(value,customizer){customizer=typeof customizer=='function'?customizer:undefined;return baseClone(value,CLONE_DEEP_FLAG|CLONE_SYMBOLS_FLAG,customizer);}/**
     * Checks if `object` conforms to `source` by invoking the predicate
     * properties of `source` with the corresponding property values of `object`.
     *
     * **Note:** This method is equivalent to `_.conforms` when `source` is
     * partially applied.
     *
     * @static
     * @memberOf _
     * @since 4.14.0
     * @category Lang
     * @param {Object} object The object to inspect.
     * @param {Object} source The object of property predicates to conform to.
     * @returns {boolean} Returns `true` if `object` conforms, else `false`.
     * @example
     *
     * var object = { 'a': 1, 'b': 2 };
     *
     * _.conformsTo(object, { 'b': function(n) { return n > 1; } });
     * // => true
     *
     * _.conformsTo(object, { 'b': function(n) { return n > 2; } });
     * // => false
     */function conformsTo(object,source){return source==null||baseConformsTo(object,source,keys(source));}/**
     * Performs a
     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * comparison between two values to determine if they are equivalent.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
     * @example
     *
     * var object = { 'a': 1 };
     * var other = { 'a': 1 };
     *
     * _.eq(object, object);
     * // => true
     *
     * _.eq(object, other);
     * // => false
     *
     * _.eq('a', 'a');
     * // => true
     *
     * _.eq('a', Object('a'));
     * // => false
     *
     * _.eq(NaN, NaN);
     * // => true
     */function eq(value,other){return value===other||value!==value&&other!==other;}/**
     * Checks if `value` is greater than `other`.
     *
     * @static
     * @memberOf _
     * @since 3.9.0
     * @category Lang
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if `value` is greater than `other`,
     *  else `false`.
     * @see _.lt
     * @example
     *
     * _.gt(3, 1);
     * // => true
     *
     * _.gt(3, 3);
     * // => false
     *
     * _.gt(1, 3);
     * // => false
     */var gt=createRelationalOperation(baseGt);/**
     * Checks if `value` is greater than or equal to `other`.
     *
     * @static
     * @memberOf _
     * @since 3.9.0
     * @category Lang
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if `value` is greater than or equal to
     *  `other`, else `false`.
     * @see _.lte
     * @example
     *
     * _.gte(3, 1);
     * // => true
     *
     * _.gte(3, 3);
     * // => true
     *
     * _.gte(1, 3);
     * // => false
     */var gte=createRelationalOperation(function(value,other){return value>=other;});/**
     * Checks if `value` is likely an `arguments` object.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an `arguments` object,
     *  else `false`.
     * @example
     *
     * _.isArguments(function() { return arguments; }());
     * // => true
     *
     * _.isArguments([1, 2, 3]);
     * // => false
     */var isArguments=baseIsArguments(function(){return arguments;}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,'callee')&&!propertyIsEnumerable.call(value,'callee');};/**
     * Checks if `value` is classified as an `Array` object.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an array, else `false`.
     * @example
     *
     * _.isArray([1, 2, 3]);
     * // => true
     *
     * _.isArray(document.body.children);
     * // => false
     *
     * _.isArray('abc');
     * // => false
     *
     * _.isArray(_.noop);
     * // => false
     */var isArray=Array.isArray;/**
     * Checks if `value` is classified as an `ArrayBuffer` object.
     *
     * @static
     * @memberOf _
     * @since 4.3.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
     * @example
     *
     * _.isArrayBuffer(new ArrayBuffer(2));
     * // => true
     *
     * _.isArrayBuffer(new Array(2));
     * // => false
     */var isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer;/**
     * Checks if `value` is array-like. A value is considered array-like if it's
     * not a function and has a `value.length` that's an integer greater than or
     * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
     * @example
     *
     * _.isArrayLike([1, 2, 3]);
     * // => true
     *
     * _.isArrayLike(document.body.children);
     * // => true
     *
     * _.isArrayLike('abc');
     * // => true
     *
     * _.isArrayLike(_.noop);
     * // => false
     */function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value);}/**
     * This method is like `_.isArrayLike` except that it also checks if `value`
     * is an object.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an array-like object,
     *  else `false`.
     * @example
     *
     * _.isArrayLikeObject([1, 2, 3]);
     * // => true
     *
     * _.isArrayLikeObject(document.body.children);
     * // => true
     *
     * _.isArrayLikeObject('abc');
     * // => false
     *
     * _.isArrayLikeObject(_.noop);
     * // => false
     */function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value);}/**
     * Checks if `value` is classified as a boolean primitive or object.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
     * @example
     *
     * _.isBoolean(false);
     * // => true
     *
     * _.isBoolean(null);
     * // => false
     */function isBoolean(value){return value===true||value===false||isObjectLike(value)&&baseGetTag(value)==boolTag;}/**
     * Checks if `value` is a buffer.
     *
     * @static
     * @memberOf _
     * @since 4.3.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
     * @example
     *
     * _.isBuffer(new Buffer(2));
     * // => true
     *
     * _.isBuffer(new Uint8Array(2));
     * // => false
     */var isBuffer=nativeIsBuffer||stubFalse;/**
     * Checks if `value` is classified as a `Date` object.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
     * @example
     *
     * _.isDate(new Date);
     * // => true
     *
     * _.isDate('Mon April 23 2012');
     * // => false
     */var isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate;/**
     * Checks if `value` is likely a DOM element.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
     * @example
     *
     * _.isElement(document.body);
     * // => true
     *
     * _.isElement('<body>');
     * // => false
     */function isElement(value){return isObjectLike(value)&&value.nodeType===1&&!isPlainObject(value);}/**
     * Checks if `value` is an empty object, collection, map, or set.
     *
     * Objects are considered empty if they have no own enumerable string keyed
     * properties.
     *
     * Array-like values such as `arguments` objects, arrays, buffers, strings, or
     * jQuery-like collections are considered empty if they have a `length` of `0`.
     * Similarly, maps and sets are considered empty if they have a `size` of `0`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is empty, else `false`.
     * @example
     *
     * _.isEmpty(null);
     * // => true
     *
     * _.isEmpty(true);
     * // => true
     *
     * _.isEmpty(1);
     * // => true
     *
     * _.isEmpty([1, 2, 3]);
     * // => false
     *
     * _.isEmpty({ 'a': 1 });
     * // => false
     */function isEmpty(value){if(value==null){return true;}if(isArrayLike(value)&&(isArray(value)||typeof value=='string'||typeof value.splice=='function'||isBuffer(value)||isTypedArray(value)||isArguments(value))){return!value.length;}var tag=getTag(value);if(tag==mapTag||tag==setTag){return!value.size;}if(isPrototype(value)){return!baseKeys(value).length;}for(var key in value){if(hasOwnProperty.call(value,key)){return false;}}return true;}/**
     * Performs a deep comparison between two values to determine if they are
     * equivalent.
     *
     * **Note:** This method supports comparing arrays, array buffers, booleans,
     * date objects, error objects, maps, numbers, `Object` objects, regexes,
     * sets, strings, symbols, and typed arrays. `Object` objects are compared
     * by their own, not inherited, enumerable properties. Functions and DOM
     * nodes are compared by strict equality, i.e. `===`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
     * @example
     *
     * var object = { 'a': 1 };
     * var other = { 'a': 1 };
     *
     * _.isEqual(object, other);
     * // => true
     *
     * object === other;
     * // => false
     */function isEqual(value,other){return baseIsEqual(value,other);}/**
     * This method is like `_.isEqual` except that it accepts `customizer` which
     * is invoked to compare values. If `customizer` returns `undefined`, comparisons
     * are handled by the method instead. The `customizer` is invoked with up to
     * six arguments: (objValue, othValue [, index|key, object, other, stack]).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @param {Function} [customizer] The function to customize comparisons.
     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
     * @example
     *
     * function isGreeting(value) {
     *   return /^h(?:i|ello)$/.test(value);
     * }
     *
     * function customizer(objValue, othValue) {
     *   if (isGreeting(objValue) && isGreeting(othValue)) {
     *     return true;
     *   }
     * }
     *
     * var array = ['hello', 'goodbye'];
     * var other = ['hi', 'goodbye'];
     *
     * _.isEqualWith(array, other, customizer);
     * // => true
     */function isEqualWith(value,other,customizer){customizer=typeof customizer=='function'?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,undefined,customizer):!!result;}/**
     * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
     * `SyntaxError`, `TypeError`, or `URIError` object.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
     * @example
     *
     * _.isError(new Error);
     * // => true
     *
     * _.isError(Error);
     * // => false
     */function isError(value){if(!isObjectLike(value)){return false;}var tag=baseGetTag(value);return tag==errorTag||tag==domExcTag||typeof value.message=='string'&&typeof value.name=='string'&&!isPlainObject(value);}/**
     * Checks if `value` is a finite primitive number.
     *
     * **Note:** This method is based on
     * [`Number.isFinite`](https://mdn.io/Number/isFinite).
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
     * @example
     *
     * _.isFinite(3);
     * // => true
     *
     * _.isFinite(Number.MIN_VALUE);
     * // => true
     *
     * _.isFinite(Infinity);
     * // => false
     *
     * _.isFinite('3');
     * // => false
     */function isFinite(value){return typeof value=='number'&&nativeIsFinite(value);}/**
     * Checks if `value` is classified as a `Function` object.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a function, else `false`.
     * @example
     *
     * _.isFunction(_);
     * // => true
     *
     * _.isFunction(/abc/);
     * // => false
     */function isFunction(value){if(!isObject(value)){return false;}// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag=baseGetTag(value);return tag==funcTag||tag==genTag||tag==asyncTag||tag==proxyTag;}/**
     * Checks if `value` is an integer.
     *
     * **Note:** This method is based on
     * [`Number.isInteger`](https://mdn.io/Number/isInteger).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an integer, else `false`.
     * @example
     *
     * _.isInteger(3);
     * // => true
     *
     * _.isInteger(Number.MIN_VALUE);
     * // => false
     *
     * _.isInteger(Infinity);
     * // => false
     *
     * _.isInteger('3');
     * // => false
     */function isInteger(value){return typeof value=='number'&&value==toInteger(value);}/**
     * Checks if `value` is a valid array-like length.
     *
     * **Note:** This method is loosely based on
     * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
     * @example
     *
     * _.isLength(3);
     * // => true
     *
     * _.isLength(Number.MIN_VALUE);
     * // => false
     *
     * _.isLength(Infinity);
     * // => false
     *
     * _.isLength('3');
     * // => false
     */function isLength(value){return typeof value=='number'&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER;}/**
     * Checks if `value` is the
     * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
     * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an object, else `false`.
     * @example
     *
     * _.isObject({});
     * // => true
     *
     * _.isObject([1, 2, 3]);
     * // => true
     *
     * _.isObject(_.noop);
     * // => true
     *
     * _.isObject(null);
     * // => false
     */function isObject(value){var type=typeof value;return value!=null&&(type=='object'||type=='function');}/**
     * Checks if `value` is object-like. A value is object-like if it's not `null`
     * and has a `typeof` result of "object".
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
     * @example
     *
     * _.isObjectLike({});
     * // => true
     *
     * _.isObjectLike([1, 2, 3]);
     * // => true
     *
     * _.isObjectLike(_.noop);
     * // => false
     *
     * _.isObjectLike(null);
     * // => false
     */function isObjectLike(value){return value!=null&&typeof value=='object';}/**
     * Checks if `value` is classified as a `Map` object.
     *
     * @static
     * @memberOf _
     * @since 4.3.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a map, else `false`.
     * @example
     *
     * _.isMap(new Map);
     * // => true
     *
     * _.isMap(new WeakMap);
     * // => false
     */var isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap;/**
     * Performs a partial deep comparison between `object` and `source` to
     * determine if `object` contains equivalent property values.
     *
     * **Note:** This method is equivalent to `_.matches` when `source` is
     * partially applied.
     *
     * Partial comparisons will match empty array and empty object `source`
     * values against any array or object value, respectively. See `_.isEqual`
     * for a list of supported value comparisons.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Lang
     * @param {Object} object The object to inspect.
     * @param {Object} source The object of property values to match.
     * @returns {boolean} Returns `true` if `object` is a match, else `false`.
     * @example
     *
     * var object = { 'a': 1, 'b': 2 };
     *
     * _.isMatch(object, { 'b': 2 });
     * // => true
     *
     * _.isMatch(object, { 'b': 1 });
     * // => false
     */function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source));}/**
     * This method is like `_.isMatch` except that it accepts `customizer` which
     * is invoked to compare values. If `customizer` returns `undefined`, comparisons
     * are handled by the method instead. The `customizer` is invoked with five
     * arguments: (objValue, srcValue, index|key, object, source).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {Object} object The object to inspect.
     * @param {Object} source The object of property values to match.
     * @param {Function} [customizer] The function to customize comparisons.
     * @returns {boolean} Returns `true` if `object` is a match, else `false`.
     * @example
     *
     * function isGreeting(value) {
     *   return /^h(?:i|ello)$/.test(value);
     * }
     *
     * function customizer(objValue, srcValue) {
     *   if (isGreeting(objValue) && isGreeting(srcValue)) {
     *     return true;
     *   }
     * }
     *
     * var object = { 'greeting': 'hello' };
     * var source = { 'greeting': 'hi' };
     *
     * _.isMatchWith(object, source, customizer);
     * // => true
     */function isMatchWith(object,source,customizer){customizer=typeof customizer=='function'?customizer:undefined;return baseIsMatch(object,source,getMatchData(source),customizer);}/**
     * Checks if `value` is `NaN`.
     *
     * **Note:** This method is based on
     * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
     * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
     * `undefined` and other non-number values.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
     * @example
     *
     * _.isNaN(NaN);
     * // => true
     *
     * _.isNaN(new Number(NaN));
     * // => true
     *
     * isNaN(undefined);
     * // => true
     *
     * _.isNaN(undefined);
     * // => false
     */function isNaN(value){// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber(value)&&value!=+value;}/**
     * Checks if `value` is a pristine native function.
     *
     * **Note:** This method can't reliably detect native functions in the presence
     * of the core-js package because core-js circumvents this kind of detection.
     * Despite multiple requests, the core-js maintainer has made it clear: any
     * attempt to fix the detection will be obstructed. As a result, we're left
     * with little choice but to throw an error. Unfortunately, this also affects
     * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),
     * which rely on core-js.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a native function,
     *  else `false`.
     * @example
     *
     * _.isNative(Array.prototype.push);
     * // => true
     *
     * _.isNative(_);
     * // => false
     */function isNative(value){if(isMaskable(value)){throw new Error(CORE_ERROR_TEXT);}return baseIsNative(value);}/**
     * Checks if `value` is `null`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
     * @example
     *
     * _.isNull(null);
     * // => true
     *
     * _.isNull(void 0);
     * // => false
     */function isNull(value){return value===null;}/**
     * Checks if `value` is `null` or `undefined`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is nullish, else `false`.
     * @example
     *
     * _.isNil(null);
     * // => true
     *
     * _.isNil(void 0);
     * // => true
     *
     * _.isNil(NaN);
     * // => false
     */function isNil(value){return value==null;}/**
     * Checks if `value` is classified as a `Number` primitive or object.
     *
     * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
     * classified as numbers, use the `_.isFinite` method.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a number, else `false`.
     * @example
     *
     * _.isNumber(3);
     * // => true
     *
     * _.isNumber(Number.MIN_VALUE);
     * // => true
     *
     * _.isNumber(Infinity);
     * // => true
     *
     * _.isNumber('3');
     * // => false
     */function isNumber(value){return typeof value=='number'||isObjectLike(value)&&baseGetTag(value)==numberTag;}/**
     * Checks if `value` is a plain object, that is, an object created by the
     * `Object` constructor or one with a `[[Prototype]]` of `null`.
     *
     * @static
     * @memberOf _
     * @since 0.8.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     * }
     *
     * _.isPlainObject(new Foo);
     * // => false
     *
     * _.isPlainObject([1, 2, 3]);
     * // => false
     *
     * _.isPlainObject({ 'x': 0, 'y': 0 });
     * // => true
     *
     * _.isPlainObject(Object.create(null));
     * // => true
     */function isPlainObject(value){if(!isObjectLike(value)||baseGetTag(value)!=objectTag){return false;}var proto=getPrototype(value);if(proto===null){return true;}var Ctor=hasOwnProperty.call(proto,'constructor')&&proto.constructor;return typeof Ctor=='function'&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString;}/**
     * Checks if `value` is classified as a `RegExp` object.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
     * @example
     *
     * _.isRegExp(/abc/);
     * // => true
     *
     * _.isRegExp('/abc/');
     * // => false
     */var isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp;/**
     * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
     * double precision number which isn't the result of a rounded unsafe integer.
     *
     * **Note:** This method is based on
     * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
     * @example
     *
     * _.isSafeInteger(3);
     * // => true
     *
     * _.isSafeInteger(Number.MIN_VALUE);
     * // => false
     *
     * _.isSafeInteger(Infinity);
     * // => false
     *
     * _.isSafeInteger('3');
     * // => false
     */function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&value<=MAX_SAFE_INTEGER;}/**
     * Checks if `value` is classified as a `Set` object.
     *
     * @static
     * @memberOf _
     * @since 4.3.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a set, else `false`.
     * @example
     *
     * _.isSet(new Set);
     * // => true
     *
     * _.isSet(new WeakSet);
     * // => false
     */var isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet;/**
     * Checks if `value` is classified as a `String` primitive or object.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a string, else `false`.
     * @example
     *
     * _.isString('abc');
     * // => true
     *
     * _.isString(1);
     * // => false
     */function isString(value){return typeof value=='string'||!isArray(value)&&isObjectLike(value)&&baseGetTag(value)==stringTag;}/**
     * Checks if `value` is classified as a `Symbol` primitive or object.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
     * @example
     *
     * _.isSymbol(Symbol.iterator);
     * // => true
     *
     * _.isSymbol('abc');
     * // => false
     */function isSymbol(value){return typeof value=='symbol'||isObjectLike(value)&&baseGetTag(value)==symbolTag;}/**
     * Checks if `value` is classified as a typed array.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
     * @example
     *
     * _.isTypedArray(new Uint8Array);
     * // => true
     *
     * _.isTypedArray([]);
     * // => false
     */var isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;/**
     * Checks if `value` is `undefined`.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
     * @example
     *
     * _.isUndefined(void 0);
     * // => true
     *
     * _.isUndefined(null);
     * // => false
     */function isUndefined(value){return value===undefined;}/**
     * Checks if `value` is classified as a `WeakMap` object.
     *
     * @static
     * @memberOf _
     * @since 4.3.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
     * @example
     *
     * _.isWeakMap(new WeakMap);
     * // => true
     *
     * _.isWeakMap(new Map);
     * // => false
     */function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag;}/**
     * Checks if `value` is classified as a `WeakSet` object.
     *
     * @static
     * @memberOf _
     * @since 4.3.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a weak set, else `false`.
     * @example
     *
     * _.isWeakSet(new WeakSet);
     * // => true
     *
     * _.isWeakSet(new Set);
     * // => false
     */function isWeakSet(value){return isObjectLike(value)&&baseGetTag(value)==weakSetTag;}/**
     * Checks if `value` is less than `other`.
     *
     * @static
     * @memberOf _
     * @since 3.9.0
     * @category Lang
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if `value` is less than `other`,
     *  else `false`.
     * @see _.gt
     * @example
     *
     * _.lt(1, 3);
     * // => true
     *
     * _.lt(3, 3);
     * // => false
     *
     * _.lt(3, 1);
     * // => false
     */var lt=createRelationalOperation(baseLt);/**
     * Checks if `value` is less than or equal to `other`.
     *
     * @static
     * @memberOf _
     * @since 3.9.0
     * @category Lang
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if `value` is less than or equal to
     *  `other`, else `false`.
     * @see _.gte
     * @example
     *
     * _.lte(1, 3);
     * // => true
     *
     * _.lte(3, 3);
     * // => true
     *
     * _.lte(3, 1);
     * // => false
     */var lte=createRelationalOperation(function(value,other){return value<=other;});/**
     * Converts `value` to an array.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Lang
     * @param {*} value The value to convert.
     * @returns {Array} Returns the converted array.
     * @example
     *
     * _.toArray({ 'a': 1, 'b': 2 });
     * // => [1, 2]
     *
     * _.toArray('abc');
     * // => ['a', 'b', 'c']
     *
     * _.toArray(1);
     * // => []
     *
     * _.toArray(null);
     * // => []
     */function toArray(value){if(!value){return[];}if(isArrayLike(value)){return isString(value)?stringToArray(value):copyArray(value);}if(symIterator&&value[symIterator]){return iteratorToArray(value[symIterator]());}var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value);}/**
     * Converts `value` to a finite number.
     *
     * @static
     * @memberOf _
     * @since 4.12.0
     * @category Lang
     * @param {*} value The value to convert.
     * @returns {number} Returns the converted number.
     * @example
     *
     * _.toFinite(3.2);
     * // => 3.2
     *
     * _.toFinite(Number.MIN_VALUE);
     * // => 5e-324
     *
     * _.toFinite(Infinity);
     * // => 1.7976931348623157e+308
     *
     * _.toFinite('3.2');
     * // => 3.2
     */function toFinite(value){if(!value){return value===0?value:0;}value=toNumber(value);if(value===INFINITY||value===-INFINITY){var sign=value<0?-1:1;return sign*MAX_INTEGER;}return value===value?value:0;}/**
     * Converts `value` to an integer.
     *
     * **Note:** This method is loosely based on
     * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to convert.
     * @returns {number} Returns the converted integer.
     * @example
     *
     * _.toInteger(3.2);
     * // => 3
     *
     * _.toInteger(Number.MIN_VALUE);
     * // => 0
     *
     * _.toInteger(Infinity);
     * // => 1.7976931348623157e+308
     *
     * _.toInteger('3.2');
     * // => 3
     */function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0;}/**
     * Converts `value` to an integer suitable for use as the length of an
     * array-like object.
     *
     * **Note:** This method is based on
     * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to convert.
     * @returns {number} Returns the converted integer.
     * @example
     *
     * _.toLength(3.2);
     * // => 3
     *
     * _.toLength(Number.MIN_VALUE);
     * // => 0
     *
     * _.toLength(Infinity);
     * // => 4294967295
     *
     * _.toLength('3.2');
     * // => 3
     */function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0;}/**
     * Converts `value` to a number.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to process.
     * @returns {number} Returns the number.
     * @example
     *
     * _.toNumber(3.2);
     * // => 3.2
     *
     * _.toNumber(Number.MIN_VALUE);
     * // => 5e-324
     *
     * _.toNumber(Infinity);
     * // => Infinity
     *
     * _.toNumber('3.2');
     * // => 3.2
     */function toNumber(value){if(typeof value=='number'){return value;}if(isSymbol(value)){return NAN;}if(isObject(value)){var other=typeof value.valueOf=='function'?value.valueOf():value;value=isObject(other)?other+'':other;}if(typeof value!='string'){return value===0?value:+value;}value=baseTrim(value);var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value;}/**
     * Converts `value` to a plain object flattening inherited enumerable string
     * keyed properties of `value` to own properties of the plain object.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Lang
     * @param {*} value The value to convert.
     * @returns {Object} Returns the converted plain object.
     * @example
     *
     * function Foo() {
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.assign({ 'a': 1 }, new Foo);
     * // => { 'a': 1, 'b': 2 }
     *
     * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
     * // => { 'a': 1, 'b': 2, 'c': 3 }
     */function toPlainObject(value){return copyObject(value,keysIn(value));}/**
     * Converts `value` to a safe integer. A safe integer can be compared and
     * represented correctly.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to convert.
     * @returns {number} Returns the converted integer.
     * @example
     *
     * _.toSafeInteger(3.2);
     * // => 3
     *
     * _.toSafeInteger(Number.MIN_VALUE);
     * // => 0
     *
     * _.toSafeInteger(Infinity);
     * // => 9007199254740991
     *
     * _.toSafeInteger('3.2');
     * // => 3
     */function toSafeInteger(value){return value?baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER):value===0?value:0;}/**
     * Converts `value` to a string. An empty string is returned for `null`
     * and `undefined` values. The sign of `-0` is preserved.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to convert.
     * @returns {string} Returns the converted string.
     * @example
     *
     * _.toString(null);
     * // => ''
     *
     * _.toString(-0);
     * // => '-0'
     *
     * _.toString([1, 2, 3]);
     * // => '1,2,3'
     */function toString(value){return value==null?'':baseToString(value);}/*------------------------------------------------------------------------*/ /**
     * Assigns own enumerable string keyed properties of source objects to the
     * destination object. Source objects are applied from left to right.
     * Subsequent sources overwrite property assignments of previous sources.
     *
     * **Note:** This method mutates `object` and is loosely based on
     * [`Object.assign`](https://mdn.io/Object/assign).
     *
     * @static
     * @memberOf _
     * @since 0.10.0
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} [sources] The source objects.
     * @returns {Object} Returns `object`.
     * @see _.assignIn
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     * }
     *
     * function Bar() {
     *   this.c = 3;
     * }
     *
     * Foo.prototype.b = 2;
     * Bar.prototype.d = 4;
     *
     * _.assign({ 'a': 0 }, new Foo, new Bar);
     * // => { 'a': 1, 'c': 3 }
     */var assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source)){copyObject(source,keys(source),object);return;}for(var key in source){if(hasOwnProperty.call(source,key)){assignValue(object,key,source[key]);}}});/**
     * This method is like `_.assign` except that it iterates over own and
     * inherited source properties.
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @alias extend
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} [sources] The source objects.
     * @returns {Object} Returns `object`.
     * @see _.assign
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     * }
     *
     * function Bar() {
     *   this.c = 3;
     * }
     *
     * Foo.prototype.b = 2;
     * Bar.prototype.d = 4;
     *
     * _.assignIn({ 'a': 0 }, new Foo, new Bar);
     * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
     */var assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object);});/**
     * This method is like `_.assignIn` except that it accepts `customizer`
     * which is invoked to produce the assigned values. If `customizer` returns
     * `undefined`, assignment is handled by the method instead. The `customizer`
     * is invoked with five arguments: (objValue, srcValue, key, object, source).
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @alias extendWith
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} sources The source objects.
     * @param {Function} [customizer] The function to customize assigned values.
     * @returns {Object} Returns `object`.
     * @see _.assignWith
     * @example
     *
     * function customizer(objValue, srcValue) {
     *   return _.isUndefined(objValue) ? srcValue : objValue;
     * }
     *
     * var defaults = _.partialRight(_.assignInWith, customizer);
     *
     * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
     * // => { 'a': 1, 'b': 2 }
     */var assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer);});/**
     * This method is like `_.assign` except that it accepts `customizer`
     * which is invoked to produce the assigned values. If `customizer` returns
     * `undefined`, assignment is handled by the method instead. The `customizer`
     * is invoked with five arguments: (objValue, srcValue, key, object, source).
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} sources The source objects.
     * @param {Function} [customizer] The function to customize assigned values.
     * @returns {Object} Returns `object`.
     * @see _.assignInWith
     * @example
     *
     * function customizer(objValue, srcValue) {
     *   return _.isUndefined(objValue) ? srcValue : objValue;
     * }
     *
     * var defaults = _.partialRight(_.assignWith, customizer);
     *
     * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
     * // => { 'a': 1, 'b': 2 }
     */var assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer);});/**
     * Creates an array of values corresponding to `paths` of `object`.
     *
     * @static
     * @memberOf _
     * @since 1.0.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {...(string|string[])} [paths] The property paths to pick.
     * @returns {Array} Returns the picked values.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
     *
     * _.at(object, ['a[0].b.c', 'a[1]']);
     * // => [3, 4]
     */var at=flatRest(baseAt);/**
     * Creates an object that inherits from the `prototype` object. If a
     * `properties` object is given, its own enumerable string keyed properties
     * are assigned to the created object.
     *
     * @static
     * @memberOf _
     * @since 2.3.0
     * @category Object
     * @param {Object} prototype The object to inherit from.
     * @param {Object} [properties] The properties to assign to the object.
     * @returns {Object} Returns the new object.
     * @example
     *
     * function Shape() {
     *   this.x = 0;
     *   this.y = 0;
     * }
     *
     * function Circle() {
     *   Shape.call(this);
     * }
     *
     * Circle.prototype = _.create(Shape.prototype, {
     *   'constructor': Circle
     * });
     *
     * var circle = new Circle;
     * circle instanceof Circle;
     * // => true
     *
     * circle instanceof Shape;
     * // => true
     */function create(prototype,properties){var result=baseCreate(prototype);return properties==null?result:baseAssign(result,properties);}/**
     * Assigns own and inherited enumerable string keyed properties of source
     * objects to the destination object for all destination properties that
     * resolve to `undefined`. Source objects are applied from left to right.
     * Once a property is set, additional values of the same property are ignored.
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} [sources] The source objects.
     * @returns {Object} Returns `object`.
     * @see _.defaultsDeep
     * @example
     *
     * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
     * // => { 'a': 1, 'b': 2 }
     */var defaults=baseRest(function(object,sources){object=Object(object);var index=-1;var length=sources.length;var guard=length>2?sources[2]:undefined;if(guard&&isIterateeCall(sources[0],sources[1],guard)){length=1;}while(++index<length){var source=sources[index];var props=keysIn(source);var propsIndex=-1;var propsLength=props.length;while(++propsIndex<propsLength){var key=props[propsIndex];var value=object[key];if(value===undefined||eq(value,objectProto[key])&&!hasOwnProperty.call(object,key)){object[key]=source[key];}}}return object;});/**
     * This method is like `_.defaults` except that it recursively assigns
     * default properties.
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 3.10.0
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} [sources] The source objects.
     * @returns {Object} Returns `object`.
     * @see _.defaults
     * @example
     *
     * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
     * // => { 'a': { 'b': 2, 'c': 3 } }
     */var defaultsDeep=baseRest(function(args){args.push(undefined,customDefaultsMerge);return apply(mergeWith,undefined,args);});/**
     * This method is like `_.find` except that it returns the key of the first
     * element `predicate` returns truthy for instead of the element itself.
     *
     * @static
     * @memberOf _
     * @since 1.1.0
     * @category Object
     * @param {Object} object The object to inspect.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {string|undefined} Returns the key of the matched element,
     *  else `undefined`.
     * @example
     *
     * var users = {
     *   'barney':  { 'age': 36, 'active': true },
     *   'fred':    { 'age': 40, 'active': false },
     *   'pebbles': { 'age': 1,  'active': true }
     * };
     *
     * _.findKey(users, function(o) { return o.age < 40; });
     * // => 'barney' (iteration order is not guaranteed)
     *
     * // The `_.matches` iteratee shorthand.
     * _.findKey(users, { 'age': 1, 'active': true });
     * // => 'pebbles'
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.findKey(users, ['active', false]);
     * // => 'fred'
     *
     * // The `_.property` iteratee shorthand.
     * _.findKey(users, 'active');
     * // => 'barney'
     */function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn);}/**
     * This method is like `_.findKey` except that it iterates over elements of
     * a collection in the opposite order.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Object
     * @param {Object} object The object to inspect.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {string|undefined} Returns the key of the matched element,
     *  else `undefined`.
     * @example
     *
     * var users = {
     *   'barney':  { 'age': 36, 'active': true },
     *   'fred':    { 'age': 40, 'active': false },
     *   'pebbles': { 'age': 1,  'active': true }
     * };
     *
     * _.findLastKey(users, function(o) { return o.age < 40; });
     * // => returns 'pebbles' assuming `_.findKey` returns 'barney'
     *
     * // The `_.matches` iteratee shorthand.
     * _.findLastKey(users, { 'age': 36, 'active': true });
     * // => 'barney'
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.findLastKey(users, ['active', false]);
     * // => 'fred'
     *
     * // The `_.property` iteratee shorthand.
     * _.findLastKey(users, 'active');
     * // => 'pebbles'
     */function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight);}/**
     * Iterates over own and inherited enumerable string keyed properties of an
     * object and invokes `iteratee` for each property. The iteratee is invoked
     * with three arguments: (value, key, object). Iteratee functions may exit
     * iteration early by explicitly returning `false`.
     *
     * @static
     * @memberOf _
     * @since 0.3.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Object} Returns `object`.
     * @see _.forInRight
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.forIn(new Foo, function(value, key) {
     *   console.log(key);
     * });
     * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
     */function forIn(object,iteratee){return object==null?object:baseFor(object,getIteratee(iteratee,3),keysIn);}/**
     * This method is like `_.forIn` except that it iterates over properties of
     * `object` in the opposite order.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Object} Returns `object`.
     * @see _.forIn
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.forInRight(new Foo, function(value, key) {
     *   console.log(key);
     * });
     * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
     */function forInRight(object,iteratee){return object==null?object:baseForRight(object,getIteratee(iteratee,3),keysIn);}/**
     * Iterates over own enumerable string keyed properties of an object and
     * invokes `iteratee` for each property. The iteratee is invoked with three
     * arguments: (value, key, object). Iteratee functions may exit iteration
     * early by explicitly returning `false`.
     *
     * @static
     * @memberOf _
     * @since 0.3.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Object} Returns `object`.
     * @see _.forOwnRight
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.forOwn(new Foo, function(value, key) {
     *   console.log(key);
     * });
     * // => Logs 'a' then 'b' (iteration order is not guaranteed).
     */function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3));}/**
     * This method is like `_.forOwn` except that it iterates over properties of
     * `object` in the opposite order.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Object} Returns `object`.
     * @see _.forOwn
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.forOwnRight(new Foo, function(value, key) {
     *   console.log(key);
     * });
     * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
     */function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3));}/**
     * Creates an array of function property names from own enumerable properties
     * of `object`.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The object to inspect.
     * @returns {Array} Returns the function names.
     * @see _.functionsIn
     * @example
     *
     * function Foo() {
     *   this.a = _.constant('a');
     *   this.b = _.constant('b');
     * }
     *
     * Foo.prototype.c = _.constant('c');
     *
     * _.functions(new Foo);
     * // => ['a', 'b']
     */function functions(object){return object==null?[]:baseFunctions(object,keys(object));}/**
     * Creates an array of function property names from own and inherited
     * enumerable properties of `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The object to inspect.
     * @returns {Array} Returns the function names.
     * @see _.functions
     * @example
     *
     * function Foo() {
     *   this.a = _.constant('a');
     *   this.b = _.constant('b');
     * }
     *
     * Foo.prototype.c = _.constant('c');
     *
     * _.functionsIn(new Foo);
     * // => ['a', 'b', 'c']
     */function functionsIn(object){return object==null?[]:baseFunctions(object,keysIn(object));}/**
     * Gets the value at `path` of `object`. If the resolved value is
     * `undefined`, the `defaultValue` is returned in its place.
     *
     * @static
     * @memberOf _
     * @since 3.7.0
     * @category Object
     * @param {Object} object The object to query.
     * @param {Array|string} path The path of the property to get.
     * @param {*} [defaultValue] The value returned for `undefined` resolved values.
     * @returns {*} Returns the resolved value.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c': 3 } }] };
     *
     * _.get(object, 'a[0].b.c');
     * // => 3
     *
     * _.get(object, ['a', '0', 'b', 'c']);
     * // => 3
     *
     * _.get(object, 'a.b.c', 'default');
     * // => 'default'
     */function get(object,path,defaultValue){var result=object==null?undefined:baseGet(object,path);return result===undefined?defaultValue:result;}/**
     * Checks if `path` is a direct property of `object`.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The object to query.
     * @param {Array|string} path The path to check.
     * @returns {boolean} Returns `true` if `path` exists, else `false`.
     * @example
     *
     * var object = { 'a': { 'b': 2 } };
     * var other = _.create({ 'a': _.create({ 'b': 2 }) });
     *
     * _.has(object, 'a');
     * // => true
     *
     * _.has(object, 'a.b');
     * // => true
     *
     * _.has(object, ['a', 'b']);
     * // => true
     *
     * _.has(other, 'a');
     * // => false
     */function has(object,path){return object!=null&&hasPath(object,path,baseHas);}/**
     * Checks if `path` is a direct or inherited property of `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The object to query.
     * @param {Array|string} path The path to check.
     * @returns {boolean} Returns `true` if `path` exists, else `false`.
     * @example
     *
     * var object = _.create({ 'a': _.create({ 'b': 2 }) });
     *
     * _.hasIn(object, 'a');
     * // => true
     *
     * _.hasIn(object, 'a.b');
     * // => true
     *
     * _.hasIn(object, ['a', 'b']);
     * // => true
     *
     * _.hasIn(object, 'b');
     * // => false
     */function hasIn(object,path){return object!=null&&hasPath(object,path,baseHasIn);}/**
     * Creates an object composed of the inverted keys and values of `object`.
     * If `object` contains duplicate values, subsequent values overwrite
     * property assignments of previous values.
     *
     * @static
     * @memberOf _
     * @since 0.7.0
     * @category Object
     * @param {Object} object The object to invert.
     * @returns {Object} Returns the new inverted object.
     * @example
     *
     * var object = { 'a': 1, 'b': 2, 'c': 1 };
     *
     * _.invert(object);
     * // => { '1': 'c', '2': 'b' }
     */var invert=createInverter(function(result,value,key){if(value!=null&&typeof value.toString!='function'){value=nativeObjectToString.call(value);}result[value]=key;},constant(identity));/**
     * This method is like `_.invert` except that the inverted object is generated
     * from the results of running each element of `object` thru `iteratee`. The
     * corresponding inverted value of each inverted key is an array of keys
     * responsible for generating the inverted value. The iteratee is invoked
     * with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.1.0
     * @category Object
     * @param {Object} object The object to invert.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {Object} Returns the new inverted object.
     * @example
     *
     * var object = { 'a': 1, 'b': 2, 'c': 1 };
     *
     * _.invertBy(object);
     * // => { '1': ['a', 'c'], '2': ['b'] }
     *
     * _.invertBy(object, function(value) {
     *   return 'group' + value;
     * });
     * // => { 'group1': ['a', 'c'], 'group2': ['b'] }
     */var invertBy=createInverter(function(result,value,key){if(value!=null&&typeof value.toString!='function'){value=nativeObjectToString.call(value);}if(hasOwnProperty.call(result,value)){result[value].push(key);}else{result[value]=[key];}},getIteratee);/**
     * Invokes the method at `path` of `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The object to query.
     * @param {Array|string} path The path of the method to invoke.
     * @param {...*} [args] The arguments to invoke the method with.
     * @returns {*} Returns the result of the invoked method.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
     *
     * _.invoke(object, 'a[0].b.c.slice', 1, 3);
     * // => [2, 3]
     */var invoke=baseRest(baseInvoke);/**
     * Creates an array of the own enumerable property names of `object`.
     *
     * **Note:** Non-object values are coerced to objects. See the
     * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
     * for more details.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property names.
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.keys(new Foo);
     * // => ['a', 'b'] (iteration order is not guaranteed)
     *
     * _.keys('hi');
     * // => ['0', '1']
     */function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object);}/**
     * Creates an array of the own and inherited enumerable property names of `object`.
     *
     * **Note:** Non-object values are coerced to objects.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Object
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property names.
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.keysIn(new Foo);
     * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
     */function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,true):baseKeysIn(object);}/**
     * The opposite of `_.mapValues`; this method creates an object with the
     * same values as `object` and keys generated by running each own enumerable
     * string keyed property of `object` thru `iteratee`. The iteratee is invoked
     * with three arguments: (value, key, object).
     *
     * @static
     * @memberOf _
     * @since 3.8.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Object} Returns the new mapped object.
     * @see _.mapValues
     * @example
     *
     * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
     *   return key + value;
     * });
     * // => { 'a1': 1, 'b2': 2 }
     */function mapKeys(object,iteratee){var result={};iteratee=getIteratee(iteratee,3);baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value);});return result;}/**
     * Creates an object with the same keys as `object` and values generated
     * by running each own enumerable string keyed property of `object` thru
     * `iteratee`. The iteratee is invoked with three arguments:
     * (value, key, object).
     *
     * @static
     * @memberOf _
     * @since 2.4.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Object} Returns the new mapped object.
     * @see _.mapKeys
     * @example
     *
     * var users = {
     *   'fred':    { 'user': 'fred',    'age': 40 },
     *   'pebbles': { 'user': 'pebbles', 'age': 1 }
     * };
     *
     * _.mapValues(users, function(o) { return o.age; });
     * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
     *
     * // The `_.property` iteratee shorthand.
     * _.mapValues(users, 'age');
     * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
     */function mapValues(object,iteratee){var result={};iteratee=getIteratee(iteratee,3);baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object));});return result;}/**
     * This method is like `_.assign` except that it recursively merges own and
     * inherited enumerable string keyed properties of source objects into the
     * destination object. Source properties that resolve to `undefined` are
     * skipped if a destination value exists. Array and plain object properties
     * are merged recursively. Other objects and value types are overridden by
     * assignment. Source objects are applied from left to right. Subsequent
     * sources overwrite property assignments of previous sources.
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 0.5.0
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} [sources] The source objects.
     * @returns {Object} Returns `object`.
     * @example
     *
     * var object = {
     *   'a': [{ 'b': 2 }, { 'd': 4 }]
     * };
     *
     * var other = {
     *   'a': [{ 'c': 3 }, { 'e': 5 }]
     * };
     *
     * _.merge(object, other);
     * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
     */var merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex);});/**
     * This method is like `_.merge` except that it accepts `customizer` which
     * is invoked to produce the merged values of the destination and source
     * properties. If `customizer` returns `undefined`, merging is handled by the
     * method instead. The `customizer` is invoked with six arguments:
     * (objValue, srcValue, key, object, source, stack).
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} sources The source objects.
     * @param {Function} customizer The function to customize assigned values.
     * @returns {Object} Returns `object`.
     * @example
     *
     * function customizer(objValue, srcValue) {
     *   if (_.isArray(objValue)) {
     *     return objValue.concat(srcValue);
     *   }
     * }
     *
     * var object = { 'a': [1], 'b': [2] };
     * var other = { 'a': [3], 'b': [4] };
     *
     * _.mergeWith(object, other, customizer);
     * // => { 'a': [1, 3], 'b': [2, 4] }
     */var mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer);});/**
     * The opposite of `_.pick`; this method creates an object composed of the
     * own and inherited enumerable property paths of `object` that are not omitted.
     *
     * **Note:** This method is considerably slower than `_.pick`.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The source object.
     * @param {...(string|string[])} [paths] The property paths to omit.
     * @returns {Object} Returns the new object.
     * @example
     *
     * var object = { 'a': 1, 'b': '2', 'c': 3 };
     *
     * _.omit(object, ['a', 'c']);
     * // => { 'b': '2' }
     */var omit=flatRest(function(object,paths){var result={};if(object==null){return result;}var isDeep=false;paths=arrayMap(paths,function(path){path=castPath(path,object);isDeep||(isDeep=path.length>1);return path;});copyObject(object,getAllKeysIn(object),result);if(isDeep){result=baseClone(result,CLONE_DEEP_FLAG|CLONE_FLAT_FLAG|CLONE_SYMBOLS_FLAG,customOmitClone);}var length=paths.length;while(length--){baseUnset(result,paths[length]);}return result;});/**
     * The opposite of `_.pickBy`; this method creates an object composed of
     * the own and inherited enumerable string keyed properties of `object` that
     * `predicate` doesn't return truthy for. The predicate is invoked with two
     * arguments: (value, key).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The source object.
     * @param {Function} [predicate=_.identity] The function invoked per property.
     * @returns {Object} Returns the new object.
     * @example
     *
     * var object = { 'a': 1, 'b': '2', 'c': 3 };
     *
     * _.omitBy(object, _.isNumber);
     * // => { 'b': '2' }
     */function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)));}/**
     * Creates an object composed of the picked `object` properties.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The source object.
     * @param {...(string|string[])} [paths] The property paths to pick.
     * @returns {Object} Returns the new object.
     * @example
     *
     * var object = { 'a': 1, 'b': '2', 'c': 3 };
     *
     * _.pick(object, ['a', 'c']);
     * // => { 'a': 1, 'c': 3 }
     */var pick=flatRest(function(object,paths){return object==null?{}:basePick(object,paths);});/**
     * Creates an object composed of the `object` properties `predicate` returns
     * truthy for. The predicate is invoked with two arguments: (value, key).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The source object.
     * @param {Function} [predicate=_.identity] The function invoked per property.
     * @returns {Object} Returns the new object.
     * @example
     *
     * var object = { 'a': 1, 'b': '2', 'c': 3 };
     *
     * _.pickBy(object, _.isNumber);
     * // => { 'a': 1, 'c': 3 }
     */function pickBy(object,predicate){if(object==null){return{};}var props=arrayMap(getAllKeysIn(object),function(prop){return[prop];});predicate=getIteratee(predicate);return basePickBy(object,props,function(value,path){return predicate(value,path[0]);});}/**
     * This method is like `_.get` except that if the resolved value is a
     * function it's invoked with the `this` binding of its parent object and
     * its result is returned.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The object to query.
     * @param {Array|string} path The path of the property to resolve.
     * @param {*} [defaultValue] The value returned for `undefined` resolved values.
     * @returns {*} Returns the resolved value.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
     *
     * _.result(object, 'a[0].b.c1');
     * // => 3
     *
     * _.result(object, 'a[0].b.c2');
     * // => 4
     *
     * _.result(object, 'a[0].b.c3', 'default');
     * // => 'default'
     *
     * _.result(object, 'a[0].b.c3', _.constant('default'));
     * // => 'default'
     */function result(object,path,defaultValue){path=castPath(path,object);var index=-1,length=path.length;// Ensure the loop is entered when path is empty.
if(!length){length=1;object=undefined;}while(++index<length){var value=object==null?undefined:object[toKey(path[index])];if(value===undefined){index=length;value=defaultValue;}object=isFunction(value)?value.call(object):value;}return object;}/**
     * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
     * it's created. Arrays are created for missing index properties while objects
     * are created for all other missing properties. Use `_.setWith` to customize
     * `path` creation.
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 3.7.0
     * @category Object
     * @param {Object} object The object to modify.
     * @param {Array|string} path The path of the property to set.
     * @param {*} value The value to set.
     * @returns {Object} Returns `object`.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c': 3 } }] };
     *
     * _.set(object, 'a[0].b.c', 4);
     * console.log(object.a[0].b.c);
     * // => 4
     *
     * _.set(object, ['x', '0', 'y', 'z'], 5);
     * console.log(object.x[0].y.z);
     * // => 5
     */function set(object,path,value){return object==null?object:baseSet(object,path,value);}/**
     * This method is like `_.set` except that it accepts `customizer` which is
     * invoked to produce the objects of `path`.  If `customizer` returns `undefined`
     * path creation is handled by the method instead. The `customizer` is invoked
     * with three arguments: (nsValue, key, nsObject).
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The object to modify.
     * @param {Array|string} path The path of the property to set.
     * @param {*} value The value to set.
     * @param {Function} [customizer] The function to customize assigned values.
     * @returns {Object} Returns `object`.
     * @example
     *
     * var object = {};
     *
     * _.setWith(object, '[0][1]', 'a', Object);
     * // => { '0': { '1': 'a' } }
     */function setWith(object,path,value,customizer){customizer=typeof customizer=='function'?customizer:undefined;return object==null?object:baseSet(object,path,value,customizer);}/**
     * Creates an array of own enumerable string keyed-value pairs for `object`
     * which can be consumed by `_.fromPairs`. If `object` is a map or set, its
     * entries are returned.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @alias entries
     * @category Object
     * @param {Object} object The object to query.
     * @returns {Array} Returns the key-value pairs.
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.toPairs(new Foo);
     * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
     */var toPairs=createToPairs(keys);/**
     * Creates an array of own and inherited enumerable string keyed-value pairs
     * for `object` which can be consumed by `_.fromPairs`. If `object` is a map
     * or set, its entries are returned.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @alias entriesIn
     * @category Object
     * @param {Object} object The object to query.
     * @returns {Array} Returns the key-value pairs.
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.toPairsIn(new Foo);
     * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
     */var toPairsIn=createToPairs(keysIn);/**
     * An alternative to `_.reduce`; this method transforms `object` to a new
     * `accumulator` object which is the result of running each of its own
     * enumerable string keyed properties thru `iteratee`, with each invocation
     * potentially mutating the `accumulator` object. If `accumulator` is not
     * provided, a new object with the same `[[Prototype]]` will be used. The
     * iteratee is invoked with four arguments: (accumulator, value, key, object).
     * Iteratee functions may exit iteration early by explicitly returning `false`.
     *
     * @static
     * @memberOf _
     * @since 1.3.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @param {*} [accumulator] The custom accumulator value.
     * @returns {*} Returns the accumulated value.
     * @example
     *
     * _.transform([2, 3, 4], function(result, n) {
     *   result.push(n *= n);
     *   return n % 2 == 0;
     * }, []);
     * // => [4, 9]
     *
     * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
     *   (result[value] || (result[value] = [])).push(key);
     * }, {});
     * // => { '1': ['a', 'c'], '2': ['b'] }
     */function transform(object,iteratee,accumulator){var isArr=isArray(object),isArrLike=isArr||isBuffer(object)||isTypedArray(object);iteratee=getIteratee(iteratee,4);if(accumulator==null){var Ctor=object&&object.constructor;if(isArrLike){accumulator=isArr?new Ctor():[];}else if(isObject(object)){accumulator=isFunction(Ctor)?baseCreate(getPrototype(object)):{};}else{accumulator={};}}(isArrLike?arrayEach:baseForOwn)(object,function(value,index,object){return iteratee(accumulator,value,index,object);});return accumulator;}/**
     * Removes the property at `path` of `object`.
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The object to modify.
     * @param {Array|string} path The path of the property to unset.
     * @returns {boolean} Returns `true` if the property is deleted, else `false`.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c': 7 } }] };
     * _.unset(object, 'a[0].b.c');
     * // => true
     *
     * console.log(object);
     * // => { 'a': [{ 'b': {} }] };
     *
     * _.unset(object, ['a', '0', 'b', 'c']);
     * // => true
     *
     * console.log(object);
     * // => { 'a': [{ 'b': {} }] };
     */function unset(object,path){return object==null?true:baseUnset(object,path);}/**
     * This method is like `_.set` except that accepts `updater` to produce the
     * value to set. Use `_.updateWith` to customize `path` creation. The `updater`
     * is invoked with one argument: (value).
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.6.0
     * @category Object
     * @param {Object} object The object to modify.
     * @param {Array|string} path The path of the property to set.
     * @param {Function} updater The function to produce the updated value.
     * @returns {Object} Returns `object`.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c': 3 } }] };
     *
     * _.update(object, 'a[0].b.c', function(n) { return n * n; });
     * console.log(object.a[0].b.c);
     * // => 9
     *
     * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
     * console.log(object.x[0].y.z);
     * // => 0
     */function update(object,path,updater){return object==null?object:baseUpdate(object,path,castFunction(updater));}/**
     * This method is like `_.update` except that it accepts `customizer` which is
     * invoked to produce the objects of `path`.  If `customizer` returns `undefined`
     * path creation is handled by the method instead. The `customizer` is invoked
     * with three arguments: (nsValue, key, nsObject).
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.6.0
     * @category Object
     * @param {Object} object The object to modify.
     * @param {Array|string} path The path of the property to set.
     * @param {Function} updater The function to produce the updated value.
     * @param {Function} [customizer] The function to customize assigned values.
     * @returns {Object} Returns `object`.
     * @example
     *
     * var object = {};
     *
     * _.updateWith(object, '[0][1]', _.constant('a'), Object);
     * // => { '0': { '1': 'a' } }
     */function updateWith(object,path,updater,customizer){customizer=typeof customizer=='function'?customizer:undefined;return object==null?object:baseUpdate(object,path,castFunction(updater),customizer);}/**
     * Creates an array of the own enumerable string keyed property values of `object`.
     *
     * **Note:** Non-object values are coerced to objects.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property values.
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.values(new Foo);
     * // => [1, 2] (iteration order is not guaranteed)
     *
     * _.values('hi');
     * // => ['h', 'i']
     */function values(object){return object==null?[]:baseValues(object,keys(object));}/**
     * Creates an array of the own and inherited enumerable string keyed property
     * values of `object`.
     *
     * **Note:** Non-object values are coerced to objects.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Object
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property values.
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.valuesIn(new Foo);
     * // => [1, 2, 3] (iteration order is not guaranteed)
     */function valuesIn(object){return object==null?[]:baseValues(object,keysIn(object));}/*------------------------------------------------------------------------*/ /**
     * Clamps `number` within the inclusive `lower` and `upper` bounds.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Number
     * @param {number} number The number to clamp.
     * @param {number} [lower] The lower bound.
     * @param {number} upper The upper bound.
     * @returns {number} Returns the clamped number.
     * @example
     *
     * _.clamp(-10, -5, 5);
     * // => -5
     *
     * _.clamp(10, -5, 5);
     * // => 5
     */function clamp(number,lower,upper){if(upper===undefined){upper=lower;lower=undefined;}if(upper!==undefined){upper=toNumber(upper);upper=upper===upper?upper:0;}if(lower!==undefined){lower=toNumber(lower);lower=lower===lower?lower:0;}return baseClamp(toNumber(number),lower,upper);}/**
     * Checks if `n` is between `start` and up to, but not including, `end`. If
     * `end` is not specified, it's set to `start` with `start` then set to `0`.
     * If `start` is greater than `end` the params are swapped to support
     * negative ranges.
     *
     * @static
     * @memberOf _
     * @since 3.3.0
     * @category Number
     * @param {number} number The number to check.
     * @param {number} [start=0] The start of the range.
     * @param {number} end The end of the range.
     * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
     * @see _.range, _.rangeRight
     * @example
     *
     * _.inRange(3, 2, 4);
     * // => true
     *
     * _.inRange(4, 8);
     * // => true
     *
     * _.inRange(4, 2);
     * // => false
     *
     * _.inRange(2, 2);
     * // => false
     *
     * _.inRange(1.2, 2);
     * // => true
     *
     * _.inRange(5.2, 4);
     * // => false
     *
     * _.inRange(-3, -2, -6);
     * // => true
     */function inRange(number,start,end){start=toFinite(start);if(end===undefined){end=start;start=0;}else{end=toFinite(end);}number=toNumber(number);return baseInRange(number,start,end);}/**
     * Produces a random number between the inclusive `lower` and `upper` bounds.
     * If only one argument is provided a number between `0` and the given number
     * is returned. If `floating` is `true`, or either `lower` or `upper` are
     * floats, a floating-point number is returned instead of an integer.
     *
     * **Note:** JavaScript follows the IEEE-754 standard for resolving
     * floating-point values which can produce unexpected results.
     *
     * @static
     * @memberOf _
     * @since 0.7.0
     * @category Number
     * @param {number} [lower=0] The lower bound.
     * @param {number} [upper=1] The upper bound.
     * @param {boolean} [floating] Specify returning a floating-point number.
     * @returns {number} Returns the random number.
     * @example
     *
     * _.random(0, 5);
     * // => an integer between 0 and 5
     *
     * _.random(5);
     * // => also an integer between 0 and 5
     *
     * _.random(5, true);
     * // => a floating-point number between 0 and 5
     *
     * _.random(1.2, 5.2);
     * // => a floating-point number between 1.2 and 5.2
     */function random(lower,upper,floating){if(floating&&typeof floating!='boolean'&&isIterateeCall(lower,upper,floating)){upper=floating=undefined;}if(floating===undefined){if(typeof upper=='boolean'){floating=upper;upper=undefined;}else if(typeof lower=='boolean'){floating=lower;lower=undefined;}}if(lower===undefined&&upper===undefined){lower=0;upper=1;}else{lower=toFinite(lower);if(upper===undefined){upper=lower;lower=0;}else{upper=toFinite(upper);}}if(lower>upper){var temp=lower;lower=upper;upper=temp;}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat('1e-'+((rand+'').length-1))),upper);}return baseRandom(lower,upper);}/*------------------------------------------------------------------------*/ /**
     * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the camel cased string.
     * @example
     *
     * _.camelCase('Foo Bar');
     * // => 'fooBar'
     *
     * _.camelCase('--foo-bar--');
     * // => 'fooBar'
     *
     * _.camelCase('__FOO_BAR__');
     * // => 'fooBar'
     */var camelCase=createCompounder(function(result,word,index){word=word.toLowerCase();return result+(index?capitalize(word):word);});/**
     * Converts the first character of `string` to upper case and the remaining
     * to lower case.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to capitalize.
     * @returns {string} Returns the capitalized string.
     * @example
     *
     * _.capitalize('FRED');
     * // => 'Fred'
     */function capitalize(string){return upperFirst(toString(string).toLowerCase());}/**
     * Deburrs `string` by converting
     * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
     * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
     * letters to basic Latin letters and removing
     * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to deburr.
     * @returns {string} Returns the deburred string.
     * @example
     *
     * _.deburr('déjà vu');
     * // => 'deja vu'
     */function deburr(string){string=toString(string);return string&&string.replace(reLatin,deburrLetter).replace(reComboMark,'');}/**
     * Checks if `string` ends with the given target string.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to inspect.
     * @param {string} [target] The string to search for.
     * @param {number} [position=string.length] The position to search up to.
     * @returns {boolean} Returns `true` if `string` ends with `target`,
     *  else `false`.
     * @example
     *
     * _.endsWith('abc', 'c');
     * // => true
     *
     * _.endsWith('abc', 'b');
     * // => false
     *
     * _.endsWith('abc', 'b', 2);
     * // => true
     */function endsWith(string,target,position){string=toString(string);target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;position-=target.length;return position>=0&&string.slice(position,end)==target;}/**
     * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
     * corresponding HTML entities.
     *
     * **Note:** No other characters are escaped. To escape additional
     * characters use a third-party library like [_he_](https://mths.be/he).
     *
     * Though the ">" character is escaped for symmetry, characters like
     * ">" and "/" don't need escaping in HTML and have no special meaning
     * unless they're part of a tag or unquoted attribute value. See
     * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
     * (under "semi-related fun fact") for more details.
     *
     * When working with HTML you should always
     * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
     * XSS vectors.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category String
     * @param {string} [string=''] The string to escape.
     * @returns {string} Returns the escaped string.
     * @example
     *
     * _.escape('fred, barney, & pebbles');
     * // => 'fred, barney, &amp; pebbles'
     */function escape(string){string=toString(string);return string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string;}/**
     * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
     * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to escape.
     * @returns {string} Returns the escaped string.
     * @example
     *
     * _.escapeRegExp('[lodash](https://lodash.com/)');
     * // => '\[lodash\]\(https://lodash\.com/\)'
     */function escapeRegExp(string){string=toString(string);return string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,'\\$&'):string;}/**
     * Converts `string` to
     * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the kebab cased string.
     * @example
     *
     * _.kebabCase('Foo Bar');
     * // => 'foo-bar'
     *
     * _.kebabCase('fooBar');
     * // => 'foo-bar'
     *
     * _.kebabCase('__FOO_BAR__');
     * // => 'foo-bar'
     */var kebabCase=createCompounder(function(result,word,index){return result+(index?'-':'')+word.toLowerCase();});/**
     * Converts `string`, as space separated words, to lower case.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the lower cased string.
     * @example
     *
     * _.lowerCase('--Foo-Bar--');
     * // => 'foo bar'
     *
     * _.lowerCase('fooBar');
     * // => 'foo bar'
     *
     * _.lowerCase('__FOO_BAR__');
     * // => 'foo bar'
     */var lowerCase=createCompounder(function(result,word,index){return result+(index?' ':'')+word.toLowerCase();});/**
     * Converts the first character of `string` to lower case.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the converted string.
     * @example
     *
     * _.lowerFirst('Fred');
     * // => 'fred'
     *
     * _.lowerFirst('FRED');
     * // => 'fRED'
     */var lowerFirst=createCaseFirst('toLowerCase');/**
     * Pads `string` on the left and right sides if it's shorter than `length`.
     * Padding characters are truncated if they can't be evenly divided by `length`.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to pad.
     * @param {number} [length=0] The padding length.
     * @param {string} [chars=' '] The string used as padding.
     * @returns {string} Returns the padded string.
     * @example
     *
     * _.pad('abc', 8);
     * // => '  abc   '
     *
     * _.pad('abc', 8, '_-');
     * // => '_-abc_-_'
     *
     * _.pad('abc', 3);
     * // => 'abc'
     */function pad(string,length,chars){string=toString(string);length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length){return string;}var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars);}/**
     * Pads `string` on the right side if it's shorter than `length`. Padding
     * characters are truncated if they exceed `length`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to pad.
     * @param {number} [length=0] The padding length.
     * @param {string} [chars=' '] The string used as padding.
     * @returns {string} Returns the padded string.
     * @example
     *
     * _.padEnd('abc', 6);
     * // => 'abc   '
     *
     * _.padEnd('abc', 6, '_-');
     * // => 'abc_-_'
     *
     * _.padEnd('abc', 3);
     * // => 'abc'
     */function padEnd(string,length,chars){string=toString(string);length=toInteger(length);var strLength=length?stringSize(string):0;return length&&strLength<length?string+createPadding(length-strLength,chars):string;}/**
     * Pads `string` on the left side if it's shorter than `length`. Padding
     * characters are truncated if they exceed `length`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to pad.
     * @param {number} [length=0] The padding length.
     * @param {string} [chars=' '] The string used as padding.
     * @returns {string} Returns the padded string.
     * @example
     *
     * _.padStart('abc', 6);
     * // => '   abc'
     *
     * _.padStart('abc', 6, '_-');
     * // => '_-_abc'
     *
     * _.padStart('abc', 3);
     * // => 'abc'
     */function padStart(string,length,chars){string=toString(string);length=toInteger(length);var strLength=length?stringSize(string):0;return length&&strLength<length?createPadding(length-strLength,chars)+string:string;}/**
     * Converts `string` to an integer of the specified radix. If `radix` is
     * `undefined` or `0`, a `radix` of `10` is used unless `value` is a
     * hexadecimal, in which case a `radix` of `16` is used.
     *
     * **Note:** This method aligns with the
     * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
     *
     * @static
     * @memberOf _
     * @since 1.1.0
     * @category String
     * @param {string} string The string to convert.
     * @param {number} [radix=10] The radix to interpret `value` by.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {number} Returns the converted integer.
     * @example
     *
     * _.parseInt('08');
     * // => 8
     *
     * _.map(['6', '08', '10'], _.parseInt);
     * // => [6, 8, 10]
     */function parseInt(string,radix,guard){if(guard||radix==null){radix=0;}else if(radix){radix=+radix;}return nativeParseInt(toString(string).replace(reTrimStart,''),radix||0);}/**
     * Repeats the given string `n` times.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to repeat.
     * @param {number} [n=1] The number of times to repeat the string.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {string} Returns the repeated string.
     * @example
     *
     * _.repeat('*', 3);
     * // => '***'
     *
     * _.repeat('abc', 2);
     * // => 'abcabc'
     *
     * _.repeat('abc', 0);
     * // => ''
     */function repeat(string,n,guard){if(guard?isIterateeCall(string,n,guard):n===undefined){n=1;}else{n=toInteger(n);}return baseRepeat(toString(string),n);}/**
     * Replaces matches for `pattern` in `string` with `replacement`.
     *
     * **Note:** This method is based on
     * [`String#replace`](https://mdn.io/String/replace).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to modify.
     * @param {RegExp|string} pattern The pattern to replace.
     * @param {Function|string} replacement The match replacement.
     * @returns {string} Returns the modified string.
     * @example
     *
     * _.replace('Hi Fred', 'Fred', 'Barney');
     * // => 'Hi Barney'
     */function replace(){var args=arguments,string=toString(args[0]);return args.length<3?string:string.replace(args[1],args[2]);}/**
     * Converts `string` to
     * [snake case](https://en.wikipedia.org/wiki/Snake_case).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the snake cased string.
     * @example
     *
     * _.snakeCase('Foo Bar');
     * // => 'foo_bar'
     *
     * _.snakeCase('fooBar');
     * // => 'foo_bar'
     *
     * _.snakeCase('--FOO-BAR--');
     * // => 'foo_bar'
     */var snakeCase=createCompounder(function(result,word,index){return result+(index?'_':'')+word.toLowerCase();});/**
     * Splits `string` by `separator`.
     *
     * **Note:** This method is based on
     * [`String#split`](https://mdn.io/String/split).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to split.
     * @param {RegExp|string} separator The separator pattern to split by.
     * @param {number} [limit] The length to truncate results to.
     * @returns {Array} Returns the string segments.
     * @example
     *
     * _.split('a-b-c', '-', 2);
     * // => ['a', 'b']
     */function split(string,separator,limit){if(limit&&typeof limit!='number'&&isIterateeCall(string,separator,limit)){separator=limit=undefined;}limit=limit===undefined?MAX_ARRAY_LENGTH:limit>>>0;if(!limit){return[];}string=toString(string);if(string&&(typeof separator=='string'||separator!=null&&!isRegExp(separator))){separator=baseToString(separator);if(!separator&&hasUnicode(string)){return castSlice(stringToArray(string),0,limit);}}return string.split(separator,limit);}/**
     * Converts `string` to
     * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
     *
     * @static
     * @memberOf _
     * @since 3.1.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the start cased string.
     * @example
     *
     * _.startCase('--foo-bar--');
     * // => 'Foo Bar'
     *
     * _.startCase('fooBar');
     * // => 'Foo Bar'
     *
     * _.startCase('__FOO_BAR__');
     * // => 'FOO BAR'
     */var startCase=createCompounder(function(result,word,index){return result+(index?' ':'')+upperFirst(word);});/**
     * Checks if `string` starts with the given target string.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to inspect.
     * @param {string} [target] The string to search for.
     * @param {number} [position=0] The position to search from.
     * @returns {boolean} Returns `true` if `string` starts with `target`,
     *  else `false`.
     * @example
     *
     * _.startsWith('abc', 'a');
     * // => true
     *
     * _.startsWith('abc', 'b');
     * // => false
     *
     * _.startsWith('abc', 'b', 1);
     * // => true
     */function startsWith(string,target,position){string=toString(string);position=position==null?0:baseClamp(toInteger(position),0,string.length);target=baseToString(target);return string.slice(position,position+target.length)==target;}/**
     * Creates a compiled template function that can interpolate data properties
     * in "interpolate" delimiters, HTML-escape interpolated data properties in
     * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
     * properties may be accessed as free variables in the template. If a setting
     * object is given, it takes precedence over `_.templateSettings` values.
     *
     * **Note:** In the development build `_.template` utilizes
     * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
     * for easier debugging.
     *
     * For more information on precompiling templates see
     * [lodash's custom builds documentation](https://lodash.com/custom-builds).
     *
     * For more information on Chrome extension sandboxes see
     * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category String
     * @param {string} [string=''] The template string.
     * @param {Object} [options={}] The options object.
     * @param {RegExp} [options.escape=_.templateSettings.escape]
     *  The HTML "escape" delimiter.
     * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
     *  The "evaluate" delimiter.
     * @param {Object} [options.imports=_.templateSettings.imports]
     *  An object to import into the template as free variables.
     * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
     *  The "interpolate" delimiter.
     * @param {string} [options.sourceURL='lodash.templateSources[n]']
     *  The sourceURL of the compiled template.
     * @param {string} [options.variable='obj']
     *  The data object variable name.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Function} Returns the compiled template function.
     * @example
     *
     * // Use the "interpolate" delimiter to create a compiled template.
     * var compiled = _.template('hello <%= user %>!');
     * compiled({ 'user': 'fred' });
     * // => 'hello fred!'
     *
     * // Use the HTML "escape" delimiter to escape data property values.
     * var compiled = _.template('<b><%- value %></b>');
     * compiled({ 'value': '<script>' });
     * // => '<b>&lt;script&gt;</b>'
     *
     * // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
     * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
     * compiled({ 'users': ['fred', 'barney'] });
     * // => '<li>fred</li><li>barney</li>'
     *
     * // Use the internal `print` function in "evaluate" delimiters.
     * var compiled = _.template('<% print("hello " + user); %>!');
     * compiled({ 'user': 'barney' });
     * // => 'hello barney!'
     *
     * // Use the ES template literal delimiter as an "interpolate" delimiter.
     * // Disable support by replacing the "interpolate" delimiter.
     * var compiled = _.template('hello ${ user }!');
     * compiled({ 'user': 'pebbles' });
     * // => 'hello pebbles!'
     *
     * // Use backslashes to treat delimiters as plain text.
     * var compiled = _.template('<%= "\\<%- value %\\>" %>');
     * compiled({ 'value': 'ignored' });
     * // => '<%- value %>'
     *
     * // Use the `imports` option to import `jQuery` as `jq`.
     * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
     * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
     * compiled({ 'users': ['fred', 'barney'] });
     * // => '<li>fred</li><li>barney</li>'
     *
     * // Use the `sourceURL` option to specify a custom sourceURL for the template.
     * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
     * compiled(data);
     * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
     *
     * // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
     * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
     * compiled.source;
     * // => function(data) {
     * //   var __t, __p = '';
     * //   __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
     * //   return __p;
     * // }
     *
     * // Use custom template delimiters.
     * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
     * var compiled = _.template('hello {{ user }}!');
     * compiled({ 'user': 'mustache' });
     * // => 'hello mustache!'
     *
     * // Use the `source` property to inline compiled templates for meaningful
     * // line numbers in error messages and stack traces.
     * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
     *   var JST = {\
     *     "main": ' + _.template(mainText).source + '\
     *   };\
     * ');
     */function template(string,options,guard){// Based on John Resig's `tmpl` implementation
// (http://ejohn.org/blog/javascript-micro-templating/)
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
var settings=lodash.templateSettings;if(guard&&isIterateeCall(string,options,guard)){options=undefined;}string=toString(string);options=assignInWith({},options,settings,customDefaultsAssignIn);var imports=assignInWith({},options.imports,settings.imports,customDefaultsAssignIn),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys);var isEscaping,isEvaluating,index=0,interpolate=options.interpolate||reNoMatch,source="__p += '";// Compile the regexp to match each delimiter.
var reDelimiters=RegExp((options.escape||reNoMatch).source+'|'+interpolate.source+'|'+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+'|'+(options.evaluate||reNoMatch).source+'|$','g');// Use a sourceURL for easier debugging.
// The sourceURL gets injected into the source that's eval-ed, so be careful
// to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in
// and escape the comment, thus injecting code that gets evaled.
var sourceURL='//# sourceURL='+(hasOwnProperty.call(options,'sourceURL')?(options.sourceURL+'').replace(/\s/g,' '):'lodash.templateSources['+ ++templateCounter+']')+'\n';string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){interpolateValue||(interpolateValue=esTemplateValue);// Escape characters that can't be included in string literals.
source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar);// Replace delimiters with snippets.
if(escapeValue){isEscaping=true;source+="' +\n__e("+escapeValue+") +\n'";}if(evaluateValue){isEvaluating=true;source+="';\n"+evaluateValue+";\n__p += '";}if(interpolateValue){source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'";}index=offset+match.length;// The JS engine embedded in Adobe products needs `match` returned in
// order to produce the correct `offset` value.
return match;});source+="';\n";// If `variable` is not specified wrap a with-statement around the generated
// code to add the data object to the top of the scope chain.
var variable=hasOwnProperty.call(options,'variable')&&options.variable;if(!variable){source='with (obj) {\n'+source+'\n}\n';}// Throw an error if a forbidden character was found in `variable`, to prevent
// potential command injection attacks.
else if(reForbiddenIdentifierChars.test(variable)){throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT);}// Cleanup code by stripping empty strings.
source=(isEvaluating?source.replace(reEmptyStringLeading,''):source).replace(reEmptyStringMiddle,'$1').replace(reEmptyStringTrailing,'$1;');// Frame code as the function body.
source='function('+(variable||'obj')+') {\n'+(variable?'':'obj || (obj = {});\n')+"var __t, __p = ''"+(isEscaping?', __e = _.escape':'')+(isEvaluating?', __j = Array.prototype.join;\n'+"function print() { __p += __j.call(arguments, '') }\n":';\n')+source+'return __p\n}';var result=attempt(function(){return Function(importsKeys,sourceURL+'return '+source).apply(undefined,importsValues);});// Provide the compiled function's source by its `toString` method or
// the `source` property as a convenience for inlining compiled templates.
result.source=source;if(isError(result)){throw result;}return result;}/**
     * Converts `string`, as a whole, to lower case just like
     * [String#toLowerCase](https://mdn.io/toLowerCase).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the lower cased string.
     * @example
     *
     * _.toLower('--Foo-Bar--');
     * // => '--foo-bar--'
     *
     * _.toLower('fooBar');
     * // => 'foobar'
     *
     * _.toLower('__FOO_BAR__');
     * // => '__foo_bar__'
     */function toLower(value){return toString(value).toLowerCase();}/**
     * Converts `string`, as a whole, to upper case just like
     * [String#toUpperCase](https://mdn.io/toUpperCase).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the upper cased string.
     * @example
     *
     * _.toUpper('--foo-bar--');
     * // => '--FOO-BAR--'
     *
     * _.toUpper('fooBar');
     * // => 'FOOBAR'
     *
     * _.toUpper('__foo_bar__');
     * // => '__FOO_BAR__'
     */function toUpper(value){return toString(value).toUpperCase();}/**
     * Removes leading and trailing whitespace or specified characters from `string`.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to trim.
     * @param {string} [chars=whitespace] The characters to trim.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {string} Returns the trimmed string.
     * @example
     *
     * _.trim('  abc  ');
     * // => 'abc'
     *
     * _.trim('-_-abc-_-', '_-');
     * // => 'abc'
     *
     * _.map(['  foo  ', '  bar  '], _.trim);
     * // => ['foo', 'bar']
     */function trim(string,chars,guard){string=toString(string);if(string&&(guard||chars===undefined)){return baseTrim(string);}if(!string||!(chars=baseToString(chars))){return string;}var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join('');}/**
     * Removes trailing whitespace or specified characters from `string`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to trim.
     * @param {string} [chars=whitespace] The characters to trim.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {string} Returns the trimmed string.
     * @example
     *
     * _.trimEnd('  abc  ');
     * // => '  abc'
     *
     * _.trimEnd('-_-abc-_-', '_-');
     * // => '-_-abc'
     */function trimEnd(string,chars,guard){string=toString(string);if(string&&(guard||chars===undefined)){return string.slice(0,trimmedEndIndex(string)+1);}if(!string||!(chars=baseToString(chars))){return string;}var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join('');}/**
     * Removes leading whitespace or specified characters from `string`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to trim.
     * @param {string} [chars=whitespace] The characters to trim.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {string} Returns the trimmed string.
     * @example
     *
     * _.trimStart('  abc  ');
     * // => 'abc  '
     *
     * _.trimStart('-_-abc-_-', '_-');
     * // => 'abc-_-'
     */function trimStart(string,chars,guard){string=toString(string);if(string&&(guard||chars===undefined)){return string.replace(reTrimStart,'');}if(!string||!(chars=baseToString(chars))){return string;}var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join('');}/**
     * Truncates `string` if it's longer than the given maximum string length.
     * The last characters of the truncated string are replaced with the omission
     * string which defaults to "...".
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to truncate.
     * @param {Object} [options={}] The options object.
     * @param {number} [options.length=30] The maximum string length.
     * @param {string} [options.omission='...'] The string to indicate text is omitted.
     * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
     * @returns {string} Returns the truncated string.
     * @example
     *
     * _.truncate('hi-diddly-ho there, neighborino');
     * // => 'hi-diddly-ho there, neighbo...'
     *
     * _.truncate('hi-diddly-ho there, neighborino', {
     *   'length': 24,
     *   'separator': ' '
     * });
     * // => 'hi-diddly-ho there,...'
     *
     * _.truncate('hi-diddly-ho there, neighborino', {
     *   'length': 24,
     *   'separator': /,? +/
     * });
     * // => 'hi-diddly-ho there...'
     *
     * _.truncate('hi-diddly-ho there, neighborino', {
     *   'omission': ' [...]'
     * });
     * // => 'hi-diddly-ho there, neig [...]'
     */function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator='separator'in options?options.separator:separator;length='length'in options?toInteger(options.length):length;omission='omission'in options?baseToString(options.omission):omission;}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length;}if(length>=strLength){return string;}var end=length-stringSize(omission);if(end<1){return omission;}var result=strSymbols?castSlice(strSymbols,0,end).join(''):string.slice(0,end);if(separator===undefined){return result+omission;}if(strSymbols){end+=result.length-end;}if(isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;if(!separator.global){separator=RegExp(separator.source,toString(reFlags.exec(separator))+'g');}separator.lastIndex=0;while(match=separator.exec(substring)){var newEnd=match.index;}result=result.slice(0,newEnd===undefined?end:newEnd);}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);if(index>-1){result=result.slice(0,index);}}return result+omission;}/**
     * The inverse of `_.escape`; this method converts the HTML entities
     * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to
     * their corresponding characters.
     *
     * **Note:** No other HTML entities are unescaped. To unescape additional
     * HTML entities use a third-party library like [_he_](https://mths.be/he).
     *
     * @static
     * @memberOf _
     * @since 0.6.0
     * @category String
     * @param {string} [string=''] The string to unescape.
     * @returns {string} Returns the unescaped string.
     * @example
     *
     * _.unescape('fred, barney, &amp; pebbles');
     * // => 'fred, barney, & pebbles'
     */function unescape(string){string=toString(string);return string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string;}/**
     * Converts `string`, as space separated words, to upper case.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the upper cased string.
     * @example
     *
     * _.upperCase('--foo-bar');
     * // => 'FOO BAR'
     *
     * _.upperCase('fooBar');
     * // => 'FOO BAR'
     *
     * _.upperCase('__foo_bar__');
     * // => 'FOO BAR'
     */var upperCase=createCompounder(function(result,word,index){return result+(index?' ':'')+word.toUpperCase();});/**
     * Converts the first character of `string` to upper case.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the converted string.
     * @example
     *
     * _.upperFirst('fred');
     * // => 'Fred'
     *
     * _.upperFirst('FRED');
     * // => 'FRED'
     */var upperFirst=createCaseFirst('toUpperCase');/**
     * Splits `string` into an array of its words.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to inspect.
     * @param {RegExp|string} [pattern] The pattern to match words.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Array} Returns the words of `string`.
     * @example
     *
     * _.words('fred, barney, & pebbles');
     * // => ['fred', 'barney', 'pebbles']
     *
     * _.words('fred, barney, & pebbles', /[^, ]+/g);
     * // => ['fred', 'barney', '&', 'pebbles']
     */function words(string,pattern,guard){string=toString(string);pattern=guard?undefined:pattern;if(pattern===undefined){return hasUnicodeWord(string)?unicodeWords(string):asciiWords(string);}return string.match(pattern)||[];}/*------------------------------------------------------------------------*/ /**
     * Attempts to invoke `func`, returning either the result or the caught error
     * object. Any additional arguments are provided to `func` when it's invoked.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Util
     * @param {Function} func The function to attempt.
     * @param {...*} [args] The arguments to invoke `func` with.
     * @returns {*} Returns the `func` result or error object.
     * @example
     *
     * // Avoid throwing errors for invalid selectors.
     * var elements = _.attempt(function(selector) {
     *   return document.querySelectorAll(selector);
     * }, '>_>');
     *
     * if (_.isError(elements)) {
     *   elements = [];
     * }
     */var attempt=baseRest(function(func,args){try{return apply(func,undefined,args);}catch(e){return isError(e)?e:new Error(e);}});/**
     * Binds methods of an object to the object itself, overwriting the existing
     * method.
     *
     * **Note:** This method doesn't set the "length" property of bound functions.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Util
     * @param {Object} object The object to bind and assign the bound methods to.
     * @param {...(string|string[])} methodNames The object method names to bind.
     * @returns {Object} Returns `object`.
     * @example
     *
     * var view = {
     *   'label': 'docs',
     *   'click': function() {
     *     console.log('clicked ' + this.label);
     *   }
     * };
     *
     * _.bindAll(view, ['click']);
     * jQuery(element).on('click', view.click);
     * // => Logs 'clicked docs' when clicked.
     */var bindAll=flatRest(function(object,methodNames){arrayEach(methodNames,function(key){key=toKey(key);baseAssignValue(object,key,bind(object[key],object));});return object;});/**
     * Creates a function that iterates over `pairs` and invokes the corresponding
     * function of the first predicate to return truthy. The predicate-function
     * pairs are invoked with the `this` binding and arguments of the created
     * function.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {Array} pairs The predicate-function pairs.
     * @returns {Function} Returns the new composite function.
     * @example
     *
     * var func = _.cond([
     *   [_.matches({ 'a': 1 }),           _.constant('matches A')],
     *   [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
     *   [_.stubTrue,                      _.constant('no match')]
     * ]);
     *
     * func({ 'a': 1, 'b': 2 });
     * // => 'matches A'
     *
     * func({ 'a': 0, 'b': 1 });
     * // => 'matches B'
     *
     * func({ 'a': '1', 'b': '2' });
     * // => 'no match'
     */function cond(pairs){var length=pairs==null?0:pairs.length,toIteratee=getIteratee();pairs=!length?[]:arrayMap(pairs,function(pair){if(typeof pair[1]!='function'){throw new TypeError(FUNC_ERROR_TEXT);}return[toIteratee(pair[0]),pair[1]];});return baseRest(function(args){var index=-1;while(++index<length){var pair=pairs[index];if(apply(pair[0],this,args)){return apply(pair[1],this,args);}}});}/**
     * Creates a function that invokes the predicate properties of `source` with
     * the corresponding property values of a given object, returning `true` if
     * all predicates return truthy, else `false`.
     *
     * **Note:** The created function is equivalent to `_.conformsTo` with
     * `source` partially applied.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {Object} source The object of property predicates to conform to.
     * @returns {Function} Returns the new spec function.
     * @example
     *
     * var objects = [
     *   { 'a': 2, 'b': 1 },
     *   { 'a': 1, 'b': 2 }
     * ];
     *
     * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
     * // => [{ 'a': 1, 'b': 2 }]
     */function conforms(source){return baseConforms(baseClone(source,CLONE_DEEP_FLAG));}/**
     * Creates a function that returns `value`.
     *
     * @static
     * @memberOf _
     * @since 2.4.0
     * @category Util
     * @param {*} value The value to return from the new function.
     * @returns {Function} Returns the new constant function.
     * @example
     *
     * var objects = _.times(2, _.constant({ 'a': 1 }));
     *
     * console.log(objects);
     * // => [{ 'a': 1 }, { 'a': 1 }]
     *
     * console.log(objects[0] === objects[1]);
     * // => true
     */function constant(value){return function(){return value;};}/**
     * Checks `value` to determine whether a default value should be returned in
     * its place. The `defaultValue` is returned if `value` is `NaN`, `null`,
     * or `undefined`.
     *
     * @static
     * @memberOf _
     * @since 4.14.0
     * @category Util
     * @param {*} value The value to check.
     * @param {*} defaultValue The default value.
     * @returns {*} Returns the resolved value.
     * @example
     *
     * _.defaultTo(1, 10);
     * // => 1
     *
     * _.defaultTo(undefined, 10);
     * // => 10
     */function defaultTo(value,defaultValue){return value==null||value!==value?defaultValue:value;}/**
     * Creates a function that returns the result of invoking the given functions
     * with the `this` binding of the created function, where each successive
     * invocation is supplied the return value of the previous.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Util
     * @param {...(Function|Function[])} [funcs] The functions to invoke.
     * @returns {Function} Returns the new composite function.
     * @see _.flowRight
     * @example
     *
     * function square(n) {
     *   return n * n;
     * }
     *
     * var addSquare = _.flow([_.add, square]);
     * addSquare(1, 2);
     * // => 9
     */var flow=createFlow();/**
     * This method is like `_.flow` except that it creates a function that
     * invokes the given functions from right to left.
     *
     * @static
     * @since 3.0.0
     * @memberOf _
     * @category Util
     * @param {...(Function|Function[])} [funcs] The functions to invoke.
     * @returns {Function} Returns the new composite function.
     * @see _.flow
     * @example
     *
     * function square(n) {
     *   return n * n;
     * }
     *
     * var addSquare = _.flowRight([square, _.add]);
     * addSquare(1, 2);
     * // => 9
     */var flowRight=createFlow(true);/**
     * This method returns the first argument it receives.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Util
     * @param {*} value Any value.
     * @returns {*} Returns `value`.
     * @example
     *
     * var object = { 'a': 1 };
     *
     * console.log(_.identity(object) === object);
     * // => true
     */function identity(value){return value;}/**
     * Creates a function that invokes `func` with the arguments of the created
     * function. If `func` is a property name, the created function returns the
     * property value for a given element. If `func` is an array or object, the
     * created function returns `true` for elements that contain the equivalent
     * source properties, otherwise it returns `false`.
     *
     * @static
     * @since 4.0.0
     * @memberOf _
     * @category Util
     * @param {*} [func=_.identity] The value to convert to a callback.
     * @returns {Function} Returns the callback.
     * @example
     *
     * var users = [
     *   { 'user': 'barney', 'age': 36, 'active': true },
     *   { 'user': 'fred',   'age': 40, 'active': false }
     * ];
     *
     * // The `_.matches` iteratee shorthand.
     * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
     * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.filter(users, _.iteratee(['user', 'fred']));
     * // => [{ 'user': 'fred', 'age': 40 }]
     *
     * // The `_.property` iteratee shorthand.
     * _.map(users, _.iteratee('user'));
     * // => ['barney', 'fred']
     *
     * // Create custom iteratee shorthands.
     * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
     *   return !_.isRegExp(func) ? iteratee(func) : function(string) {
     *     return func.test(string);
     *   };
     * });
     *
     * _.filter(['abc', 'def'], /ef/);
     * // => ['def']
     */function iteratee(func){return baseIteratee(typeof func=='function'?func:baseClone(func,CLONE_DEEP_FLAG));}/**
     * Creates a function that performs a partial deep comparison between a given
     * object and `source`, returning `true` if the given object has equivalent
     * property values, else `false`.
     *
     * **Note:** The created function is equivalent to `_.isMatch` with `source`
     * partially applied.
     *
     * Partial comparisons will match empty array and empty object `source`
     * values against any array or object value, respectively. See `_.isEqual`
     * for a list of supported value comparisons.
     *
     * **Note:** Multiple values can be checked by combining several matchers
     * using `_.overSome`
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Util
     * @param {Object} source The object of property values to match.
     * @returns {Function} Returns the new spec function.
     * @example
     *
     * var objects = [
     *   { 'a': 1, 'b': 2, 'c': 3 },
     *   { 'a': 4, 'b': 5, 'c': 6 }
     * ];
     *
     * _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
     * // => [{ 'a': 4, 'b': 5, 'c': 6 }]
     *
     * // Checking for several possible values
     * _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })]));
     * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
     */function matches(source){return baseMatches(baseClone(source,CLONE_DEEP_FLAG));}/**
     * Creates a function that performs a partial deep comparison between the
     * value at `path` of a given object to `srcValue`, returning `true` if the
     * object value is equivalent, else `false`.
     *
     * **Note:** Partial comparisons will match empty array and empty object
     * `srcValue` values against any array or object value, respectively. See
     * `_.isEqual` for a list of supported value comparisons.
     *
     * **Note:** Multiple values can be checked by combining several matchers
     * using `_.overSome`
     *
     * @static
     * @memberOf _
     * @since 3.2.0
     * @category Util
     * @param {Array|string} path The path of the property to get.
     * @param {*} srcValue The value to match.
     * @returns {Function} Returns the new spec function.
     * @example
     *
     * var objects = [
     *   { 'a': 1, 'b': 2, 'c': 3 },
     *   { 'a': 4, 'b': 5, 'c': 6 }
     * ];
     *
     * _.find(objects, _.matchesProperty('a', 4));
     * // => { 'a': 4, 'b': 5, 'c': 6 }
     *
     * // Checking for several possible values
     * _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)]));
     * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
     */function matchesProperty(path,srcValue){return baseMatchesProperty(path,baseClone(srcValue,CLONE_DEEP_FLAG));}/**
     * Creates a function that invokes the method at `path` of a given object.
     * Any additional arguments are provided to the invoked method.
     *
     * @static
     * @memberOf _
     * @since 3.7.0
     * @category Util
     * @param {Array|string} path The path of the method to invoke.
     * @param {...*} [args] The arguments to invoke the method with.
     * @returns {Function} Returns the new invoker function.
     * @example
     *
     * var objects = [
     *   { 'a': { 'b': _.constant(2) } },
     *   { 'a': { 'b': _.constant(1) } }
     * ];
     *
     * _.map(objects, _.method('a.b'));
     * // => [2, 1]
     *
     * _.map(objects, _.method(['a', 'b']));
     * // => [2, 1]
     */var method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args);};});/**
     * The opposite of `_.method`; this method creates a function that invokes
     * the method at a given path of `object`. Any additional arguments are
     * provided to the invoked method.
     *
     * @static
     * @memberOf _
     * @since 3.7.0
     * @category Util
     * @param {Object} object The object to query.
     * @param {...*} [args] The arguments to invoke the method with.
     * @returns {Function} Returns the new invoker function.
     * @example
     *
     * var array = _.times(3, _.constant),
     *     object = { 'a': array, 'b': array, 'c': array };
     *
     * _.map(['a[2]', 'c[0]'], _.methodOf(object));
     * // => [2, 0]
     *
     * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
     * // => [2, 0]
     */var methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args);};});/**
     * Adds all own enumerable string keyed function properties of a source
     * object to the destination object. If `object` is a function, then methods
     * are added to its prototype as well.
     *
     * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
     * avoid conflicts caused by modifying the original.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Util
     * @param {Function|Object} [object=lodash] The destination object.
     * @param {Object} source The object of functions to add.
     * @param {Object} [options={}] The options object.
     * @param {boolean} [options.chain=true] Specify whether mixins are chainable.
     * @returns {Function|Object} Returns `object`.
     * @example
     *
     * function vowels(string) {
     *   return _.filter(string, function(v) {
     *     return /[aeiou]/i.test(v);
     *   });
     * }
     *
     * _.mixin({ 'vowels': vowels });
     * _.vowels('fred');
     * // => ['e']
     *
     * _('fred').vowels().value();
     * // => ['e']
     *
     * _.mixin({ 'vowels': vowels }, { 'chain': false });
     * _('fred').vowels();
     * // => ['e']
     */function mixin(object,source,options){var props=keys(source),methodNames=baseFunctions(source,props);if(options==null&&!(isObject(source)&&(methodNames.length||!props.length))){options=source;source=object;object=this;methodNames=baseFunctions(source,keys(source));}var chain=!(isObject(options)&&'chain'in options)||!!options.chain,isFunc=isFunction(object);arrayEach(methodNames,function(methodName){var func=source[methodName];object[methodName]=func;if(isFunc){object.prototype[methodName]=function(){var chainAll=this.__chain__;if(chain||chainAll){var result=object(this.__wrapped__),actions=result.__actions__=copyArray(this.__actions__);actions.push({'func':func,'args':arguments,'thisArg':object});result.__chain__=chainAll;return result;}return func.apply(object,arrayPush([this.value()],arguments));};}});return object;}/**
     * Reverts the `_` variable to its previous value and returns a reference to
     * the `lodash` function.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Util
     * @returns {Function} Returns the `lodash` function.
     * @example
     *
     * var lodash = _.noConflict();
     */function noConflict(){if(root._===this){root._=oldDash;}return this;}/**
     * This method returns `undefined`.
     *
     * @static
     * @memberOf _
     * @since 2.3.0
     * @category Util
     * @example
     *
     * _.times(2, _.noop);
     * // => [undefined, undefined]
     */function noop(){// No operation performed.
}/**
     * Creates a function that gets the argument at index `n`. If `n` is negative,
     * the nth argument from the end is returned.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {number} [n=0] The index of the argument to return.
     * @returns {Function} Returns the new pass-thru function.
     * @example
     *
     * var func = _.nthArg(1);
     * func('a', 'b', 'c', 'd');
     * // => 'b'
     *
     * var func = _.nthArg(-2);
     * func('a', 'b', 'c', 'd');
     * // => 'c'
     */function nthArg(n){n=toInteger(n);return baseRest(function(args){return baseNth(args,n);});}/**
     * Creates a function that invokes `iteratees` with the arguments it receives
     * and returns their results.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {...(Function|Function[])} [iteratees=[_.identity]]
     *  The iteratees to invoke.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var func = _.over([Math.max, Math.min]);
     *
     * func(1, 2, 3, 4);
     * // => [4, 1]
     */var over=createOver(arrayMap);/**
     * Creates a function that checks if **all** of the `predicates` return
     * truthy when invoked with the arguments it receives.
     *
     * Following shorthands are possible for providing predicates.
     * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
     * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {...(Function|Function[])} [predicates=[_.identity]]
     *  The predicates to check.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var func = _.overEvery([Boolean, isFinite]);
     *
     * func('1');
     * // => true
     *
     * func(null);
     * // => false
     *
     * func(NaN);
     * // => false
     */var overEvery=createOver(arrayEvery);/**
     * Creates a function that checks if **any** of the `predicates` return
     * truthy when invoked with the arguments it receives.
     *
     * Following shorthands are possible for providing predicates.
     * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
     * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {...(Function|Function[])} [predicates=[_.identity]]
     *  The predicates to check.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var func = _.overSome([Boolean, isFinite]);
     *
     * func('1');
     * // => true
     *
     * func(null);
     * // => true
     *
     * func(NaN);
     * // => false
     *
     * var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }])
     * var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]])
     */var overSome=createOver(arraySome);/**
     * Creates a function that returns the value at `path` of a given object.
     *
     * @static
     * @memberOf _
     * @since 2.4.0
     * @category Util
     * @param {Array|string} path The path of the property to get.
     * @returns {Function} Returns the new accessor function.
     * @example
     *
     * var objects = [
     *   { 'a': { 'b': 2 } },
     *   { 'a': { 'b': 1 } }
     * ];
     *
     * _.map(objects, _.property('a.b'));
     * // => [2, 1]
     *
     * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
     * // => [1, 2]
     */function property(path){return isKey(path)?baseProperty(toKey(path)):basePropertyDeep(path);}/**
     * The opposite of `_.property`; this method creates a function that returns
     * the value at a given path of `object`.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Util
     * @param {Object} object The object to query.
     * @returns {Function} Returns the new accessor function.
     * @example
     *
     * var array = [0, 1, 2],
     *     object = { 'a': array, 'b': array, 'c': array };
     *
     * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
     * // => [2, 0]
     *
     * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
     * // => [2, 0]
     */function propertyOf(object){return function(path){return object==null?undefined:baseGet(object,path);};}/**
     * Creates an array of numbers (positive and/or negative) progressing from
     * `start` up to, but not including, `end`. A step of `-1` is used if a negative
     * `start` is specified without an `end` or `step`. If `end` is not specified,
     * it's set to `start` with `start` then set to `0`.
     *
     * **Note:** JavaScript follows the IEEE-754 standard for resolving
     * floating-point values which can produce unexpected results.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Util
     * @param {number} [start=0] The start of the range.
     * @param {number} end The end of the range.
     * @param {number} [step=1] The value to increment or decrement by.
     * @returns {Array} Returns the range of numbers.
     * @see _.inRange, _.rangeRight
     * @example
     *
     * _.range(4);
     * // => [0, 1, 2, 3]
     *
     * _.range(-4);
     * // => [0, -1, -2, -3]
     *
     * _.range(1, 5);
     * // => [1, 2, 3, 4]
     *
     * _.range(0, 20, 5);
     * // => [0, 5, 10, 15]
     *
     * _.range(0, -4, -1);
     * // => [0, -1, -2, -3]
     *
     * _.range(1, 4, 0);
     * // => [1, 1, 1]
     *
     * _.range(0);
     * // => []
     */var range=createRange();/**
     * This method is like `_.range` except that it populates values in
     * descending order.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {number} [start=0] The start of the range.
     * @param {number} end The end of the range.
     * @param {number} [step=1] The value to increment or decrement by.
     * @returns {Array} Returns the range of numbers.
     * @see _.inRange, _.range
     * @example
     *
     * _.rangeRight(4);
     * // => [3, 2, 1, 0]
     *
     * _.rangeRight(-4);
     * // => [-3, -2, -1, 0]
     *
     * _.rangeRight(1, 5);
     * // => [4, 3, 2, 1]
     *
     * _.rangeRight(0, 20, 5);
     * // => [15, 10, 5, 0]
     *
     * _.rangeRight(0, -4, -1);
     * // => [-3, -2, -1, 0]
     *
     * _.rangeRight(1, 4, 0);
     * // => [1, 1, 1]
     *
     * _.rangeRight(0);
     * // => []
     */var rangeRight=createRange(true);/**
     * This method returns a new empty array.
     *
     * @static
     * @memberOf _
     * @since 4.13.0
     * @category Util
     * @returns {Array} Returns the new empty array.
     * @example
     *
     * var arrays = _.times(2, _.stubArray);
     *
     * console.log(arrays);
     * // => [[], []]
     *
     * console.log(arrays[0] === arrays[1]);
     * // => false
     */function stubArray(){return[];}/**
     * This method returns `false`.
     *
     * @static
     * @memberOf _
     * @since 4.13.0
     * @category Util
     * @returns {boolean} Returns `false`.
     * @example
     *
     * _.times(2, _.stubFalse);
     * // => [false, false]
     */function stubFalse(){return false;}/**
     * This method returns a new empty object.
     *
     * @static
     * @memberOf _
     * @since 4.13.0
     * @category Util
     * @returns {Object} Returns the new empty object.
     * @example
     *
     * var objects = _.times(2, _.stubObject);
     *
     * console.log(objects);
     * // => [{}, {}]
     *
     * console.log(objects[0] === objects[1]);
     * // => false
     */function stubObject(){return{};}/**
     * This method returns an empty string.
     *
     * @static
     * @memberOf _
     * @since 4.13.0
     * @category Util
     * @returns {string} Returns the empty string.
     * @example
     *
     * _.times(2, _.stubString);
     * // => ['', '']
     */function stubString(){return'';}/**
     * This method returns `true`.
     *
     * @static
     * @memberOf _
     * @since 4.13.0
     * @category Util
     * @returns {boolean} Returns `true`.
     * @example
     *
     * _.times(2, _.stubTrue);
     * // => [true, true]
     */function stubTrue(){return true;}/**
     * Invokes the iteratee `n` times, returning an array of the results of
     * each invocation. The iteratee is invoked with one argument; (index).
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Util
     * @param {number} n The number of times to invoke `iteratee`.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the array of results.
     * @example
     *
     * _.times(3, String);
     * // => ['0', '1', '2']
     *
     *  _.times(4, _.constant(0));
     * // => [0, 0, 0, 0]
     */function times(n,iteratee){n=toInteger(n);if(n<1||n>MAX_SAFE_INTEGER){return[];}var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee);n-=MAX_ARRAY_LENGTH;var result=baseTimes(length,iteratee);while(++index<n){iteratee(index);}return result;}/**
     * Converts `value` to a property path array.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {*} value The value to convert.
     * @returns {Array} Returns the new property path array.
     * @example
     *
     * _.toPath('a.b.c');
     * // => ['a', 'b', 'c']
     *
     * _.toPath('a[0].b.c');
     * // => ['a', '0', 'b', 'c']
     */function toPath(value){if(isArray(value)){return arrayMap(value,toKey);}return isSymbol(value)?[value]:copyArray(stringToPath(toString(value)));}/**
     * Generates a unique ID. If `prefix` is given, the ID is appended to it.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Util
     * @param {string} [prefix=''] The value to prefix the ID with.
     * @returns {string} Returns the unique ID.
     * @example
     *
     * _.uniqueId('contact_');
     * // => 'contact_104'
     *
     * _.uniqueId();
     * // => '105'
     */function uniqueId(prefix){var id=++idCounter;return toString(prefix)+id;}/*------------------------------------------------------------------------*/ /**
     * Adds two numbers.
     *
     * @static
     * @memberOf _
     * @since 3.4.0
     * @category Math
     * @param {number} augend The first number in an addition.
     * @param {number} addend The second number in an addition.
     * @returns {number} Returns the total.
     * @example
     *
     * _.add(6, 4);
     * // => 10
     */var add=createMathOperation(function(augend,addend){return augend+addend;},0);/**
     * Computes `number` rounded up to `precision`.
     *
     * @static
     * @memberOf _
     * @since 3.10.0
     * @category Math
     * @param {number} number The number to round up.
     * @param {number} [precision=0] The precision to round up to.
     * @returns {number} Returns the rounded up number.
     * @example
     *
     * _.ceil(4.006);
     * // => 5
     *
     * _.ceil(6.004, 2);
     * // => 6.01
     *
     * _.ceil(6040, -2);
     * // => 6100
     */var ceil=createRound('ceil');/**
     * Divide two numbers.
     *
     * @static
     * @memberOf _
     * @since 4.7.0
     * @category Math
     * @param {number} dividend The first number in a division.
     * @param {number} divisor The second number in a division.
     * @returns {number} Returns the quotient.
     * @example
     *
     * _.divide(6, 4);
     * // => 1.5
     */var divide=createMathOperation(function(dividend,divisor){return dividend/divisor;},1);/**
     * Computes `number` rounded down to `precision`.
     *
     * @static
     * @memberOf _
     * @since 3.10.0
     * @category Math
     * @param {number} number The number to round down.
     * @param {number} [precision=0] The precision to round down to.
     * @returns {number} Returns the rounded down number.
     * @example
     *
     * _.floor(4.006);
     * // => 4
     *
     * _.floor(0.046, 2);
     * // => 0.04
     *
     * _.floor(4060, -2);
     * // => 4000
     */var floor=createRound('floor');/**
     * Computes the maximum value of `array`. If `array` is empty or falsey,
     * `undefined` is returned.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Math
     * @param {Array} array The array to iterate over.
     * @returns {*} Returns the maximum value.
     * @example
     *
     * _.max([4, 2, 8, 6]);
     * // => 8
     *
     * _.max([]);
     * // => undefined
     */function max(array){return array&&array.length?baseExtremum(array,identity,baseGt):undefined;}/**
     * This method is like `_.max` except that it accepts `iteratee` which is
     * invoked for each element in `array` to generate the criterion by which
     * the value is ranked. The iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Math
     * @param {Array} array The array to iterate over.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {*} Returns the maximum value.
     * @example
     *
     * var objects = [{ 'n': 1 }, { 'n': 2 }];
     *
     * _.maxBy(objects, function(o) { return o.n; });
     * // => { 'n': 2 }
     *
     * // The `_.property` iteratee shorthand.
     * _.maxBy(objects, 'n');
     * // => { 'n': 2 }
     */function maxBy(array,iteratee){return array&&array.length?baseExtremum(array,getIteratee(iteratee,2),baseGt):undefined;}/**
     * Computes the mean of the values in `array`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Math
     * @param {Array} array The array to iterate over.
     * @returns {number} Returns the mean.
     * @example
     *
     * _.mean([4, 2, 8, 6]);
     * // => 5
     */function mean(array){return baseMean(array,identity);}/**
     * This method is like `_.mean` except that it accepts `iteratee` which is
     * invoked for each element in `array` to generate the value to be averaged.
     * The iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.7.0
     * @category Math
     * @param {Array} array The array to iterate over.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {number} Returns the mean.
     * @example
     *
     * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
     *
     * _.meanBy(objects, function(o) { return o.n; });
     * // => 5
     *
     * // The `_.property` iteratee shorthand.
     * _.meanBy(objects, 'n');
     * // => 5
     */function meanBy(array,iteratee){return baseMean(array,getIteratee(iteratee,2));}/**
     * Computes the minimum value of `array`. If `array` is empty or falsey,
     * `undefined` is returned.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Math
     * @param {Array} array The array to iterate over.
     * @returns {*} Returns the minimum value.
     * @example
     *
     * _.min([4, 2, 8, 6]);
     * // => 2
     *
     * _.min([]);
     * // => undefined
     */function min(array){return array&&array.length?baseExtremum(array,identity,baseLt):undefined;}/**
     * This method is like `_.min` except that it accepts `iteratee` which is
     * invoked for each element in `array` to generate the criterion by which
     * the value is ranked. The iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Math
     * @param {Array} array The array to iterate over.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {*} Returns the minimum value.
     * @example
     *
     * var objects = [{ 'n': 1 }, { 'n': 2 }];
     *
     * _.minBy(objects, function(o) { return o.n; });
     * // => { 'n': 1 }
     *
     * // The `_.property` iteratee shorthand.
     * _.minBy(objects, 'n');
     * // => { 'n': 1 }
     */function minBy(array,iteratee){return array&&array.length?baseExtremum(array,getIteratee(iteratee,2),baseLt):undefined;}/**
     * Multiply two numbers.
     *
     * @static
     * @memberOf _
     * @since 4.7.0
     * @category Math
     * @param {number} multiplier The first number in a multiplication.
     * @param {number} multiplicand The second number in a multiplication.
     * @returns {number} Returns the product.
     * @example
     *
     * _.multiply(6, 4);
     * // => 24
     */var multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand;},1);/**
     * Computes `number` rounded to `precision`.
     *
     * @static
     * @memberOf _
     * @since 3.10.0
     * @category Math
     * @param {number} number The number to round.
     * @param {number} [precision=0] The precision to round to.
     * @returns {number} Returns the rounded number.
     * @example
     *
     * _.round(4.006);
     * // => 4
     *
     * _.round(4.006, 2);
     * // => 4.01
     *
     * _.round(4060, -2);
     * // => 4100
     */var round=createRound('round');/**
     * Subtract two numbers.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Math
     * @param {number} minuend The first number in a subtraction.
     * @param {number} subtrahend The second number in a subtraction.
     * @returns {number} Returns the difference.
     * @example
     *
     * _.subtract(6, 4);
     * // => 2
     */var subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend;},0);/**
     * Computes the sum of the values in `array`.
     *
     * @static
     * @memberOf _
     * @since 3.4.0
     * @category Math
     * @param {Array} array The array to iterate over.
     * @returns {number} Returns the sum.
     * @example
     *
     * _.sum([4, 2, 8, 6]);
     * // => 20
     */function sum(array){return array&&array.length?baseSum(array,identity):0;}/**
     * This method is like `_.sum` except that it accepts `iteratee` which is
     * invoked for each element in `array` to generate the value to be summed.
     * The iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Math
     * @param {Array} array The array to iterate over.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {number} Returns the sum.
     * @example
     *
     * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
     *
     * _.sumBy(objects, function(o) { return o.n; });
     * // => 20
     *
     * // The `_.property` iteratee shorthand.
     * _.sumBy(objects, 'n');
     * // => 20
     */function sumBy(array,iteratee){return array&&array.length?baseSum(array,getIteratee(iteratee,2)):0;}/*------------------------------------------------------------------------*/ // Add methods that return wrapped values in chain sequences.
lodash.after=after;lodash.ary=ary;lodash.assign=assign;lodash.assignIn=assignIn;lodash.assignInWith=assignInWith;lodash.assignWith=assignWith;lodash.at=at;lodash.before=before;lodash.bind=bind;lodash.bindAll=bindAll;lodash.bindKey=bindKey;lodash.castArray=castArray;lodash.chain=chain;lodash.chunk=chunk;lodash.compact=compact;lodash.concat=concat;lodash.cond=cond;lodash.conforms=conforms;lodash.constant=constant;lodash.countBy=countBy;lodash.create=create;lodash.curry=curry;lodash.curryRight=curryRight;lodash.debounce=debounce;lodash.defaults=defaults;lodash.defaultsDeep=defaultsDeep;lodash.defer=defer;lodash.delay=delay;lodash.difference=difference;lodash.differenceBy=differenceBy;lodash.differenceWith=differenceWith;lodash.drop=drop;lodash.dropRight=dropRight;lodash.dropRightWhile=dropRightWhile;lodash.dropWhile=dropWhile;lodash.fill=fill;lodash.filter=filter;lodash.flatMap=flatMap;lodash.flatMapDeep=flatMapDeep;lodash.flatMapDepth=flatMapDepth;lodash.flatten=flatten;lodash.flattenDeep=flattenDeep;lodash.flattenDepth=flattenDepth;lodash.flip=flip;lodash.flow=flow;lodash.flowRight=flowRight;lodash.fromPairs=fromPairs;lodash.functions=functions;lodash.functionsIn=functionsIn;lodash.groupBy=groupBy;lodash.initial=initial;lodash.intersection=intersection;lodash.intersectionBy=intersectionBy;lodash.intersectionWith=intersectionWith;lodash.invert=invert;lodash.invertBy=invertBy;lodash.invokeMap=invokeMap;lodash.iteratee=iteratee;lodash.keyBy=keyBy;lodash.keys=keys;lodash.keysIn=keysIn;lodash.map=map;lodash.mapKeys=mapKeys;lodash.mapValues=mapValues;lodash.matches=matches;lodash.matchesProperty=matchesProperty;lodash.memoize=memoize;lodash.merge=merge;lodash.mergeWith=mergeWith;lodash.method=method;lodash.methodOf=methodOf;lodash.mixin=mixin;lodash.negate=negate;lodash.nthArg=nthArg;lodash.omit=omit;lodash.omitBy=omitBy;lodash.once=once;lodash.orderBy=orderBy;lodash.over=over;lodash.overArgs=overArgs;lodash.overEvery=overEvery;lodash.overSome=overSome;lodash.partial=partial;lodash.partialRight=partialRight;lodash.partition=partition;lodash.pick=pick;lodash.pickBy=pickBy;lodash.property=property;lodash.propertyOf=propertyOf;lodash.pull=pull;lodash.pullAll=pullAll;lodash.pullAllBy=pullAllBy;lodash.pullAllWith=pullAllWith;lodash.pullAt=pullAt;lodash.range=range;lodash.rangeRight=rangeRight;lodash.rearg=rearg;lodash.reject=reject;lodash.remove=remove;lodash.rest=rest;lodash.reverse=reverse;lodash.sampleSize=sampleSize;lodash.set=set;lodash.setWith=setWith;lodash.shuffle=shuffle;lodash.slice=slice;lodash.sortBy=sortBy;lodash.sortedUniq=sortedUniq;lodash.sortedUniqBy=sortedUniqBy;lodash.split=split;lodash.spread=spread;lodash.tail=tail;lodash.take=take;lodash.takeRight=takeRight;lodash.takeRightWhile=takeRightWhile;lodash.takeWhile=takeWhile;lodash.tap=tap;lodash.throttle=throttle;lodash.thru=thru;lodash.toArray=toArray;lodash.toPairs=toPairs;lodash.toPairsIn=toPairsIn;lodash.toPath=toPath;lodash.toPlainObject=toPlainObject;lodash.transform=transform;lodash.unary=unary;lodash.union=union;lodash.unionBy=unionBy;lodash.unionWith=unionWith;lodash.uniq=uniq;lodash.uniqBy=uniqBy;lodash.uniqWith=uniqWith;lodash.unset=unset;lodash.unzip=unzip;lodash.unzipWith=unzipWith;lodash.update=update;lodash.updateWith=updateWith;lodash.values=values;lodash.valuesIn=valuesIn;lodash.without=without;lodash.words=words;lodash.wrap=wrap;lodash.xor=xor;lodash.xorBy=xorBy;lodash.xorWith=xorWith;lodash.zip=zip;lodash.zipObject=zipObject;lodash.zipObjectDeep=zipObjectDeep;lodash.zipWith=zipWith;// Add aliases.
lodash.entries=toPairs;lodash.entriesIn=toPairsIn;lodash.extend=assignIn;lodash.extendWith=assignInWith;// Add methods to `lodash.prototype`.
mixin(lodash,lodash);/*------------------------------------------------------------------------*/ // Add methods that return unwrapped values in chain sequences.
lodash.add=add;lodash.attempt=attempt;lodash.camelCase=camelCase;lodash.capitalize=capitalize;lodash.ceil=ceil;lodash.clamp=clamp;lodash.clone=clone;lodash.cloneDeep=cloneDeep;lodash.cloneDeepWith=cloneDeepWith;lodash.cloneWith=cloneWith;lodash.conformsTo=conformsTo;lodash.deburr=deburr;lodash.defaultTo=defaultTo;lodash.divide=divide;lodash.endsWith=endsWith;lodash.eq=eq;lodash.escape=escape;lodash.escapeRegExp=escapeRegExp;lodash.every=every;lodash.find=find;lodash.findIndex=findIndex;lodash.findKey=findKey;lodash.findLast=findLast;lodash.findLastIndex=findLastIndex;lodash.findLastKey=findLastKey;lodash.floor=floor;lodash.forEach=forEach;lodash.forEachRight=forEachRight;lodash.forIn=forIn;lodash.forInRight=forInRight;lodash.forOwn=forOwn;lodash.forOwnRight=forOwnRight;lodash.get=get;lodash.gt=gt;lodash.gte=gte;lodash.has=has;lodash.hasIn=hasIn;lodash.head=head;lodash.identity=identity;lodash.includes=includes;lodash.indexOf=indexOf;lodash.inRange=inRange;lodash.invoke=invoke;lodash.isArguments=isArguments;lodash.isArray=isArray;lodash.isArrayBuffer=isArrayBuffer;lodash.isArrayLike=isArrayLike;lodash.isArrayLikeObject=isArrayLikeObject;lodash.isBoolean=isBoolean;lodash.isBuffer=isBuffer;lodash.isDate=isDate;lodash.isElement=isElement;lodash.isEmpty=isEmpty;lodash.isEqual=isEqual;lodash.isEqualWith=isEqualWith;lodash.isError=isError;lodash.isFinite=isFinite;lodash.isFunction=isFunction;lodash.isInteger=isInteger;lodash.isLength=isLength;lodash.isMap=isMap;lodash.isMatch=isMatch;lodash.isMatchWith=isMatchWith;lodash.isNaN=isNaN;lodash.isNative=isNative;lodash.isNil=isNil;lodash.isNull=isNull;lodash.isNumber=isNumber;lodash.isObject=isObject;lodash.isObjectLike=isObjectLike;lodash.isPlainObject=isPlainObject;lodash.isRegExp=isRegExp;lodash.isSafeInteger=isSafeInteger;lodash.isSet=isSet;lodash.isString=isString;lodash.isSymbol=isSymbol;lodash.isTypedArray=isTypedArray;lodash.isUndefined=isUndefined;lodash.isWeakMap=isWeakMap;lodash.isWeakSet=isWeakSet;lodash.join=join;lodash.kebabCase=kebabCase;lodash.last=last;lodash.lastIndexOf=lastIndexOf;lodash.lowerCase=lowerCase;lodash.lowerFirst=lowerFirst;lodash.lt=lt;lodash.lte=lte;lodash.max=max;lodash.maxBy=maxBy;lodash.mean=mean;lodash.meanBy=meanBy;lodash.min=min;lodash.minBy=minBy;lodash.stubArray=stubArray;lodash.stubFalse=stubFalse;lodash.stubObject=stubObject;lodash.stubString=stubString;lodash.stubTrue=stubTrue;lodash.multiply=multiply;lodash.nth=nth;lodash.noConflict=noConflict;lodash.noop=noop;lodash.now=now;lodash.pad=pad;lodash.padEnd=padEnd;lodash.padStart=padStart;lodash.parseInt=parseInt;lodash.random=random;lodash.reduce=reduce;lodash.reduceRight=reduceRight;lodash.repeat=repeat;lodash.replace=replace;lodash.result=result;lodash.round=round;lodash.runInContext=runInContext;lodash.sample=sample;lodash.size=size;lodash.snakeCase=snakeCase;lodash.some=some;lodash.sortedIndex=sortedIndex;lodash.sortedIndexBy=sortedIndexBy;lodash.sortedIndexOf=sortedIndexOf;lodash.sortedLastIndex=sortedLastIndex;lodash.sortedLastIndexBy=sortedLastIndexBy;lodash.sortedLastIndexOf=sortedLastIndexOf;lodash.startCase=startCase;lodash.startsWith=startsWith;lodash.subtract=subtract;lodash.sum=sum;lodash.sumBy=sumBy;lodash.template=template;lodash.times=times;lodash.toFinite=toFinite;lodash.toInteger=toInteger;lodash.toLength=toLength;lodash.toLower=toLower;lodash.toNumber=toNumber;lodash.toSafeInteger=toSafeInteger;lodash.toString=toString;lodash.toUpper=toUpper;lodash.trim=trim;lodash.trimEnd=trimEnd;lodash.trimStart=trimStart;lodash.truncate=truncate;lodash.unescape=unescape;lodash.uniqueId=uniqueId;lodash.upperCase=upperCase;lodash.upperFirst=upperFirst;// Add aliases.
lodash.each=forEach;lodash.eachRight=forEachRight;lodash.first=head;mixin(lodash,function(){var source={};baseForOwn(lodash,function(func,methodName){if(!hasOwnProperty.call(lodash.prototype,methodName)){source[methodName]=func;}});return source;}(),{'chain':false});/*------------------------------------------------------------------------*/ /**
     * The semantic version number.
     *
     * @static
     * @memberOf _
     * @type {string}
     */lodash.VERSION=VERSION;// Assign default placeholders.
arrayEach(['bind','bindKey','curry','curryRight','partial','partialRight'],function(methodName){lodash[methodName].placeholder=lodash;});// Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
arrayEach(['drop','take'],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.__filtered__&&!index?new LazyWrapper(this):this.clone();if(result.__filtered__){result.__takeCount__=nativeMin(n,result.__takeCount__);}else{result.__views__.push({'size':nativeMin(n,MAX_ARRAY_LENGTH),'type':methodName+(result.__dir__<0?'Right':'')});}return result;};LazyWrapper.prototype[methodName+'Right']=function(n){return this.reverse()[methodName](n).reverse();};});// Add `LazyWrapper` methods that accept an `iteratee` value.
arrayEach(['filter','map','takeWhile'],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();result.__iteratees__.push({'iteratee':getIteratee(iteratee,3),'type':type});result.__filtered__=result.__filtered__||isFilter;return result;};});// Add `LazyWrapper` methods for `_.head` and `_.last`.
arrayEach(['head','last'],function(methodName,index){var takeName='take'+(index?'Right':'');LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0];};});// Add `LazyWrapper` methods for `_.initial` and `_.tail`.
arrayEach(['initial','tail'],function(methodName,index){var dropName='drop'+(index?'':'Right');LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1);};});LazyWrapper.prototype.compact=function(){return this.filter(identity);};LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head();};LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate);};LazyWrapper.prototype.invokeMap=baseRest(function(path,args){if(typeof path=='function'){return new LazyWrapper(this);}return this.map(function(value){return baseInvoke(value,path,args);});});LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)));};LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;if(result.__filtered__&&(start>0||end<0)){return new LazyWrapper(result);}if(start<0){result=result.takeRight(-start);}else if(start){result=result.drop(start);}if(end!==undefined){end=toInteger(end);result=end<0?result.dropRight(-end):result.take(end-start);}return result;};LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse();};LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH);};// Add `LazyWrapper` methods to `lodash.prototype`.
baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?'take'+(methodName=='last'?'Right':''):methodName],retUnwrapped=isTaker||/^find/.test(methodName);if(!lodashFunc){return;}lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value);var interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result;};if(useLazy&&checkIteratee&&typeof iteratee=='function'&&iteratee.length!=1){// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy=useLazy=false;}var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);result.__actions__.push({'func':thru,'args':[interceptor],'thisArg':undefined});return new LodashWrapper(result,chainAll);}if(isUnwrapped&&onlyLazy){return func.apply(this,args);}result=this.thru(interceptor);return isUnwrapped?isTaker?result.value()[0]:result.value():result;};});// Add `Array` methods to `lodash.prototype`.
arrayEach(['pop','push','shift','sort','splice','unshift'],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?'tap':'thru',retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args);}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args);});};});// Map minified method names to their real names.
baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+'';if(!hasOwnProperty.call(realNames,key)){realNames[key]=[];}realNames[key].push({'name':methodName,'func':lodashFunc});}});realNames[createHybrid(undefined,WRAP_BIND_KEY_FLAG).name]=[{'name':'wrapper','func':undefined}];// Add methods to `LazyWrapper`.
LazyWrapper.prototype.clone=lazyClone;LazyWrapper.prototype.reverse=lazyReverse;LazyWrapper.prototype.value=lazyValue;// Add chain sequence methods to the `lodash` wrapper.
lodash.prototype.at=wrapperAt;lodash.prototype.chain=wrapperChain;lodash.prototype.commit=wrapperCommit;lodash.prototype.next=wrapperNext;lodash.prototype.plant=wrapperPlant;lodash.prototype.reverse=wrapperReverse;lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue;// Add lazy aliases.
lodash.prototype.first=lodash.prototype.head;if(symIterator){lodash.prototype[symIterator]=wrapperToIterator;}return lodash;};/*--------------------------------------------------------------------------*/ // Export lodash.
var _=runInContext();// Some AMD build optimizers, like r.js, check for condition patterns like:
if(true){// Expose Lodash on the global object to prevent errors when Lodash is
// loaded by a script tag in the presence of an AMD loader.
// See http://requirejs.org/docs/errors.html#mismatch for more details.
// Use `_.noConflict` to remove Lodash from the global object.
root._=_;// Define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module.
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function(){return _;}).call(exports, __webpack_require__, exports, module),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));}// Check for `exports` after `define` in case a build optimizer adds it.
else {}}).call(this);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(18), __webpack_require__(43)(module)))

/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


const atob = __webpack_require__(326);

const btoa = __webpack_require__(327);

module.exports = {
  atob,
  btoa
};

/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(335);

/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(349);

/***/ }),
/* 43 */
/***/ (function(module, exports) {

module.exports = function (module) {
  if (!module.webpackPolyfill) {
    module.deprecate = function () {};

    module.paths = []; // module.parent = undefined by default

    if (!module.children) module.children = [];
    Object.defineProperty(module, "loaded", {
      enumerable: true,
      get: function () {
        return module.l;
      }
    });
    Object.defineProperty(module, "id", {
      enumerable: true,
      get: function () {
        return module.i;
      }
    });
    module.webpackPolyfill = 1;
  }

  return module;
};

/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(20),
    isObjectLike = __webpack_require__(19);
/** `Object#toString` result references. */


var symbolTag = '[object Symbol]';
/**
 * Checks if `value` is classified as a `Symbol` primitive or object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
 * @example
 *
 * _.isSymbol(Symbol.iterator);
 * // => true
 *
 * _.isSymbol('abc');
 * // => false
 */

function isSymbol(value) {
  return typeof value == 'symbol' || isObjectLike(value) && baseGetTag(value) == symbolTag;
}

module.exports = isSymbol;

/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {

var root = __webpack_require__(9);
/** Built-in value references. */


var Symbol = root.Symbol;
module.exports = Symbol;

/***/ }),
/* 46 */
/***/ (function(module, exports) {

/**
 * Performs a
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * comparison between two values to determine if they are equivalent.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.eq(object, object);
 * // => true
 *
 * _.eq(object, other);
 * // => false
 *
 * _.eq('a', 'a');
 * // => true
 *
 * _.eq('a', Object('a'));
 * // => false
 *
 * _.eq(NaN, NaN);
 * // => true
 */
function eq(value, other) {
  return value === other || value !== value && other !== other;
}

module.exports = eq;

/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {

var baseCreate = __webpack_require__(71),
    isObject = __webpack_require__(16);
/**
 * Creates a function that produces an instance of `Ctor` regardless of
 * whether it was invoked as part of a `new` expression or by `call` or `apply`.
 *
 * @private
 * @param {Function} Ctor The constructor to wrap.
 * @returns {Function} Returns the new wrapped function.
 */


function createCtor(Ctor) {
  return function () {
    // Use a `switch` statement to work with class constructors. See
    // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
    // for more details.
    var args = arguments;

    switch (args.length) {
      case 0:
        return new Ctor();

      case 1:
        return new Ctor(args[0]);

      case 2:
        return new Ctor(args[0], args[1]);

      case 3:
        return new Ctor(args[0], args[1], args[2]);

      case 4:
        return new Ctor(args[0], args[1], args[2], args[3]);

      case 5:
        return new Ctor(args[0], args[1], args[2], args[3], args[4]);

      case 6:
        return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);

      case 7:
        return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
    }

    var thisBinding = baseCreate(Ctor.prototype),
        result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior.
    // See https://es5.github.io/#x13.2.2 for more details.

    return isObject(result) ? result : thisBinding;
  };
}

module.exports = createCtor;

/***/ }),
/* 48 */
/***/ (function(module, exports) {

/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/**
 * Replaces all `placeholder` elements in `array` with an internal placeholder
 * and returns an array of their indexes.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {*} placeholder The placeholder to replace.
 * @returns {Array} Returns the new array of placeholder indexes.
 */

function replaceHolders(array, placeholder) {
  var index = -1,
      length = array.length,
      resIndex = 0,
      result = [];

  while (++index < length) {
    var value = array[index];

    if (value === placeholder || value === PLACEHOLDER) {
      array[index] = PLACEHOLDER;
      result[resIndex++] = index;
    }
  }

  return result;
}

module.exports = replaceHolders;

/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {

var listCacheClear = __webpack_require__(386),
    listCacheDelete = __webpack_require__(387),
    listCacheGet = __webpack_require__(388),
    listCacheHas = __webpack_require__(389),
    listCacheSet = __webpack_require__(390);
/**
 * Creates an list cache object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */


function ListCache(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;
  this.clear();

  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
} // Add methods to `ListCache`.


ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
module.exports = ListCache;

/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {

var eq = __webpack_require__(46);
/**
 * Gets the index at which the `key` is found in `array` of key-value pairs.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} key The key to search for.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */


function assocIndexOf(array, key) {
  var length = array.length;

  while (length--) {
    if (eq(array[length][0], key)) {
      return length;
    }
  }

  return -1;
}

module.exports = assocIndexOf;

/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(21);
/* Built-in method references that are verified to be native. */


var nativeCreate = getNative(Object, 'create');
module.exports = nativeCreate;

/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {

var isKeyable = __webpack_require__(404);
/**
 * Gets the data for `map`.
 *
 * @private
 * @param {Object} map The map to query.
 * @param {string} key The reference key.
 * @returns {*} Returns the map data.
 */


function getMapData(map, key) {
  var data = map.__data__;
  return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
}

module.exports = getMapData;

/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {

var isArray = __webpack_require__(12),
    isKey = __webpack_require__(78),
    stringToPath = __webpack_require__(427),
    toString = __webpack_require__(135);
/**
 * Casts `value` to a path array if it's not one.
 *
 * @private
 * @param {*} value The value to inspect.
 * @param {Object} [object] The object to query keys on.
 * @returns {Array} Returns the cast property path array.
 */


function castPath(value, object) {
  if (isArray(value)) {
    return value;
  }

  return isKey(value, object) ? [value] : stringToPath(toString(value));
}

module.exports = castPath;

/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {

// optional / simple context binding
var aFunction = __webpack_require__(55);

module.exports = function (fn, that, length) {
  aFunction(fn);
  if (that === undefined) return fn;

  switch (length) {
    case 1:
      return function (a) {
        return fn.call(that, a);
      };

    case 2:
      return function (a, b) {
        return fn.call(that, a, b);
      };

    case 3:
      return function (a, b, c) {
        return fn.call(that, a, b, c);
      };
  }

  return function ()
  /* ...args */
  {
    return fn.apply(that, arguments);
  };
};

/***/ }),
/* 55 */
/***/ (function(module, exports) {

module.exports = function (it) {
  if (typeof it != 'function') throw TypeError(it + ' is not a function!');
  return it;
};

/***/ }),
/* 56 */
/***/ (function(module, exports) {

var hasOwnProperty = {}.hasOwnProperty;

module.exports = function (it, key) {
  return hasOwnProperty.call(it, key);
};

/***/ }),
/* 57 */
/***/ (function(module, exports) {

var toString = {}.toString;

module.exports = function (it) {
  return toString.call(it).slice(8, -1);
};

/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(20),
    isObject = __webpack_require__(16);
/** `Object#toString` result references. */


var asyncTag = '[object AsyncFunction]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]',
    proxyTag = '[object Proxy]';
/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */

function isFunction(value) {
  if (!isObject(value)) {
    return false;
  } // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 9 which returns 'object' for typed arrays and other constructors.


  var tag = baseGetTag(value);
  return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}

module.exports = isFunction;

/***/ }),
/* 59 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
/* harmony default export */ __webpack_exports__["a"] = (freeGlobal);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(18)))

/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {

/*!
 2020 Jason Mulligan <jason.mulligan@avoidwork.com>
 @version 6.3.0
*/
!function (e, t) {
   true ? module.exports = t() : undefined;
}(this, function () {
  "use strict";

  var e = /^(b|B)$/,
      t = {
    iec: {
      bits: ["b", "Kib", "Mib", "Gib", "Tib", "Pib", "Eib", "Zib", "Yib"],
      bytes: ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
    },
    jedec: {
      bits: ["b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb"],
      bytes: ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
    }
  },
      i = {
    iec: ["", "kibi", "mebi", "gibi", "tebi", "pebi", "exbi", "zebi", "yobi"],
    jedec: ["", "kilo", "mega", "giga", "tera", "peta", "exa", "zetta", "yotta"]
  },
      o = {
    floor: Math.floor,
    ceil: Math.ceil
  };

  function n(n) {
    var r,
        a,
        b,
        l,
        s,
        c,
        d,
        f,
        u,
        p,
        B,
        h,
        g,
        y,
        M,
        m,
        v,
        x,
        j,
        T,
        E = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {},
        N = [],
        w = 0;
    if (isNaN(n)) throw new TypeError("Invalid number");
    if (b = !0 === E.bits, M = !0 === E.unix, h = !0 === E.pad, a = E.base || 2, g = void 0 !== E.round ? E.round : M ? 1 : 2, d = void 0 !== E.locale ? E.locale : "", f = E.localeOptions || {}, m = void 0 !== E.separator ? E.separator : "", v = void 0 !== E.spacer ? E.spacer : M ? "" : " ", j = E.symbols || {}, x = 2 === a && E.standard || "jedec", B = E.output || "string", s = !0 === E.fullform, c = E.fullforms instanceof Array ? E.fullforms : [], r = void 0 !== E.exponent ? E.exponent : -1, T = o[E.roundingMethod] || Math.round, l = a > 2 ? 1e3 : 1024, (u = (p = Number(n)) < 0) && (p = -p), (-1 === r || isNaN(r)) && (r = Math.floor(Math.log(p) / Math.log(l))) < 0 && (r = 0), r > 8 && (r = 8), "exponent" === B) return r;
    if (0 === p) N[0] = 0, y = N[1] = M ? "" : t[x][b ? "bits" : "bytes"][r];else {
      w = p / (2 === a ? Math.pow(2, 10 * r) : Math.pow(1e3, r)), b && (w *= 8) >= l && r < 8 && (w /= l, r++);
      var k = Math.pow(10, r > 0 ? g : 0);
      N[0] = T(w * k) / k, N[0] === l && r < 8 && void 0 === E.exponent && (N[0] = 1, r++), y = N[1] = 10 === a && 1 === r ? b ? "kb" : "kB" : t[x][b ? "bits" : "bytes"][r], M && (N[1] = "jedec" === x ? N[1].charAt(0) : r > 0 ? N[1].replace(/B$/, "") : N[1], e.test(N[1]) && (N[0] = Math.floor(N[0]), N[1] = ""));
    }

    if (u && (N[0] = -N[0]), N[1] = j[N[1]] || N[1], !0 === d ? N[0] = N[0].toLocaleString() : d.length > 0 ? N[0] = N[0].toLocaleString(d, f) : m.length > 0 && (N[0] = N[0].toString().replace(".", m)), h && !1 === Number.isInteger(N[0]) && g > 0) {
      var G = m || ".",
          K = N[0].toString().split(G),
          P = K[1] || "",
          S = P.length,
          Y = g - S;
      N[0] = "".concat(K[0]).concat(G).concat(P.padEnd(S + Y, "0"));
    }

    return s && (N[1] = c[r] ? c[r] : i[x][r] + (b ? "bit" : "byte") + (1 === N[0] ? "" : "s")), "array" === B ? N : "object" === B ? {
      value: N[0],
      symbol: N[1],
      exponent: r,
      unit: y
    } : N.join(v);
  }

  return n.partial = function (e) {
    return function (t) {
      return n(t, e);
    };
  }, n;
});

/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
__p += '<!-- src/templates/form_input.html -->\n<div class="form-group">\n    ';
 if (o.type !== 'hidden') { ;
__p += '\n        <label for="' +
__e(o.id) +
'">' +
__e(o.label) +
'</label>\n    ';
 } ;
__p += '\n    ';
 if (o.type === 'password' && o.fixed_username) { ;
__p += '\n        <!-- This is a hack to prevent Chrome from auto-filling the username in\n            any of the other input fields in the MUC configuration form. -->\n        <input class="hidden-username" type="text" autocomplete="username" value="' +
__e(o.fixed_username) +
'"></input>\n    ';
 } ;
__p += '\n    <input \n        class="form-control" name="' +
__e(o.name) +
'" type="' +
__e(o.type) +
'" id="' +
__e(o.id) +
'"\n        ';
 if (o.autocomplete) { ;
__p += ' autocomplete="' +
__e(o.autocomplete) +
'" ';
 } ;
__p += '\n        ';
 if (o.placeholder) { ;
__p += ' placeholder="' +
__e(o.placeholder) +
'" ';
 } ;
__p += '\n        ';
 if (o.value) { ;
__p += ' value="' +
__e(o.value) +
'" ';
 } ;
__p += '\n        ';
 if (o.required) { ;
__p += ' required="required" ';
 } ;
__p += ' />\n</div>\n';
return __p
};

/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
__p += '<!-- src/templates/form_username.html -->\n<div class="form-group">\n    ';
 if (o.label) { ;
__p += '\n    <label>\n        ' +
__e(o.label) +
'\n    </label>\n    ';
 } ;
__p += '\n    <div class="input-group">\n        <div class="input-group-prepend">\n            <input name="' +
__e(o.name) +
'" type="' +
__e(o.type) +
'"\n                ';
 if (o.value) { ;
__p += ' value="' +
__e(o.value) +
'" ';
 } ;
__p += '\n                ';
 if (o.required) { ;
__p += ' required="required" ';
 } ;
__p += ' />\n            <div class="input-group-text col" title="' +
__e(o.domain) +
'">' +
__e(o.domain) +
'</div>\n        </div>\n    </div>\n</div>\n';
return __p
};

/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(39)], __WEBPACK_AMD_DEFINE_RESULT__ = (function (_) {
  return _.noConflict();
}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));

/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {

/**
 * @preserve jed.js https://github.com/SlexAxton/Jed
 */

/*
-----------
A gettext compatible i18n library for modern JavaScript Applications

by Alex Sexton - AlexSexton [at] gmail - @SlexAxton

MIT License

A jQuery Foundation project - requires CLA to contribute -
https://contribute.jquery.org/CLA/



Jed offers the entire applicable GNU gettext spec'd set of
functions, but also offers some nicer wrappers around them.
The api for gettext was written for a language with no function
overloading, so Jed allows a little more of that.

Many thanks to Joshua I. Miller - unrtst@cpan.org - who wrote
gettext.js back in 2008. I was able to vet a lot of my ideas
against his. I also made sure Jed passed against his tests
in order to offer easy upgrades -- jsgettext.berlios.de
*/
(function (root, undef) {
  // Set up some underscore-style functions, if you already have
  // underscore, feel free to delete this section, and use it
  // directly, however, the amount of functions used doesn't
  // warrant having underscore as a full dependency.
  // Underscore 1.3.0 was used to port and is licensed
  // under the MIT License by Jeremy Ashkenas.
  var ArrayProto = Array.prototype,
      ObjProto = Object.prototype,
      slice = ArrayProto.slice,
      hasOwnProp = ObjProto.hasOwnProperty,
      nativeForEach = ArrayProto.forEach,
      breaker = {}; // We're not using the OOP style _ so we don't need the
  // extra level of indirection. This still means that you
  // sub out for real `_` though.

  var _ = {
    forEach: function (obj, iterator, context) {
      var i, l, key;

      if (obj === null) {
        return;
      }

      if (nativeForEach && obj.forEach === nativeForEach) {
        obj.forEach(iterator, context);
      } else if (obj.length === +obj.length) {
        for (i = 0, l = obj.length; i < l; i++) {
          if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) {
            return;
          }
        }
      } else {
        for (key in obj) {
          if (hasOwnProp.call(obj, key)) {
            if (iterator.call(context, obj[key], key, obj) === breaker) {
              return;
            }
          }
        }
      }
    },
    extend: function (obj) {
      this.forEach(slice.call(arguments, 1), function (source) {
        for (var prop in source) {
          obj[prop] = source[prop];
        }
      });
      return obj;
    }
  }; // END Miniature underscore impl
  // Jed is a constructor function

  var Jed = function (options) {
    // Some minimal defaults
    this.defaults = {
      "locale_data": {
        "messages": {
          "": {
            "domain": "messages",
            "lang": "en",
            "plural_forms": "nplurals=2; plural=(n != 1);"
          } // There are no default keys, though

        }
      },
      // The default domain if one is missing
      "domain": "messages",
      // enable debug mode to log untranslated strings to the console
      "debug": false
    }; // Mix in the sent options with the default options

    this.options = _.extend({}, this.defaults, options);
    this.textdomain(this.options.domain);

    if (options.domain && !this.options.locale_data[this.options.domain]) {
      throw new Error('Text domain set to non-existent domain: `' + options.domain + '`');
    }
  }; // The gettext spec sets this character as the default
  // delimiter for context lookups.
  // e.g.: context\u0004key
  // If your translation company uses something different,
  // just change this at any time and it will use that instead.


  Jed.context_delimiter = String.fromCharCode(4);

  function getPluralFormFunc(plural_form_string) {
    return Jed.PF.compile(plural_form_string || "nplurals=2; plural=(n != 1);");
  }

  function Chain(key, i18n) {
    this._key = key;
    this._i18n = i18n;
  } // Create a chainable api for adding args prettily


  _.extend(Chain.prototype, {
    onDomain: function (domain) {
      this._domain = domain;
      return this;
    },
    withContext: function (context) {
      this._context = context;
      return this;
    },
    ifPlural: function (num, pkey) {
      this._val = num;
      this._pkey = pkey;
      return this;
    },
    fetch: function (sArr) {
      if ({}.toString.call(sArr) != '[object Array]') {
        sArr = [].slice.call(arguments, 0);
      }

      return (sArr && sArr.length ? Jed.sprintf : function (x) {
        return x;
      })(this._i18n.dcnpgettext(this._domain, this._context, this._key, this._pkey, this._val), sArr);
    }
  }); // Add functions to the Jed prototype.
  // These will be the functions on the object that's returned
  // from creating a `new Jed()`
  // These seem redundant, but they gzip pretty well.


  _.extend(Jed.prototype, {
    // The sexier api start point
    translate: function (key) {
      return new Chain(key, this);
    },
    textdomain: function (domain) {
      if (!domain) {
        return this._textdomain;
      }

      this._textdomain = domain;
    },
    gettext: function (key) {
      return this.dcnpgettext.call(this, undef, undef, key);
    },
    dgettext: function (domain, key) {
      return this.dcnpgettext.call(this, domain, undef, key);
    },
    dcgettext: function (domain, key
    /*, category */
    ) {
      // Ignores the category anyways
      return this.dcnpgettext.call(this, domain, undef, key);
    },
    ngettext: function (skey, pkey, val) {
      return this.dcnpgettext.call(this, undef, undef, skey, pkey, val);
    },
    dngettext: function (domain, skey, pkey, val) {
      return this.dcnpgettext.call(this, domain, undef, skey, pkey, val);
    },
    dcngettext: function (domain, skey, pkey, val
    /*, category */
    ) {
      return this.dcnpgettext.call(this, domain, undef, skey, pkey, val);
    },
    pgettext: function (context, key) {
      return this.dcnpgettext.call(this, undef, context, key);
    },
    dpgettext: function (domain, context, key) {
      return this.dcnpgettext.call(this, domain, context, key);
    },
    dcpgettext: function (domain, context, key
    /*, category */
    ) {
      return this.dcnpgettext.call(this, domain, context, key);
    },
    npgettext: function (context, skey, pkey, val) {
      return this.dcnpgettext.call(this, undef, context, skey, pkey, val);
    },
    dnpgettext: function (domain, context, skey, pkey, val) {
      return this.dcnpgettext.call(this, domain, context, skey, pkey, val);
    },
    // The most fully qualified gettext function. It has every option.
    // Since it has every option, we can use it from every other method.
    // This is the bread and butter.
    // Technically there should be one more argument in this function for 'Category',
    // but since we never use it, we might as well not waste the bytes to define it.
    dcnpgettext: function (domain, context, singular_key, plural_key, val) {
      // Set some defaults
      plural_key = plural_key || singular_key; // Use the global domain default if one
      // isn't explicitly passed in

      domain = domain || this._textdomain;
      var fallback; // Handle special cases
      // No options found

      if (!this.options) {
        // There's likely something wrong, but we'll return the correct key for english
        // We do this by instantiating a brand new Jed instance with the default set
        // for everything that could be broken.
        fallback = new Jed();
        return fallback.dcnpgettext.call(fallback, undefined, undefined, singular_key, plural_key, val);
      } // No translation data provided


      if (!this.options.locale_data) {
        throw new Error('No locale data provided.');
      }

      if (!this.options.locale_data[domain]) {
        throw new Error('Domain `' + domain + '` was not found.');
      }

      if (!this.options.locale_data[domain][""]) {
        throw new Error('No locale meta information provided.');
      } // Make sure we have a truthy key. Otherwise we might start looking
      // into the empty string key, which is the options for the locale
      // data.


      if (!singular_key) {
        throw new Error('No translation key found.');
      }

      var key = context ? context + Jed.context_delimiter + singular_key : singular_key,
          locale_data = this.options.locale_data,
          dict = locale_data[domain],
          defaultConf = (locale_data.messages || this.defaults.locale_data.messages)[""],
          pluralForms = dict[""].plural_forms || dict[""]["Plural-Forms"] || dict[""]["plural-forms"] || defaultConf.plural_forms || defaultConf["Plural-Forms"] || defaultConf["plural-forms"],
          val_list,
          res;
      var val_idx;

      if (val === undefined) {
        // No value passed in; assume singular key lookup.
        val_idx = 0;
      } else {
        // Value has been passed in; use plural-forms calculations.
        // Handle invalid numbers, but try casting strings for good measure
        if (typeof val != 'number') {
          val = parseInt(val, 10);

          if (isNaN(val)) {
            throw new Error('The number that was passed in is not a number.');
          }
        }

        val_idx = getPluralFormFunc(pluralForms)(val);
      } // Throw an error if a domain isn't found


      if (!dict) {
        throw new Error('No domain named `' + domain + '` could be found.');
      }

      val_list = dict[key]; // If there is no match, then revert back to
      // english style singular/plural with the keys passed in.

      if (!val_list || val_idx > val_list.length) {
        if (this.options.missing_key_callback) {
          this.options.missing_key_callback(key, domain);
        }

        res = [singular_key, plural_key]; // collect untranslated strings

        if (this.options.debug === true) {
          console.log(res[getPluralFormFunc(pluralForms)(val)]);
        }

        return res[getPluralFormFunc()(val)];
      }

      res = val_list[val_idx]; // This includes empty strings on purpose

      if (!res) {
        res = [singular_key, plural_key];
        return res[getPluralFormFunc()(val)];
      }

      return res;
    }
  }); // We add in sprintf capabilities for post translation value interolation
  // This is not internally used, so you can remove it if you have this
  // available somewhere else, or want to use a different system.
  // We _slightly_ modify the normal sprintf behavior to more gracefully handle
  // undefined values.

  /**
   sprintf() for JavaScript 0.7-beta1
   http://www.diveintojavascript.com/projects/javascript-sprintf
    Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com>
   All rights reserved.
    Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
       * Redistributions of source code must retain the above copyright
         notice, this list of conditions and the following disclaimer.
       * Redistributions in binary form must reproduce the above copyright
         notice, this list of conditions and the following disclaimer in the
         documentation and/or other materials provided with the distribution.
       * Neither the name of sprintf() for JavaScript nor the
         names of its contributors may be used to endorse or promote products
         derived from this software without specific prior written permission.
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL Alexandru Marasteanu BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */


  var sprintf = function () {
    function get_type(variable) {
      return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
    }

    function str_repeat(input, multiplier) {
      for (var output = []; multiplier > 0; output[--multiplier] = input) {
        /* do nothing */
      }

      return output.join('');
    }

    var str_format = function () {
      if (!str_format.cache.hasOwnProperty(arguments[0])) {
        str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
      }

      return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
    };

    str_format.format = function (parse_tree, argv) {
      var cursor = 1,
          tree_length = parse_tree.length,
          node_type = '',
          arg,
          output = [],
          i,
          k,
          match,
          pad,
          pad_character,
          pad_length;

      for (i = 0; i < tree_length; i++) {
        node_type = get_type(parse_tree[i]);

        if (node_type === 'string') {
          output.push(parse_tree[i]);
        } else if (node_type === 'array') {
          match = parse_tree[i]; // convenience purposes only

          if (match[2]) {
            // keyword argument
            arg = argv[cursor];

            for (k = 0; k < match[2].length; k++) {
              if (!arg.hasOwnProperty(match[2][k])) {
                throw sprintf('[sprintf] property "%s" does not exist', match[2][k]);
              }

              arg = arg[match[2][k]];
            }
          } else if (match[1]) {
            // positional argument (explicit)
            arg = argv[match[1]];
          } else {
            // positional argument (implicit)
            arg = argv[cursor++];
          }

          if (/[^s]/.test(match[8]) && get_type(arg) != 'number') {
            throw sprintf('[sprintf] expecting number but found %s', get_type(arg));
          } // Jed EDIT


          if (typeof arg == 'undefined' || arg === null) {
            arg = '';
          } // Jed EDIT


          switch (match[8]) {
            case 'b':
              arg = arg.toString(2);
              break;

            case 'c':
              arg = String.fromCharCode(arg);
              break;

            case 'd':
              arg = parseInt(arg, 10);
              break;

            case 'e':
              arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential();
              break;

            case 'f':
              arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg);
              break;

            case 'o':
              arg = arg.toString(8);
              break;

            case 's':
              arg = (arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg;
              break;

            case 'u':
              arg = Math.abs(arg);
              break;

            case 'x':
              arg = arg.toString(16);
              break;

            case 'X':
              arg = arg.toString(16).toUpperCase();
              break;
          }

          arg = /[def]/.test(match[8]) && match[3] && arg >= 0 ? '+' + arg : arg;
          pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
          pad_length = match[6] - String(arg).length;
          pad = match[6] ? str_repeat(pad_character, pad_length) : '';
          output.push(match[5] ? arg + pad : pad + arg);
        }
      }

      return output.join('');
    };

    str_format.cache = {};

    str_format.parse = function (fmt) {
      var _fmt = fmt,
          match = [],
          parse_tree = [],
          arg_names = 0;

      while (_fmt) {
        if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
          parse_tree.push(match[0]);
        } else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
          parse_tree.push('%');
        } else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
          if (match[2]) {
            arg_names |= 1;
            var field_list = [],
                replacement_field = match[2],
                field_match = [];

            if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
              field_list.push(field_match[1]);

              while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
                if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
                  field_list.push(field_match[1]);
                } else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
                  field_list.push(field_match[1]);
                } else {
                  throw '[sprintf] huh?';
                }
              }
            } else {
              throw '[sprintf] huh?';
            }

            match[2] = field_list;
          } else {
            arg_names |= 2;
          }

          if (arg_names === 3) {
            throw '[sprintf] mixing positional and named placeholders is not (yet) supported';
          }

          parse_tree.push(match);
        } else {
          throw '[sprintf] huh?';
        }

        _fmt = _fmt.substring(match[0].length);
      }

      return parse_tree;
    };

    return str_format;
  }();

  var vsprintf = function (fmt, argv) {
    argv.unshift(fmt);
    return sprintf.apply(null, argv);
  };

  Jed.parse_plural = function (plural_forms, n) {
    plural_forms = plural_forms.replace(/n/g, n);
    return Jed.parse_expression(plural_forms);
  };

  Jed.sprintf = function (fmt, args) {
    if ({}.toString.call(args) == '[object Array]') {
      return vsprintf(fmt, [].slice.call(args));
    }

    return sprintf.apply(this, [].slice.call(arguments));
  };

  Jed.prototype.sprintf = function () {
    return Jed.sprintf.apply(this, arguments);
  }; // END sprintf Implementation
  // Start the Plural forms section
  // This is a full plural form expression parser. It is used to avoid
  // running 'eval' or 'new Function' directly against the plural
  // forms.
  //
  // This can be important if you get translations done through a 3rd
  // party vendor. I encourage you to use this instead, however, I
  // also will provide a 'precompiler' that you can use at build time
  // to output valid/safe function representations of the plural form
  // expressions. This means you can build this code out for the most
  // part.


  Jed.PF = {};

  Jed.PF.parse = function (p) {
    var plural_str = Jed.PF.extractPluralExpr(p);
    return Jed.PF.parser.parse.call(Jed.PF.parser, plural_str);
  };

  Jed.PF.compile = function (p) {
    // Handle trues and falses as 0 and 1
    function imply(val) {
      return val === true ? 1 : val ? val : 0;
    }

    var ast = Jed.PF.parse(p);
    return function (n) {
      return imply(Jed.PF.interpreter(ast)(n));
    };
  };

  Jed.PF.interpreter = function (ast) {
    return function (n) {
      var res;

      switch (ast.type) {
        case 'GROUP':
          return Jed.PF.interpreter(ast.expr)(n);

        case 'TERNARY':
          if (Jed.PF.interpreter(ast.expr)(n)) {
            return Jed.PF.interpreter(ast.truthy)(n);
          }

          return Jed.PF.interpreter(ast.falsey)(n);

        case 'OR':
          return Jed.PF.interpreter(ast.left)(n) || Jed.PF.interpreter(ast.right)(n);

        case 'AND':
          return Jed.PF.interpreter(ast.left)(n) && Jed.PF.interpreter(ast.right)(n);

        case 'LT':
          return Jed.PF.interpreter(ast.left)(n) < Jed.PF.interpreter(ast.right)(n);

        case 'GT':
          return Jed.PF.interpreter(ast.left)(n) > Jed.PF.interpreter(ast.right)(n);

        case 'LTE':
          return Jed.PF.interpreter(ast.left)(n) <= Jed.PF.interpreter(ast.right)(n);

        case 'GTE':
          return Jed.PF.interpreter(ast.left)(n) >= Jed.PF.interpreter(ast.right)(n);

        case 'EQ':
          return Jed.PF.interpreter(ast.left)(n) == Jed.PF.interpreter(ast.right)(n);

        case 'NEQ':
          return Jed.PF.interpreter(ast.left)(n) != Jed.PF.interpreter(ast.right)(n);

        case 'MOD':
          return Jed.PF.interpreter(ast.left)(n) % Jed.PF.interpreter(ast.right)(n);

        case 'VAR':
          return n;

        case 'NUM':
          return ast.val;

        default:
          throw new Error("Invalid Token found.");
      }
    };
  };

  Jed.PF.extractPluralExpr = function (p) {
    // trim first
    p = p.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

    if (!/;\s*$/.test(p)) {
      p = p.concat(';');
    }

    var nplurals_re = /nplurals\=(\d+);/,
        plural_re = /plural\=(.*);/,
        nplurals_matches = p.match(nplurals_re),
        res = {},
        plural_matches; // Find the nplurals number

    if (nplurals_matches.length > 1) {
      res.nplurals = nplurals_matches[1];
    } else {
      throw new Error('nplurals not found in plural_forms string: ' + p);
    } // remove that data to get to the formula


    p = p.replace(nplurals_re, "");
    plural_matches = p.match(plural_re);

    if (!(plural_matches && plural_matches.length > 1)) {
      throw new Error('`plural` expression not found: ' + p);
    }

    return plural_matches[1];
  };
  /* Jison generated parser */


  Jed.PF.parser = function () {
    var parser = {
      trace: function trace() {},
      yy: {},
      symbols_: {
        "error": 2,
        "expressions": 3,
        "e": 4,
        "EOF": 5,
        "?": 6,
        ":": 7,
        "||": 8,
        "&&": 9,
        "<": 10,
        "<=": 11,
        ">": 12,
        ">=": 13,
        "!=": 14,
        "==": 15,
        "%": 16,
        "(": 17,
        ")": 18,
        "n": 19,
        "NUMBER": 20,
        "$accept": 0,
        "$end": 1
      },
      terminals_: {
        2: "error",
        5: "EOF",
        6: "?",
        7: ":",
        8: "||",
        9: "&&",
        10: "<",
        11: "<=",
        12: ">",
        13: ">=",
        14: "!=",
        15: "==",
        16: "%",
        17: "(",
        18: ")",
        19: "n",
        20: "NUMBER"
      },
      productions_: [0, [3, 2], [4, 5], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 1], [4, 1]],
      performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$) {
        var $0 = $$.length - 1;

        switch (yystate) {
          case 1:
            return {
              type: 'GROUP',
              expr: $$[$0 - 1]
            };
            break;

          case 2:
            this.$ = {
              type: 'TERNARY',
              expr: $$[$0 - 4],
              truthy: $$[$0 - 2],
              falsey: $$[$0]
            };
            break;

          case 3:
            this.$ = {
              type: "OR",
              left: $$[$0 - 2],
              right: $$[$0]
            };
            break;

          case 4:
            this.$ = {
              type: "AND",
              left: $$[$0 - 2],
              right: $$[$0]
            };
            break;

          case 5:
            this.$ = {
              type: 'LT',
              left: $$[$0 - 2],
              right: $$[$0]
            };
            break;

          case 6:
            this.$ = {
              type: 'LTE',
              left: $$[$0 - 2],
              right: $$[$0]
            };
            break;

          case 7:
            this.$ = {
              type: 'GT',
              left: $$[$0 - 2],
              right: $$[$0]
            };
            break;

          case 8:
            this.$ = {
              type: 'GTE',
              left: $$[$0 - 2],
              right: $$[$0]
            };
            break;

          case 9:
            this.$ = {
              type: 'NEQ',
              left: $$[$0 - 2],
              right: $$[$0]
            };
            break;

          case 10:
            this.$ = {
              type: 'EQ',
              left: $$[$0 - 2],
              right: $$[$0]
            };
            break;

          case 11:
            this.$ = {
              type: 'MOD',
              left: $$[$0 - 2],
              right: $$[$0]
            };
            break;

          case 12:
            this.$ = {
              type: 'GROUP',
              expr: $$[$0 - 1]
            };
            break;

          case 13:
            this.$ = {
              type: 'VAR'
            };
            break;

          case 14:
            this.$ = {
              type: 'NUM',
              val: Number(yytext)
            };
            break;
        }
      },
      table: [{
        3: 1,
        4: 2,
        17: [1, 3],
        19: [1, 4],
        20: [1, 5]
      }, {
        1: [3]
      }, {
        5: [1, 6],
        6: [1, 7],
        8: [1, 8],
        9: [1, 9],
        10: [1, 10],
        11: [1, 11],
        12: [1, 12],
        13: [1, 13],
        14: [1, 14],
        15: [1, 15],
        16: [1, 16]
      }, {
        4: 17,
        17: [1, 3],
        19: [1, 4],
        20: [1, 5]
      }, {
        5: [2, 13],
        6: [2, 13],
        7: [2, 13],
        8: [2, 13],
        9: [2, 13],
        10: [2, 13],
        11: [2, 13],
        12: [2, 13],
        13: [2, 13],
        14: [2, 13],
        15: [2, 13],
        16: [2, 13],
        18: [2, 13]
      }, {
        5: [2, 14],
        6: [2, 14],
        7: [2, 14],
        8: [2, 14],
        9: [2, 14],
        10: [2, 14],
        11: [2, 14],
        12: [2, 14],
        13: [2, 14],
        14: [2, 14],
        15: [2, 14],
        16: [2, 14],
        18: [2, 14]
      }, {
        1: [2, 1]
      }, {
        4: 18,
        17: [1, 3],
        19: [1, 4],
        20: [1, 5]
      }, {
        4: 19,
        17: [1, 3],
        19: [1, 4],
        20: [1, 5]
      }, {
        4: 20,
        17: [1, 3],
        19: [1, 4],
        20: [1, 5]
      }, {
        4: 21,
        17: [1, 3],
        19: [1, 4],
        20: [1, 5]
      }, {
        4: 22,
        17: [1, 3],
        19: [1, 4],
        20: [1, 5]
      }, {
        4: 23,
        17: [1, 3],
        19: [1, 4],
        20: [1, 5]
      }, {
        4: 24,
        17: [1, 3],
        19: [1, 4],
        20: [1, 5]
      }, {
        4: 25,
        17: [1, 3],
        19: [1, 4],
        20: [1, 5]
      }, {
        4: 26,
        17: [1, 3],
        19: [1, 4],
        20: [1, 5]
      }, {
        4: 27,
        17: [1, 3],
        19: [1, 4],
        20: [1, 5]
      }, {
        6: [1, 7],
        8: [1, 8],
        9: [1, 9],
        10: [1, 10],
        11: [1, 11],
        12: [1, 12],
        13: [1, 13],
        14: [1, 14],
        15: [1, 15],
        16: [1, 16],
        18: [1, 28]
      }, {
        6: [1, 7],
        7: [1, 29],
        8: [1, 8],
        9: [1, 9],
        10: [1, 10],
        11: [1, 11],
        12: [1, 12],
        13: [1, 13],
        14: [1, 14],
        15: [1, 15],
        16: [1, 16]
      }, {
        5: [2, 3],
        6: [2, 3],
        7: [2, 3],
        8: [2, 3],
        9: [1, 9],
        10: [1, 10],
        11: [1, 11],
        12: [1, 12],
        13: [1, 13],
        14: [1, 14],
        15: [1, 15],
        16: [1, 16],
        18: [2, 3]
      }, {
        5: [2, 4],
        6: [2, 4],
        7: [2, 4],
        8: [2, 4],
        9: [2, 4],
        10: [1, 10],
        11: [1, 11],
        12: [1, 12],
        13: [1, 13],
        14: [1, 14],
        15: [1, 15],
        16: [1, 16],
        18: [2, 4]
      }, {
        5: [2, 5],
        6: [2, 5],
        7: [2, 5],
        8: [2, 5],
        9: [2, 5],
        10: [2, 5],
        11: [2, 5],
        12: [2, 5],
        13: [2, 5],
        14: [2, 5],
        15: [2, 5],
        16: [1, 16],
        18: [2, 5]
      }, {
        5: [2, 6],
        6: [2, 6],
        7: [2, 6],
        8: [2, 6],
        9: [2, 6],
        10: [2, 6],
        11: [2, 6],
        12: [2, 6],
        13: [2, 6],
        14: [2, 6],
        15: [2, 6],
        16: [1, 16],
        18: [2, 6]
      }, {
        5: [2, 7],
        6: [2, 7],
        7: [2, 7],
        8: [2, 7],
        9: [2, 7],
        10: [2, 7],
        11: [2, 7],
        12: [2, 7],
        13: [2, 7],
        14: [2, 7],
        15: [2, 7],
        16: [1, 16],
        18: [2, 7]
      }, {
        5: [2, 8],
        6: [2, 8],
        7: [2, 8],
        8: [2, 8],
        9: [2, 8],
        10: [2, 8],
        11: [2, 8],
        12: [2, 8],
        13: [2, 8],
        14: [2, 8],
        15: [2, 8],
        16: [1, 16],
        18: [2, 8]
      }, {
        5: [2, 9],
        6: [2, 9],
        7: [2, 9],
        8: [2, 9],
        9: [2, 9],
        10: [2, 9],
        11: [2, 9],
        12: [2, 9],
        13: [2, 9],
        14: [2, 9],
        15: [2, 9],
        16: [1, 16],
        18: [2, 9]
      }, {
        5: [2, 10],
        6: [2, 10],
        7: [2, 10],
        8: [2, 10],
        9: [2, 10],
        10: [2, 10],
        11: [2, 10],
        12: [2, 10],
        13: [2, 10],
        14: [2, 10],
        15: [2, 10],
        16: [1, 16],
        18: [2, 10]
      }, {
        5: [2, 11],
        6: [2, 11],
        7: [2, 11],
        8: [2, 11],
        9: [2, 11],
        10: [2, 11],
        11: [2, 11],
        12: [2, 11],
        13: [2, 11],
        14: [2, 11],
        15: [2, 11],
        16: [2, 11],
        18: [2, 11]
      }, {
        5: [2, 12],
        6: [2, 12],
        7: [2, 12],
        8: [2, 12],
        9: [2, 12],
        10: [2, 12],
        11: [2, 12],
        12: [2, 12],
        13: [2, 12],
        14: [2, 12],
        15: [2, 12],
        16: [2, 12],
        18: [2, 12]
      }, {
        4: 30,
        17: [1, 3],
        19: [1, 4],
        20: [1, 5]
      }, {
        5: [2, 2],
        6: [1, 7],
        7: [2, 2],
        8: [1, 8],
        9: [1, 9],
        10: [1, 10],
        11: [1, 11],
        12: [1, 12],
        13: [1, 13],
        14: [1, 14],
        15: [1, 15],
        16: [1, 16],
        18: [2, 2]
      }],
      defaultActions: {
        6: [2, 1]
      },
      parseError: function parseError(str, hash) {
        throw new Error(str);
      },
      parse: function parse(input) {
        var self = this,
            stack = [0],
            vstack = [null],
            // semantic value stack
        lstack = [],
            // location stack
        table = this.table,
            yytext = '',
            yylineno = 0,
            yyleng = 0,
            recovering = 0,
            TERROR = 2,
            EOF = 1; //this.reductionCount = this.shiftCount = 0;

        this.lexer.setInput(input);
        this.lexer.yy = this.yy;
        this.yy.lexer = this.lexer;
        if (typeof this.lexer.yylloc == 'undefined') this.lexer.yylloc = {};
        var yyloc = this.lexer.yylloc;
        lstack.push(yyloc);
        if (typeof this.yy.parseError === 'function') this.parseError = this.yy.parseError;

        function popStack(n) {
          stack.length = stack.length - 2 * n;
          vstack.length = vstack.length - n;
          lstack.length = lstack.length - n;
        }

        function lex() {
          var token;
          token = self.lexer.lex() || 1; // $end = 1
          // if token isn't its numeric value, convert

          if (typeof token !== 'number') {
            token = self.symbols_[token] || token;
          }

          return token;
        }

        var symbol,
            preErrorSymbol,
            state,
            action,
            a,
            r,
            yyval = {},
            p,
            len,
            newState,
            expected;

        while (true) {
          // retreive state number from top of stack
          state = stack[stack.length - 1]; // use default actions if available

          if (this.defaultActions[state]) {
            action = this.defaultActions[state];
          } else {
            if (symbol == null) symbol = lex(); // read action for current state and first input

            action = table[state] && table[state][symbol];
          } // handle parse error


          _handle_error: if (typeof action === 'undefined' || !action.length || !action[0]) {
            if (!recovering) {
              // Report error
              expected = [];

              for (p in table[state]) if (this.terminals_[p] && p > 2) {
                expected.push("'" + this.terminals_[p] + "'");
              }

              var errStr = '';

              if (this.lexer.showPosition) {
                errStr = 'Parse error on line ' + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(', ') + ", got '" + this.terminals_[symbol] + "'";
              } else {
                errStr = 'Parse error on line ' + (yylineno + 1) + ": Unexpected " + (symbol == 1
                /*EOF*/
                ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
              }

              this.parseError(errStr, {
                text: this.lexer.match,
                token: this.terminals_[symbol] || symbol,
                line: this.lexer.yylineno,
                loc: yyloc,
                expected: expected
              });
            } // just recovered from another error


            if (recovering == 3) {
              if (symbol == EOF) {
                throw new Error(errStr || 'Parsing halted.');
              } // discard current lookahead and grab another


              yyleng = this.lexer.yyleng;
              yytext = this.lexer.yytext;
              yylineno = this.lexer.yylineno;
              yyloc = this.lexer.yylloc;
              symbol = lex();
            } // try to recover from error


            while (1) {
              // check for error recovery rule in this state
              if (TERROR.toString() in table[state]) {
                break;
              }

              if (state == 0) {
                throw new Error(errStr || 'Parsing halted.');
              }

              popStack(1);
              state = stack[stack.length - 1];
            }

            preErrorSymbol = symbol; // save the lookahead token

            symbol = TERROR; // insert generic error symbol as new lookahead

            state = stack[stack.length - 1];
            action = table[state] && table[state][TERROR];
            recovering = 3; // allow 3 real symbols to be shifted before reporting a new error
          } // this shouldn't happen, unless resolve defaults are off


          if (action[0] instanceof Array && action.length > 1) {
            throw new Error('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol);
          }

          switch (action[0]) {
            case 1:
              // shift
              //this.shiftCount++;
              stack.push(symbol);
              vstack.push(this.lexer.yytext);
              lstack.push(this.lexer.yylloc);
              stack.push(action[1]); // push state

              symbol = null;

              if (!preErrorSymbol) {
                // normal execution/no error
                yyleng = this.lexer.yyleng;
                yytext = this.lexer.yytext;
                yylineno = this.lexer.yylineno;
                yyloc = this.lexer.yylloc;
                if (recovering > 0) recovering--;
              } else {
                // error just occurred, resume old lookahead f/ before error
                symbol = preErrorSymbol;
                preErrorSymbol = null;
              }

              break;

            case 2:
              // reduce
              //this.reductionCount++;
              len = this.productions_[action[1]][1]; // perform semantic action

              yyval.$ = vstack[vstack.length - len]; // default to $$ = $1
              // default location, uses first token for firsts, last for lasts

              yyval._$ = {
                first_line: lstack[lstack.length - (len || 1)].first_line,
                last_line: lstack[lstack.length - 1].last_line,
                first_column: lstack[lstack.length - (len || 1)].first_column,
                last_column: lstack[lstack.length - 1].last_column
              };
              r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);

              if (typeof r !== 'undefined') {
                return r;
              } // pop off stack


              if (len) {
                stack = stack.slice(0, -1 * len * 2);
                vstack = vstack.slice(0, -1 * len);
                lstack = lstack.slice(0, -1 * len);
              }

              stack.push(this.productions_[action[1]][0]); // push nonterminal (reduce)

              vstack.push(yyval.$);
              lstack.push(yyval._$); // goto new state = table[STATE][NONTERMINAL]

              newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
              stack.push(newState);
              break;

            case 3:
              // accept
              return true;
          }
        }

        return true;
      }
    };
    /* Jison generated lexer */

    var lexer = function () {
      var lexer = {
        EOF: 1,
        parseError: function parseError(str, hash) {
          if (this.yy.parseError) {
            this.yy.parseError(str, hash);
          } else {
            throw new Error(str);
          }
        },
        setInput: function (input) {
          this._input = input;
          this._more = this._less = this.done = false;
          this.yylineno = this.yyleng = 0;
          this.yytext = this.matched = this.match = '';
          this.conditionStack = ['INITIAL'];
          this.yylloc = {
            first_line: 1,
            first_column: 0,
            last_line: 1,
            last_column: 0
          };
          return this;
        },
        input: function () {
          var ch = this._input[0];
          this.yytext += ch;
          this.yyleng++;
          this.match += ch;
          this.matched += ch;
          var lines = ch.match(/\n/);
          if (lines) this.yylineno++;
          this._input = this._input.slice(1);
          return ch;
        },
        unput: function (ch) {
          this._input = ch + this._input;
          return this;
        },
        more: function () {
          this._more = true;
          return this;
        },
        pastInput: function () {
          var past = this.matched.substr(0, this.matched.length - this.match.length);
          return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, "");
        },
        upcomingInput: function () {
          var next = this.match;

          if (next.length < 20) {
            next += this._input.substr(0, 20 - next.length);
          }

          return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, "");
        },
        showPosition: function () {
          var pre = this.pastInput();
          var c = new Array(pre.length + 1).join("-");
          return pre + this.upcomingInput() + "\n" + c + "^";
        },
        next: function () {
          if (this.done) {
            return this.EOF;
          }

          if (!this._input) this.done = true;
          var token, match, col, lines;

          if (!this._more) {
            this.yytext = '';
            this.match = '';
          }

          var rules = this._currentRules();

          for (var i = 0; i < rules.length; i++) {
            match = this._input.match(this.rules[rules[i]]);

            if (match) {
              lines = match[0].match(/\n.*/g);
              if (lines) this.yylineno += lines.length;
              this.yylloc = {
                first_line: this.yylloc.last_line,
                last_line: this.yylineno + 1,
                first_column: this.yylloc.last_column,
                last_column: lines ? lines[lines.length - 1].length - 1 : this.yylloc.last_column + match[0].length
              };
              this.yytext += match[0];
              this.match += match[0];
              this.matches = match;
              this.yyleng = this.yytext.length;
              this._more = false;
              this._input = this._input.slice(match[0].length);
              this.matched += match[0];
              token = this.performAction.call(this, this.yy, this, rules[i], this.conditionStack[this.conditionStack.length - 1]);
              if (token) return token;else return;
            }
          }

          if (this._input === "") {
            return this.EOF;
          } else {
            this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), {
              text: "",
              token: null,
              line: this.yylineno
            });
          }
        },
        lex: function lex() {
          var r = this.next();

          if (typeof r !== 'undefined') {
            return r;
          } else {
            return this.lex();
          }
        },
        begin: function begin(condition) {
          this.conditionStack.push(condition);
        },
        popState: function popState() {
          return this.conditionStack.pop();
        },
        _currentRules: function _currentRules() {
          return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
        },
        topState: function () {
          return this.conditionStack[this.conditionStack.length - 2];
        },
        pushState: function begin(condition) {
          this.begin(condition);
        }
      };

      lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START) {
        var YYSTATE = YY_START;

        switch ($avoiding_name_collisions) {
          case 0:
            /* skip whitespace */
            break;

          case 1:
            return 20;
            break;

          case 2:
            return 19;
            break;

          case 3:
            return 8;
            break;

          case 4:
            return 9;
            break;

          case 5:
            return 6;
            break;

          case 6:
            return 7;
            break;

          case 7:
            return 11;
            break;

          case 8:
            return 13;
            break;

          case 9:
            return 10;
            break;

          case 10:
            return 12;
            break;

          case 11:
            return 14;
            break;

          case 12:
            return 15;
            break;

          case 13:
            return 16;
            break;

          case 14:
            return 17;
            break;

          case 15:
            return 18;
            break;

          case 16:
            return 5;
            break;

          case 17:
            return 'INVALID';
            break;
        }
      };

      lexer.rules = [/^\s+/, /^[0-9]+(\.[0-9]+)?\b/, /^n\b/, /^\|\|/, /^&&/, /^\?/, /^:/, /^<=/, /^>=/, /^</, /^>/, /^!=/, /^==/, /^%/, /^\(/, /^\)/, /^$/, /^./];
      lexer.conditions = {
        "INITIAL": {
          "rules": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
          "inclusive": true
        }
      };
      return lexer;
    }();

    parser.lexer = lexer;
    return parser;
  }(); // End parser
  // Handle node, amd, and global systems


  if (true) {
    if ( true && module.exports) {
      exports = module.exports = Jed;
    }

    exports.Jed = Jed;
  } else {}
})(this);

/***/ }),
/* 65 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _shims__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(0);
/*
    This program is distributed under the terms of the MIT license.
    Please see the LICENSE file for details.

    Copyright 2006-2008, OGG, LLC
*/

/* global window, clearTimeout, WebSocket, DOMParser */


/** Class: Strophe.WebSocket
 *  _Private_ helper class that handles WebSocket Connections
 *
 *  The Strophe.WebSocket class is used internally by Strophe.Connection
 *  to encapsulate WebSocket sessions. It is not meant to be used from user's code.
 */

/** File: websocket.js
 *  A JavaScript library to enable XMPP over Websocket in Strophejs.
 *
 *  This file implements XMPP over WebSockets for Strophejs.
 *  If a Connection is established with a Websocket url (ws://...)
 *  Strophe will use WebSockets.
 *  For more information on XMPP-over-WebSocket see RFC 7395:
 *  http://tools.ietf.org/html/rfc7395
 *
 *  WebSocket support implemented by Andreas Guth (andreas.guth@rwth-aachen.de)
 */

_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Websocket = class Websocket {
  /** PrivateConstructor: Strophe.Websocket
   *  Create and initialize a Strophe.WebSocket object.
   *  Currently only sets the connection Object.
   *
   *  Parameters:
   *    (Strophe.Connection) connection - The Strophe.Connection that will use WebSockets.
   *
   *  Returns:
   *    A new Strophe.WebSocket object.
   */
  constructor(connection) {
    this._conn = connection;
    this.strip = "wrapper";
    const service = connection.service;

    if (service.indexOf("ws:") !== 0 && service.indexOf("wss:") !== 0) {
      // If the service is not an absolute URL, assume it is a path and put the absolute
      // URL together from options, current URL and the path.
      let new_service = "";

      if (connection.options.protocol === "ws" && window.location.protocol !== "https:") {
        new_service += "ws";
      } else {
        new_service += "wss";
      }

      new_service += "://" + window.location.host;

      if (service.indexOf("/") !== 0) {
        new_service += window.location.pathname + service;
      } else {
        new_service += service;
      }

      connection.service = new_service;
    }
  }
  /** PrivateFunction: _buildStream
   *  _Private_ helper function to generate the <stream> start tag for WebSockets
   *
   *  Returns:
   *    A Strophe.Builder with a <stream> element.
   */


  _buildStream() {
    return Object(_core__WEBPACK_IMPORTED_MODULE_1__[/* $build */ "a"])("open", {
      "xmlns": _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].NS.FRAMING,
      "to": this._conn.domain,
      "version": '1.0'
    });
  }
  /** PrivateFunction: _checkStreamError
   * _Private_ checks a message for stream:error
   *
   *  Parameters:
   *    (Strophe.Request) bodyWrap - The received stanza.
   *    connectstatus - The ConnectStatus that will be set on error.
   *  Returns:
   *     true if there was a streamerror, false otherwise.
   */


  _checkStreamError(bodyWrap, connectstatus) {
    let errors;

    if (bodyWrap.getElementsByTagNameNS) {
      errors = bodyWrap.getElementsByTagNameNS(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].NS.STREAM, "error");
    } else {
      errors = bodyWrap.getElementsByTagName("stream:error");
    }

    if (errors.length === 0) {
      return false;
    }

    const error = errors[0];
    let condition = "";
    let text = "";
    const ns = "urn:ietf:params:xml:ns:xmpp-streams";

    for (let i = 0; i < error.childNodes.length; i++) {
      const e = error.childNodes[i];

      if (e.getAttribute("xmlns") !== ns) {
        break;
      }

      if (e.nodeName === "text") {
        text = e.textContent;
      } else {
        condition = e.nodeName;
      }
    }

    let errorString = "WebSocket stream error: ";

    if (condition) {
      errorString += condition;
    } else {
      errorString += "unknown";
    }

    if (text) {
      errorString += " - " + text;
    }

    _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error(errorString); // close the connection on stream_error

    this._conn._changeConnectStatus(connectstatus, condition);

    this._conn._doDisconnect();

    return true;
  }
  /** PrivateFunction: _reset
   *  Reset the connection.
   *
   *  This function is called by the reset function of the Strophe Connection.
   *  Is not needed by WebSockets.
   */


  _reset() {
    // eslint-disable-line class-methods-use-this
    return;
  }
  /** PrivateFunction: _connect
   *  _Private_ function called by Strophe.Connection.connect
   *
   *  Creates a WebSocket for a connection and assigns Callbacks to it.
   *  Does nothing if there already is a WebSocket.
   */


  _connect() {
    // Ensure that there is no open WebSocket from a previous Connection.
    this._closeSocket();

    this.socket = new _shims__WEBPACK_IMPORTED_MODULE_0__[/* WebSocket */ "b"](this._conn.service, "xmpp");

    this.socket.onopen = () => this._onOpen();

    this.socket.onerror = e => this._onError(e);

    this.socket.onclose = e => this._onClose(e); // Gets replaced with this._onMessage once _onInitialMessage is called


    this.socket.onmessage = message => this._onInitialMessage(message);
  }
  /** PrivateFunction: _connect_cb
   *  _Private_ function called by Strophe.Connection._connect_cb
   *
   * checks for stream:error
   *
   *  Parameters:
   *    (Strophe.Request) bodyWrap - The received stanza.
   */


  _connect_cb(bodyWrap) {
    const error = this._checkStreamError(bodyWrap, _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.CONNFAIL);

    if (error) {
      return _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.CONNFAIL;
    }
  }
  /** PrivateFunction: _handleStreamStart
   * _Private_ function that checks the opening <open /> tag for errors.
   *
   * Disconnects if there is an error and returns false, true otherwise.
   *
   *  Parameters:
   *    (Node) message - Stanza containing the <open /> tag.
   */


  _handleStreamStart(message) {
    let error = false; // Check for errors in the <open /> tag

    const ns = message.getAttribute("xmlns");

    if (typeof ns !== "string") {
      error = "Missing xmlns in <open />";
    } else if (ns !== _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].NS.FRAMING) {
      error = "Wrong xmlns in <open />: " + ns;
    }

    const ver = message.getAttribute("version");

    if (typeof ver !== "string") {
      error = "Missing version in <open />";
    } else if (ver !== "1.0") {
      error = "Wrong version in <open />: " + ver;
    }

    if (error) {
      this._conn._changeConnectStatus(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.CONNFAIL, error);

      this._conn._doDisconnect();

      return false;
    }

    return true;
  }
  /** PrivateFunction: _onInitialMessage
   * _Private_ function that handles the first connection messages.
   *
   * On receiving an opening stream tag this callback replaces itself with the real
   * message handler. On receiving a stream error the connection is terminated.
   */


  _onInitialMessage(message) {
    if (message.data.indexOf("<open ") === 0 || message.data.indexOf("<?xml") === 0) {
      // Strip the XML Declaration, if there is one
      const data = message.data.replace(/^(<\?.*?\?>\s*)*/, "");
      if (data === '') return;
      const streamStart = new _shims__WEBPACK_IMPORTED_MODULE_0__[/* DOMParser */ "a"]().parseFromString(data, "text/xml").documentElement;

      this._conn.xmlInput(streamStart);

      this._conn.rawInput(message.data); //_handleStreamSteart will check for XML errors and disconnect on error


      if (this._handleStreamStart(streamStart)) {
        //_connect_cb will check for stream:error and disconnect on error
        this._connect_cb(streamStart);
      }
    } else if (message.data.indexOf("<close ") === 0) {
      // <close xmlns="urn:ietf:params:xml:ns:xmpp-framing />
      // Parse the raw string to an XML element
      const parsedMessage = new _shims__WEBPACK_IMPORTED_MODULE_0__[/* DOMParser */ "a"]().parseFromString(message.data, "text/xml").documentElement; // Report this input to the raw and xml handlers

      this._conn.xmlInput(parsedMessage);

      this._conn.rawInput(message.data);

      const see_uri = parsedMessage.getAttribute("see-other-uri");

      if (see_uri) {
        const service = this._conn.service; // Valid scenarios: WSS->WSS, WS->ANY

        const isSecureRedirect = service.indexOf("wss:") >= 0 && see_uri.indexOf("wss:") >= 0 || service.indexOf("ws:") >= 0;

        if (isSecureRedirect) {
          this._conn._changeConnectStatus(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.REDIRECT, "Received see-other-uri, resetting connection");

          this._conn.reset();

          this._conn.service = see_uri;

          this._connect();
        }
      } else {
        this._conn._changeConnectStatus(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.CONNFAIL, "Received closing stream");

        this._conn._doDisconnect();
      }
    } else {
      this._replaceMessageHandler();

      const string = this._streamWrap(message.data);

      const elem = new _shims__WEBPACK_IMPORTED_MODULE_0__[/* DOMParser */ "a"]().parseFromString(string, "text/xml").documentElement;

      this._conn._connect_cb(elem, null, message.data);
    }
  }
  /** PrivateFunction: _replaceMessageHandler
   *
   * Called by _onInitialMessage in order to replace itself with the general message handler.
   * This method is overridden by Strophe.WorkerWebsocket, which manages a
   * websocket connection via a service worker and doesn't have direct access
   * to the socket.
   */


  _replaceMessageHandler() {
    this.socket.onmessage = m => this._onMessage(m);
  }
  /** PrivateFunction: _disconnect
   *  _Private_ function called by Strophe.Connection.disconnect
   *
   *  Disconnects and sends a last stanza if one is given
   *
   *  Parameters:
   *    (Request) pres - This stanza will be sent before disconnecting.
   */


  _disconnect(pres) {
    if (this.socket && this.socket.readyState !== _shims__WEBPACK_IMPORTED_MODULE_0__[/* WebSocket */ "b"].CLOSED) {
      if (pres) {
        this._conn.send(pres);
      }

      const close = Object(_core__WEBPACK_IMPORTED_MODULE_1__[/* $build */ "a"])("close", {
        "xmlns": _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].NS.FRAMING
      });

      this._conn.xmlOutput(close.tree());

      const closeString = _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].serialize(close);

      this._conn.rawOutput(closeString);

      try {
        this.socket.send(closeString);
      } catch (e) {
        _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].warn("Couldn't send <close /> tag.");
      }
    }

    setTimeout(() => this._conn._doDisconnect, 0);
  }
  /** PrivateFunction: _doDisconnect
   *  _Private_ function to disconnect.
   *
   *  Just closes the Socket for WebSockets
   */


  _doDisconnect() {
    _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug("WebSockets _doDisconnect was called");

    this._closeSocket();
  }
  /** PrivateFunction _streamWrap
   *  _Private_ helper function to wrap a stanza in a <stream> tag.
   *  This is used so Strophe can process stanzas from WebSockets like BOSH
   */


  _streamWrap(stanza) {
    // eslint-disable-line class-methods-use-this
    return "<wrapper>" + stanza + '</wrapper>';
  }
  /** PrivateFunction: _closeSocket
   *  _Private_ function to close the WebSocket.
   *
   *  Closes the socket if it is still open and deletes it
   */


  _closeSocket() {
    if (this.socket) {
      try {
        this.socket.onclose = null;
        this.socket.onerror = null;
        this.socket.onmessage = null;
        this.socket.close();
      } catch (e) {
        _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug(e.message);
      }
    }

    this.socket = null;
  }
  /** PrivateFunction: _emptyQueue
   * _Private_ function to check if the message queue is empty.
   *
   *  Returns:
   *    True, because WebSocket messages are send immediately after queueing.
   */


  _emptyQueue() {
    // eslint-disable-line class-methods-use-this
    return true;
  }
  /** PrivateFunction: _onClose
   * _Private_ function to handle websockets closing.
   */


  _onClose(e) {
    if (this._conn.connected && !this._conn.disconnecting) {
      _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("Websocket closed unexpectedly");

      this._conn._doDisconnect();
    } else if (e && e.code === 1006 && !this._conn.connected && this.socket) {
      // in case the onError callback was not called (Safari 10 does not
      // call onerror when the initial connection fails) we need to
      // dispatch a CONNFAIL status update to be consistent with the
      // behavior on other browsers.
      _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("Websocket closed unexcectedly");

      this._conn._changeConnectStatus(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.CONNFAIL, "The WebSocket connection could not be established or was disconnected.");

      this._conn._doDisconnect();
    } else {
      _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug("Websocket closed");
    }
  }
  /** PrivateFunction: _no_auth_received
   *
   * Called on stream start/restart when no stream:features
   * has been received.
   */


  _no_auth_received(callback) {
    _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("Server did not offer a supported authentication mechanism");

    this._conn._changeConnectStatus(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.CONNFAIL, _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].ErrorCondition.NO_AUTH_MECH);

    if (callback) {
      callback.call(this._conn);
    }

    this._conn._doDisconnect();
  }
  /** PrivateFunction: _onDisconnectTimeout
   *  _Private_ timeout handler for handling non-graceful disconnection.
   *
   *  This does nothing for WebSockets
   */


  _onDisconnectTimeout() {} // eslint-disable-line class-methods-use-this

  /** PrivateFunction: _abortAllRequests
   *  _Private_ helper function that makes sure all pending requests are aborted.
   */


  _abortAllRequests() {} // eslint-disable-line class-methods-use-this

  /** PrivateFunction: _onError
   * _Private_ function to handle websockets errors.
   *
   * Parameters:
   * (Object) error - The websocket error.
   */


  _onError(error) {
    _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("Websocket error " + error);

    this._conn._changeConnectStatus(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.CONNFAIL, "The WebSocket connection could not be established or was disconnected.");

    this._disconnect();
  }
  /** PrivateFunction: _onIdle
   *  _Private_ function called by Strophe.Connection._onIdle
   *
   *  sends all queued stanzas
   */


  _onIdle() {
    const data = this._conn._data;

    if (data.length > 0 && !this._conn.paused) {
      for (let i = 0; i < data.length; i++) {
        if (data[i] !== null) {
          let stanza;

          if (data[i] === "restart") {
            stanza = this._buildStream().tree();
          } else {
            stanza = data[i];
          }

          const rawStanza = _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].serialize(stanza);

          this._conn.xmlOutput(stanza);

          this._conn.rawOutput(rawStanza);

          this.socket.send(rawStanza);
        }
      }

      this._conn._data = [];
    }
  }
  /** PrivateFunction: _onMessage
   * _Private_ function to handle websockets messages.
   *
   * This function parses each of the messages as if they are full documents.
   * [TODO : We may actually want to use a SAX Push parser].
   *
   * Since all XMPP traffic starts with
   *  <stream:stream version='1.0'
   *                 xml:lang='en'
   *                 xmlns='jabber:client'
   *                 xmlns:stream='http://etherx.jabber.org/streams'
   *                 id='3697395463'
   *                 from='SERVER'>
   *
   * The first stanza will always fail to be parsed.
   *
   * Additionally, the seconds stanza will always be <stream:features> with
   * the stream NS defined in the previous stanza, so we need to 'force'
   * the inclusion of the NS in this stanza.
   *
   * Parameters:
   * (string) message - The websocket message.
   */


  _onMessage(message) {
    let elem; // check for closing stream

    const close = '<close xmlns="urn:ietf:params:xml:ns:xmpp-framing" />';

    if (message.data === close) {
      this._conn.rawInput(close);

      this._conn.xmlInput(message);

      if (!this._conn.disconnecting) {
        this._conn._doDisconnect();
      }

      return;
    } else if (message.data.search("<open ") === 0) {
      // This handles stream restarts
      elem = new _shims__WEBPACK_IMPORTED_MODULE_0__[/* DOMParser */ "a"]().parseFromString(message.data, "text/xml").documentElement;

      if (!this._handleStreamStart(elem)) {
        return;
      }
    } else {
      const data = this._streamWrap(message.data);

      elem = new _shims__WEBPACK_IMPORTED_MODULE_0__[/* DOMParser */ "a"]().parseFromString(data, "text/xml").documentElement;
    }

    if (this._checkStreamError(elem, _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.ERROR)) {
      return;
    } //handle unavailable presence stanza before disconnecting


    if (this._conn.disconnecting && elem.firstChild.nodeName === "presence" && elem.firstChild.getAttribute("type") === "unavailable") {
      this._conn.xmlInput(elem);

      this._conn.rawInput(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].serialize(elem)); // if we are already disconnecting we will ignore the unavailable stanza and
      // wait for the </stream:stream> tag before we close the connection


      return;
    }

    this._conn._dataRecv(elem, message.data);
  }
  /** PrivateFunction: _onOpen
   * _Private_ function to handle websockets connection setup.
   *
   * The opening stream tag is sent here.
   */


  _onOpen() {
    _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug("Websocket open");

    const start = this._buildStream();

    this._conn.xmlOutput(start.tree());

    const startString = _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].serialize(start);

    this._conn.rawOutput(startString);

    this.socket.send(startString);
  }
  /** PrivateFunction: _reqToData
   * _Private_ function to get a stanza out of a request.
   *
   * WebSockets don't use requests, so the passed argument is just returned.
   *
   *  Parameters:
   *    (Object) stanza - The stanza.
   *
   *  Returns:
   *    The stanza that was passed.
   */


  _reqToData(stanza) {
    // eslint-disable-line class-methods-use-this
    return stanza;
  }
  /** PrivateFunction: _send
   *  _Private_ part of the Connection.send function for WebSocket
   *
   * Just flushes the messages that are in the queue
   */


  _send() {
    this._conn.flush();
  }
  /** PrivateFunction: _sendRestart
   *
   *  Send an xmpp:restart stanza.
   */


  _sendRestart() {
    clearTimeout(this._conn._idleTimeout);

    this._conn._onIdle.bind(this._conn)();
  }

};

/***/ }),
/* 66 */
/***/ (function(module, exports) {

module.exports = function (originalModule) {
  if (!originalModule.webpackPolyfill) {
    var module = Object.create(originalModule); // module.parent = undefined by default

    if (!module.children) module.children = [];
    Object.defineProperty(module, "loaded", {
      enumerable: true,
      get: function () {
        return module.l;
      }
    });
    Object.defineProperty(module, "id", {
      enumerable: true,
      get: function () {
        return module.i;
      }
    });
    Object.defineProperty(module, "exports", {
      enumerable: true
    });
    module.webpackPolyfill = 1;
  }

  return module;
};

/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {

var toFinite = __webpack_require__(329);
/**
 * Converts `value` to an integer.
 *
 * **Note:** This method is loosely based on
 * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted integer.
 * @example
 *
 * _.toInteger(3.2);
 * // => 3
 *
 * _.toInteger(Number.MIN_VALUE);
 * // => 0
 *
 * _.toInteger(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toInteger('3.2');
 * // => 3
 */


function toInteger(value) {
  var result = toFinite(value),
      remainder = result % 1;
  return result === result ? remainder ? result - remainder : result : 0;
}

module.exports = toInteger;

/***/ }),
/* 68 */
/***/ (function(module, exports) {

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */

function isLength(value) {
  return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}

module.exports = isLength;

/***/ }),
/* 69 */
/***/ (function(module, exports) {

/**
 * A faster alternative to `Function#apply`, this function invokes `func`
 * with the `this` binding of `thisArg` and the arguments of `args`.
 *
 * @private
 * @param {Function} func The function to invoke.
 * @param {*} thisArg The `this` binding of `func`.
 * @param {Array} args The arguments to invoke `func` with.
 * @returns {*} Returns the result of `func`.
 */
function apply(func, thisArg, args) {
  switch (args.length) {
    case 0:
      return func.call(thisArg);

    case 1:
      return func.call(thisArg, args[0]);

    case 2:
      return func.call(thisArg, args[0], args[1]);

    case 3:
      return func.call(thisArg, args[0], args[1], args[2]);
  }

  return func.apply(thisArg, args);
}

module.exports = apply;

/***/ }),
/* 70 */
/***/ (function(module, exports) {

/**
 * A specialized version of `_.map` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 */
function arrayMap(array, iteratee) {
  var index = -1,
      length = array == null ? 0 : array.length,
      result = Array(length);

  while (++index < length) {
    result[index] = iteratee(array[index], index, array);
  }

  return result;
}

module.exports = arrayMap;

/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(16);
/** Built-in value references. */


var objectCreate = Object.create;
/**
 * The base implementation of `_.create` without support for assigning
 * properties to the created object.
 *
 * @private
 * @param {Object} proto The object to inherit from.
 * @returns {Object} Returns the new object.
 */

var baseCreate = function () {
  function object() {}

  return function (proto) {
    if (!isObject(proto)) {
      return {};
    }

    if (objectCreate) {
      return objectCreate(proto);
    }

    object.prototype = proto;
    var result = new object();
    object.prototype = undefined;
    return result;
  };
}();

module.exports = baseCreate;

/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {

var baseCreate = __webpack_require__(71),
    baseLodash = __webpack_require__(73);
/** Used as references for the maximum length and index of an array. */


var MAX_ARRAY_LENGTH = 4294967295;
/**
 * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
 *
 * @private
 * @constructor
 * @param {*} value The value to wrap.
 */

function LazyWrapper(value) {
  this.__wrapped__ = value;
  this.__actions__ = [];
  this.__dir__ = 1;
  this.__filtered__ = false;
  this.__iteratees__ = [];
  this.__takeCount__ = MAX_ARRAY_LENGTH;
  this.__views__ = [];
} // Ensure `LazyWrapper` is an instance of `baseLodash`.


LazyWrapper.prototype = baseCreate(baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;
module.exports = LazyWrapper;

/***/ }),
/* 73 */
/***/ (function(module, exports) {

/**
 * The function whose prototype chain sequence wrappers inherit from.
 *
 * @private
 */
function baseLodash() {// No operation performed.
}

module.exports = baseLodash;

/***/ }),
/* 74 */
/***/ (function(module, exports) {

/**
 * Gets the argument placeholder value for `func`.
 *
 * @private
 * @param {Function} func The function to inspect.
 * @returns {*} Returns the placeholder value.
 */
function getHolder(func) {
  var object = func;
  return object.placeholder;
}

module.exports = getHolder;

/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(21),
    root = __webpack_require__(9);
/* Built-in method references that are verified to be native. */


var Map = getNative(root, 'Map');
module.exports = Map;

/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {

var mapCacheClear = __webpack_require__(396),
    mapCacheDelete = __webpack_require__(403),
    mapCacheGet = __webpack_require__(405),
    mapCacheHas = __webpack_require__(406),
    mapCacheSet = __webpack_require__(407);
/**
 * Creates a map cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */


function MapCache(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;
  this.clear();

  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
} // Add methods to `MapCache`.


MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
module.exports = MapCache;

/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {

var castPath = __webpack_require__(53),
    toKey = __webpack_require__(35);
/**
 * The base implementation of `_.get` without support for default values.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @returns {*} Returns the resolved value.
 */


function baseGet(object, path) {
  path = castPath(path, object);
  var index = 0,
      length = path.length;

  while (object != null && index < length) {
    object = object[toKey(path[index++])];
  }

  return index && index == length ? object : undefined;
}

module.exports = baseGet;

/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {

var isArray = __webpack_require__(12),
    isSymbol = __webpack_require__(44);
/** Used to match property names within property paths. */


var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
    reIsPlainProp = /^\w*$/;
/**
 * Checks if `value` is a property name and not a property path.
 *
 * @private
 * @param {*} value The value to check.
 * @param {Object} [object] The object to query keys on.
 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
 */

function isKey(value, object) {
  if (isArray(value)) {
    return false;
  }

  var type = typeof value;

  if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) {
    return true;
  }

  return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
}

module.exports = isKey;

/***/ }),
/* 79 */
/***/ (function(module, exports) {

module.exports = function (exec) {
  try {
    return !!exec();
  } catch (e) {
    return true;
  }
};

/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(37);

var document = __webpack_require__(10).document; // typeof document.createElement is 'object' in old IE


var is = isObject(document) && isObject(document.createElement);

module.exports = function (it) {
  return is ? document.createElement(it) : {};
};

/***/ }),
/* 81 */
/***/ (function(module, exports) {

// 7.2.1 RequireObjectCoercible(argument)
module.exports = function (it) {
  if (it == undefined) throw TypeError("Can't call method on  " + it);
  return it;
};

/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {

// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(455);

var defined = __webpack_require__(81);

module.exports = function (it) {
  return IObject(defined(it));
};

/***/ }),
/* 83 */
/***/ (function(module, exports) {

// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;

module.exports = function (it) {
  return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};

/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {

var shared = __webpack_require__(142)('keys');

var uid = __webpack_require__(143);

module.exports = function (key) {
  return shared[key] || (shared[key] = uid(key));
};

/***/ }),
/* 85 */
/***/ (function(module, exports) {

module.exports = true;

/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = {
  "default": __webpack_require__(463),
  __esModule: true
};

/***/ }),
/* 87 */
/***/ (function(module, exports, __webpack_require__) {

var def = __webpack_require__(36).f;

var has = __webpack_require__(56);

var TAG = __webpack_require__(13)('toStringTag');

module.exports = function (it, tag, stat) {
  if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, {
    configurable: true,
    value: tag
  });
};

/***/ }),
/* 88 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
 // 25.4.1.5 NewPromiseCapability(C)

var aFunction = __webpack_require__(55);

function PromiseCapability(C) {
  var resolve, reject;
  this.promise = new C(function ($$resolve, $$reject) {
    if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
    resolve = $$resolve;
    reject = $$reject;
  });
  this.resolve = aFunction(resolve);
  this.reject = aFunction(reject);
}

module.exports.f = function (C) {
  return new PromiseCapability(C);
};

/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {

var baseValues = __webpack_require__(365),
    keys = __webpack_require__(29);
/**
 * Creates an array of the own enumerable string keyed property values of `object`.
 *
 * **Note:** Non-object values are coerced to objects.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property values.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.values(new Foo);
 * // => [1, 2] (iteration order is not guaranteed)
 *
 * _.values('hi');
 * // => ['h', 'i']
 */


function values(object) {
  return object == null ? [] : baseValues(object, keys(object));
}

module.exports = values;

/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {

var baseRest = __webpack_require__(107),
    createWrap = __webpack_require__(366),
    getHolder = __webpack_require__(74),
    replaceHolders = __webpack_require__(48);
/** Used to compose bitmasks for function metadata. */


var WRAP_PARTIAL_FLAG = 32;
/**
 * Creates a function that invokes `func` with `partials` prepended to the
 * arguments it receives. This method is like `_.bind` except it does **not**
 * alter the `this` binding.
 *
 * The `_.partial.placeholder` value, which defaults to `_` in monolithic
 * builds, may be used as a placeholder for partially applied arguments.
 *
 * **Note:** This method doesn't set the "length" property of partially
 * applied functions.
 *
 * @static
 * @memberOf _
 * @since 0.2.0
 * @category Function
 * @param {Function} func The function to partially apply arguments to.
 * @param {...*} [partials] The arguments to be partially applied.
 * @returns {Function} Returns the new partially applied function.
 * @example
 *
 * function greet(greeting, name) {
 *   return greeting + ' ' + name;
 * }
 *
 * var sayHelloTo = _.partial(greet, 'hello');
 * sayHelloTo('fred');
 * // => 'hello fred'
 *
 * // Partially applied with placeholders.
 * var greetFred = _.partial(greet, _, 'fred');
 * greetFred('hi');
 * // => 'hi fred'
 */

var partial = baseRest(function (func, partials) {
  var holders = replaceHolders(partials, getHolder(partial));
  return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);
}); // Assign default placeholders.

partial.placeholder = {};
module.exports = partial;

/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_RESULT__;/* global window, exports, define */
!function () {
  'use strict';

  var re = {
    not_string: /[^s]/,
    not_bool: /[^t]/,
    not_type: /[^T]/,
    not_primitive: /[^v]/,
    number: /[diefg]/,
    numeric_arg: /[bcdiefguxX]/,
    json: /[j]/,
    not_json: /[^j]/,
    text: /^[^\x25]+/,
    modulo: /^\x25{2}/,
    placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
    key: /^([a-z_][a-z_\d]*)/i,
    key_access: /^\.([a-z_][a-z_\d]*)/i,
    index_access: /^\[(\d+)\]/,
    sign: /^[+-]/
  };

  function sprintf(key) {
    // `arguments` is not an array, but should be fine for this call
    return sprintf_format(sprintf_parse(key), arguments);
  }

  function vsprintf(fmt, argv) {
    return sprintf.apply(null, [fmt].concat(argv || []));
  }

  function sprintf_format(parse_tree, argv) {
    var cursor = 1,
        tree_length = parse_tree.length,
        arg,
        output = '',
        i,
        k,
        ph,
        pad,
        pad_character,
        pad_length,
        is_positive,
        sign;

    for (i = 0; i < tree_length; i++) {
      if (typeof parse_tree[i] === 'string') {
        output += parse_tree[i];
      } else if (typeof parse_tree[i] === 'object') {
        ph = parse_tree[i]; // convenience purposes only

        if (ph.keys) {
          // keyword argument
          arg = argv[cursor];

          for (k = 0; k < ph.keys.length; k++) {
            if (arg == undefined) {
              throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k - 1]));
            }

            arg = arg[ph.keys[k]];
          }
        } else if (ph.param_no) {
          // positional argument (explicit)
          arg = argv[ph.param_no];
        } else {
          // positional argument (implicit)
          arg = argv[cursor++];
        }

        if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
          arg = arg();
        }

        if (re.numeric_arg.test(ph.type) && typeof arg !== 'number' && isNaN(arg)) {
          throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg));
        }

        if (re.number.test(ph.type)) {
          is_positive = arg >= 0;
        }

        switch (ph.type) {
          case 'b':
            arg = parseInt(arg, 10).toString(2);
            break;

          case 'c':
            arg = String.fromCharCode(parseInt(arg, 10));
            break;

          case 'd':
          case 'i':
            arg = parseInt(arg, 10);
            break;

          case 'j':
            arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0);
            break;

          case 'e':
            arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential();
            break;

          case 'f':
            arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg);
            break;

          case 'g':
            arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg);
            break;

          case 'o':
            arg = (parseInt(arg, 10) >>> 0).toString(8);
            break;

          case 's':
            arg = String(arg);
            arg = ph.precision ? arg.substring(0, ph.precision) : arg;
            break;

          case 't':
            arg = String(!!arg);
            arg = ph.precision ? arg.substring(0, ph.precision) : arg;
            break;

          case 'T':
            arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
            arg = ph.precision ? arg.substring(0, ph.precision) : arg;
            break;

          case 'u':
            arg = parseInt(arg, 10) >>> 0;
            break;

          case 'v':
            arg = arg.valueOf();
            arg = ph.precision ? arg.substring(0, ph.precision) : arg;
            break;

          case 'x':
            arg = (parseInt(arg, 10) >>> 0).toString(16);
            break;

          case 'X':
            arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase();
            break;
        }

        if (re.json.test(ph.type)) {
          output += arg;
        } else {
          if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
            sign = is_positive ? '+' : '-';
            arg = arg.toString().replace(re.sign, '');
          } else {
            sign = '';
          }

          pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' ';
          pad_length = ph.width - (sign + arg).length;
          pad = ph.width ? pad_length > 0 ? pad_character.repeat(pad_length) : '' : '';
          output += ph.align ? sign + arg + pad : pad_character === '0' ? sign + pad + arg : pad + sign + arg;
        }
      }
    }

    return output;
  }

  var sprintf_cache = Object.create(null);

  function sprintf_parse(fmt) {
    if (sprintf_cache[fmt]) {
      return sprintf_cache[fmt];
    }

    var _fmt = fmt,
        match,
        parse_tree = [],
        arg_names = 0;

    while (_fmt) {
      if ((match = re.text.exec(_fmt)) !== null) {
        parse_tree.push(match[0]);
      } else if ((match = re.modulo.exec(_fmt)) !== null) {
        parse_tree.push('%');
      } else if ((match = re.placeholder.exec(_fmt)) !== null) {
        if (match[2]) {
          arg_names |= 1;
          var field_list = [],
              replacement_field = match[2],
              field_match = [];

          if ((field_match = re.key.exec(replacement_field)) !== null) {
            field_list.push(field_match[1]);

            while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
              if ((field_match = re.key_access.exec(replacement_field)) !== null) {
                field_list.push(field_match[1]);
              } else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
                field_list.push(field_match[1]);
              } else {
                throw new SyntaxError('[sprintf] failed to parse named argument key');
              }
            }
          } else {
            throw new SyntaxError('[sprintf] failed to parse named argument key');
          }

          match[2] = field_list;
        } else {
          arg_names |= 2;
        }

        if (arg_names === 3) {
          throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported');
        }

        parse_tree.push({
          placeholder: match[0],
          param_no: match[1],
          keys: match[2],
          sign: match[3],
          pad_char: match[4],
          align: match[5],
          width: match[6],
          precision: match[7],
          type: match[8]
        });
      } else {
        throw new SyntaxError('[sprintf] unexpected placeholder');
      }

      _fmt = _fmt.substring(match[0].length);
    }

    return sprintf_cache[fmt] = parse_tree;
  }
  /**
   * export to either browser or node.js
   */

  /* eslint-disable quote-props */


  if (true) {
    exports['sprintf'] = sprintf;
    exports['vsprintf'] = vsprintf;
  }

  if (typeof window !== 'undefined') {
    window['sprintf'] = sprintf;
    window['vsprintf'] = vsprintf;

    if (true) {
      !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
        return {
          'sprintf': sprintf,
          'vsprintf': vsprintf
        };
      }).call(exports, __webpack_require__, exports, module),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
    }
  }
  /* eslint-enable quote-props */

}(); // eslint-disable-line

/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {

function DOMParser(options) {
  this.options = options || {
    locator: {}
  };
}

DOMParser.prototype.parseFromString = function (source, mimeType) {
  var options = this.options;
  var sax = new XMLReader();
  var domBuilder = options.domBuilder || new DOMHandler(); //contentHandler and LexicalHandler

  var errorHandler = options.errorHandler;
  var locator = options.locator;
  var defaultNSMap = options.xmlns || {};
  var isHTML = /\/x?html?$/.test(mimeType); //mimeType.toLowerCase().indexOf('html') > -1;

  var entityMap = isHTML ? htmlEntity.entityMap : {
    'lt': '<',
    'gt': '>',
    'amp': '&',
    'quot': '"',
    'apos': "'"
  };

  if (locator) {
    domBuilder.setDocumentLocator(locator);
  }

  sax.errorHandler = buildErrorHandler(errorHandler, domBuilder, locator);
  sax.domBuilder = options.domBuilder || domBuilder;

  if (isHTML) {
    defaultNSMap[''] = 'http://www.w3.org/1999/xhtml';
  }

  defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';

  if (source && typeof source === 'string') {
    sax.parse(source, defaultNSMap, entityMap);
  } else {
    sax.errorHandler.error("invalid doc source");
  }

  return domBuilder.doc;
};

function buildErrorHandler(errorImpl, domBuilder, locator) {
  if (!errorImpl) {
    if (domBuilder instanceof DOMHandler) {
      return domBuilder;
    }

    errorImpl = domBuilder;
  }

  var errorHandler = {};
  var isCallback = errorImpl instanceof Function;
  locator = locator || {};

  function build(key) {
    var fn = errorImpl[key];

    if (!fn && isCallback) {
      fn = errorImpl.length == 2 ? function (msg) {
        errorImpl(key, msg);
      } : errorImpl;
    }

    errorHandler[key] = fn && function (msg) {
      fn('[xmldom ' + key + ']\t' + msg + _locator(locator));
    } || function () {};
  }

  build('warning');
  build('error');
  build('fatalError');
  return errorHandler;
} //console.log('#\n\n\n\n\n\n\n####')

/**
 * +ContentHandler+ErrorHandler
 * +LexicalHandler+EntityResolver2
 * -DeclHandler-DTDHandler
 *
 * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
 * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
 * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
 */


function DOMHandler() {
  this.cdata = false;
}

function position(locator, node) {
  node.lineNumber = locator.lineNumber;
  node.columnNumber = locator.columnNumber;
}
/**
 * @see org.xml.sax.ContentHandler#startDocument
 * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
 */


DOMHandler.prototype = {
  startDocument: function () {
    this.doc = new DOMImplementation().createDocument(null, null, null);

    if (this.locator) {
      this.doc.documentURI = this.locator.systemId;
    }
  },
  startElement: function (namespaceURI, localName, qName, attrs) {
    var doc = this.doc;
    var el = doc.createElementNS(namespaceURI, qName || localName);
    var len = attrs.length;
    appendElement(this, el);
    this.currentElement = el;
    this.locator && position(this.locator, el);

    for (var i = 0; i < len; i++) {
      var namespaceURI = attrs.getURI(i);
      var value = attrs.getValue(i);
      var qName = attrs.getQName(i);
      var attr = doc.createAttributeNS(namespaceURI, qName);
      this.locator && position(attrs.getLocator(i), attr);
      attr.value = attr.nodeValue = value;
      el.setAttributeNode(attr);
    }
  },
  endElement: function (namespaceURI, localName, qName) {
    var current = this.currentElement;
    var tagName = current.tagName;
    this.currentElement = current.parentNode;
  },
  startPrefixMapping: function (prefix, uri) {},
  endPrefixMapping: function (prefix) {},
  processingInstruction: function (target, data) {
    var ins = this.doc.createProcessingInstruction(target, data);
    this.locator && position(this.locator, ins);
    appendElement(this, ins);
  },
  ignorableWhitespace: function (ch, start, length) {},
  characters: function (chars, start, length) {
    chars = _toString.apply(this, arguments); //console.log(chars)

    if (chars) {
      if (this.cdata) {
        var charNode = this.doc.createCDATASection(chars);
      } else {
        var charNode = this.doc.createTextNode(chars);
      }

      if (this.currentElement) {
        this.currentElement.appendChild(charNode);
      } else if (/^\s*$/.test(chars)) {
        this.doc.appendChild(charNode); //process xml
      }

      this.locator && position(this.locator, charNode);
    }
  },
  skippedEntity: function (name) {},
  endDocument: function () {
    this.doc.normalize();
  },
  setDocumentLocator: function (locator) {
    if (this.locator = locator) {
      // && !('lineNumber' in locator)){
      locator.lineNumber = 0;
    }
  },
  //LexicalHandler
  comment: function (chars, start, length) {
    chars = _toString.apply(this, arguments);
    var comm = this.doc.createComment(chars);
    this.locator && position(this.locator, comm);
    appendElement(this, comm);
  },
  startCDATA: function () {
    //used in characters() methods
    this.cdata = true;
  },
  endCDATA: function () {
    this.cdata = false;
  },
  startDTD: function (name, publicId, systemId) {
    var impl = this.doc.implementation;

    if (impl && impl.createDocumentType) {
      var dt = impl.createDocumentType(name, publicId, systemId);
      this.locator && position(this.locator, dt);
      appendElement(this, dt);
    }
  },

  /**
   * @see org.xml.sax.ErrorHandler
   * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
   */
  warning: function (error) {
    console.warn('[xmldom warning]\t' + error, _locator(this.locator));
  },
  error: function (error) {
    console.error('[xmldom error]\t' + error, _locator(this.locator));
  },
  fatalError: function (error) {
    throw new ParseError(error, this.locator);
  }
};

function _locator(l) {
  if (l) {
    return '\n@' + (l.systemId || '') + '#[line:' + l.lineNumber + ',col:' + l.columnNumber + ']';
  }
}

function _toString(chars, start, length) {
  if (typeof chars == 'string') {
    return chars.substr(start, length);
  } else {
    //java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
    if (chars.length >= start + length || start) {
      return new java.lang.String(chars, start, length) + '';
    }

    return chars;
  }
}
/*
 * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
 * used method of org.xml.sax.ext.LexicalHandler:
 *  #comment(chars, start, length)
 *  #startCDATA()
 *  #endCDATA()
 *  #startDTD(name, publicId, systemId)
 *
 *
 * IGNORED method of org.xml.sax.ext.LexicalHandler:
 *  #endDTD()
 *  #startEntity(name)
 *  #endEntity(name)
 *
 *
 * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
 * IGNORED method of org.xml.sax.ext.DeclHandler
 * 	#attributeDecl(eName, aName, type, mode, value)
 *  #elementDecl(name, model)
 *  #externalEntityDecl(name, publicId, systemId)
 *  #internalEntityDecl(name, value)
 * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
 * IGNORED method of org.xml.sax.EntityResolver2
 *  #resolveEntity(String name,String publicId,String baseURI,String systemId)
 *  #resolveEntity(publicId, systemId)
 *  #getExternalSubset(name, baseURI)
 * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
 * IGNORED method of org.xml.sax.DTDHandler
 *  #notationDecl(name, publicId, systemId) {};
 *  #unparsedEntityDecl(name, publicId, systemId, notationName) {};
 */


"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g, function (key) {
  DOMHandler.prototype[key] = function () {
    return null;
  };
});
/* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */

function appendElement(hander, node) {
  if (!hander.currentElement) {
    hander.doc.appendChild(node);
  } else {
    hander.currentElement.appendChild(node);
  }
} //appendChild and setAttributeNS are preformance key
//if(typeof require == 'function'){


var htmlEntity = __webpack_require__(324);

var sax = __webpack_require__(325);

var XMLReader = sax.XMLReader;
var ParseError = sax.ParseError;

var DOMImplementation = exports.DOMImplementation = __webpack_require__(93).DOMImplementation;

exports.XMLSerializer = __webpack_require__(93).XMLSerializer;
exports.DOMParser = DOMParser;
exports.__DOMHandler = DOMHandler; //}

/***/ }),
/* 93 */
/***/ (function(module, exports) {

function copy(src, dest) {
  for (var p in src) {
    dest[p] = src[p];
  }
}
/**
^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
 */


function _extends(Class, Super) {
  var pt = Class.prototype;

  if (!(pt instanceof Super)) {
    function t() {}

    ;
    t.prototype = Super.prototype;
    t = new t();
    copy(pt, t);
    Class.prototype = pt = t;
  }

  if (pt.constructor != Class) {
    if (typeof Class != 'function') {
      console.error("unknow Class:" + Class);
    }

    pt.constructor = Class;
  }
}

var htmlns = 'http://www.w3.org/1999/xhtml'; // Node Types

var NodeType = {};
var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
var TEXT_NODE = NodeType.TEXT_NODE = 3;
var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
var NOTATION_NODE = NodeType.NOTATION_NODE = 12; // ExceptionCode

var ExceptionCode = {};
var ExceptionMessage = {};
var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = (ExceptionMessage[1] = "Index size error", 1);
var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = (ExceptionMessage[2] = "DOMString size error", 2);
var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = (ExceptionMessage[3] = "Hierarchy request error", 3);
var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = (ExceptionMessage[4] = "Wrong document", 4);
var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = (ExceptionMessage[5] = "Invalid character", 5);
var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = (ExceptionMessage[6] = "No data allowed", 6);
var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = (ExceptionMessage[7] = "No modification allowed", 7);
var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = (ExceptionMessage[8] = "Not found", 8);
var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = (ExceptionMessage[9] = "Not supported", 9);
var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = (ExceptionMessage[10] = "Attribute in use", 10); //level2

var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = (ExceptionMessage[11] = "Invalid state", 11);
var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = (ExceptionMessage[12] = "Syntax error", 12);
var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = (ExceptionMessage[13] = "Invalid modification", 13);
var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = (ExceptionMessage[14] = "Invalid namespace", 14);
var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = (ExceptionMessage[15] = "Invalid access", 15);
/**
 * DOM Level 2
 * Object DOMException
 * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
 * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
 */

function DOMException(code, message) {
  if (message instanceof Error) {
    var error = message;
  } else {
    error = this;
    Error.call(this, ExceptionMessage[code]);
    this.message = ExceptionMessage[code];
    if (Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
  }

  error.code = code;
  if (message) this.message = this.message + ": " + message;
  return error;
}

;
DOMException.prototype = Error.prototype;
copy(ExceptionCode, DOMException);
/**
 * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
 * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
 * The items in the NodeList are accessible via an integral index, starting from 0.
 */

function NodeList() {}

;
NodeList.prototype = {
  /**
   * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
   * @standard level1
   */
  length: 0,

  /**
   * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
   * @standard level1
   * @param index  unsigned long 
   *   Index into the collection.
   * @return Node
   * 	The node at the indexth position in the NodeList, or null if that is not a valid index. 
   */
  item: function (index) {
    return this[index] || null;
  },
  toString: function (isHTML, nodeFilter) {
    for (var buf = [], i = 0; i < this.length; i++) {
      serializeToString(this[i], buf, isHTML, nodeFilter);
    }

    return buf.join('');
  }
};

function LiveNodeList(node, refresh) {
  this._node = node;
  this._refresh = refresh;

  _updateLiveList(this);
}

function _updateLiveList(list) {
  var inc = list._node._inc || list._node.ownerDocument._inc;

  if (list._inc != inc) {
    var ls = list._refresh(list._node); //console.log(ls.length)


    __set__(list, 'length', ls.length);

    copy(ls, list);
    list._inc = inc;
  }
}

LiveNodeList.prototype.item = function (i) {
  _updateLiveList(this);

  return this[i];
};

_extends(LiveNodeList, NodeList);
/**
 * 
 * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.
 * NamedNodeMap objects in the DOM are live.
 * used for attributes or DocumentType entities 
 */


function NamedNodeMap() {}

;

function _findNodeIndex(list, node) {
  var i = list.length;

  while (i--) {
    if (list[i] === node) {
      return i;
    }
  }
}

function _addNamedNode(el, list, newAttr, oldAttr) {
  if (oldAttr) {
    list[_findNodeIndex(list, oldAttr)] = newAttr;
  } else {
    list[list.length++] = newAttr;
  }

  if (el) {
    newAttr.ownerElement = el;
    var doc = el.ownerDocument;

    if (doc) {
      oldAttr && _onRemoveAttribute(doc, el, oldAttr);

      _onAddAttribute(doc, el, newAttr);
    }
  }
}

function _removeNamedNode(el, list, attr) {
  //console.log('remove attr:'+attr)
  var i = _findNodeIndex(list, attr);

  if (i >= 0) {
    var lastIndex = list.length - 1;

    while (i < lastIndex) {
      list[i] = list[++i];
    }

    list.length = lastIndex;

    if (el) {
      var doc = el.ownerDocument;

      if (doc) {
        _onRemoveAttribute(doc, el, attr);

        attr.ownerElement = null;
      }
    }
  } else {
    throw DOMException(NOT_FOUND_ERR, new Error(el.tagName + '@' + attr));
  }
}

NamedNodeMap.prototype = {
  length: 0,
  item: NodeList.prototype.item,
  getNamedItem: function (key) {
    //		if(key.indexOf(':')>0 || key == 'xmlns'){
    //			return null;
    //		}
    //console.log()
    var i = this.length;

    while (i--) {
      var attr = this[i]; //console.log(attr.nodeName,key)

      if (attr.nodeName == key) {
        return attr;
      }
    }
  },
  setNamedItem: function (attr) {
    var el = attr.ownerElement;

    if (el && el != this._ownerElement) {
      throw new DOMException(INUSE_ATTRIBUTE_ERR);
    }

    var oldAttr = this.getNamedItem(attr.nodeName);

    _addNamedNode(this._ownerElement, this, attr, oldAttr);

    return oldAttr;
  },

  /* returns Node */
  setNamedItemNS: function (attr) {
    // raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
    var el = attr.ownerElement,
        oldAttr;

    if (el && el != this._ownerElement) {
      throw new DOMException(INUSE_ATTRIBUTE_ERR);
    }

    oldAttr = this.getNamedItemNS(attr.namespaceURI, attr.localName);

    _addNamedNode(this._ownerElement, this, attr, oldAttr);

    return oldAttr;
  },

  /* returns Node */
  removeNamedItem: function (key) {
    var attr = this.getNamedItem(key);

    _removeNamedNode(this._ownerElement, this, attr);

    return attr;
  },
  // raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
  //for level2
  removeNamedItemNS: function (namespaceURI, localName) {
    var attr = this.getNamedItemNS(namespaceURI, localName);

    _removeNamedNode(this._ownerElement, this, attr);

    return attr;
  },
  getNamedItemNS: function (namespaceURI, localName) {
    var i = this.length;

    while (i--) {
      var node = this[i];

      if (node.localName == localName && node.namespaceURI == namespaceURI) {
        return node;
      }
    }

    return null;
  }
};
/**
 * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
 */

function DOMImplementation(
/* Object */
features) {
  this._features = {};

  if (features) {
    for (var feature in features) {
      this._features = features[feature];
    }
  }
}

;
DOMImplementation.prototype = {
  hasFeature: function (
  /* string */
  feature,
  /* string */
  version) {
    var versions = this._features[feature.toLowerCase()];

    if (versions && (!version || version in versions)) {
      return true;
    } else {
      return false;
    }
  },
  // Introduced in DOM Level 2:
  createDocument: function (namespaceURI, qualifiedName, doctype) {
    // raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
    var doc = new Document();
    doc.implementation = this;
    doc.childNodes = new NodeList();
    doc.doctype = doctype;

    if (doctype) {
      doc.appendChild(doctype);
    }

    if (qualifiedName) {
      var root = doc.createElementNS(namespaceURI, qualifiedName);
      doc.appendChild(root);
    }

    return doc;
  },
  // Introduced in DOM Level 2:
  createDocumentType: function (qualifiedName, publicId, systemId) {
    // raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
    var node = new DocumentType();
    node.name = qualifiedName;
    node.nodeName = qualifiedName;
    node.publicId = publicId;
    node.systemId = systemId; // Introduced in DOM Level 2:
    //readonly attribute DOMString        internalSubset;
    //TODO:..
    //  readonly attribute NamedNodeMap     entities;
    //  readonly attribute NamedNodeMap     notations;

    return node;
  }
};
/**
 * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
 */

function Node() {}

;
Node.prototype = {
  firstChild: null,
  lastChild: null,
  previousSibling: null,
  nextSibling: null,
  attributes: null,
  parentNode: null,
  childNodes: null,
  ownerDocument: null,
  nodeValue: null,
  namespaceURI: null,
  prefix: null,
  localName: null,
  // Modified in DOM Level 2:
  insertBefore: function (newChild, refChild) {
    //raises 
    return _insertBefore(this, newChild, refChild);
  },
  replaceChild: function (newChild, oldChild) {
    //raises 
    this.insertBefore(newChild, oldChild);

    if (oldChild) {
      this.removeChild(oldChild);
    }
  },
  removeChild: function (oldChild) {
    return _removeChild(this, oldChild);
  },
  appendChild: function (newChild) {
    return this.insertBefore(newChild, null);
  },
  hasChildNodes: function () {
    return this.firstChild != null;
  },
  cloneNode: function (deep) {
    return cloneNode(this.ownerDocument || this, this, deep);
  },
  // Modified in DOM Level 2:
  normalize: function () {
    var child = this.firstChild;

    while (child) {
      var next = child.nextSibling;

      if (next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE) {
        this.removeChild(next);
        child.appendData(next.data);
      } else {
        child.normalize();
        child = next;
      }
    }
  },
  // Introduced in DOM Level 2:
  isSupported: function (feature, version) {
    return this.ownerDocument.implementation.hasFeature(feature, version);
  },
  // Introduced in DOM Level 2:
  hasAttributes: function () {
    return this.attributes.length > 0;
  },
  lookupPrefix: function (namespaceURI) {
    var el = this;

    while (el) {
      var map = el._nsMap; //console.dir(map)

      if (map) {
        for (var n in map) {
          if (map[n] == namespaceURI) {
            return n;
          }
        }
      }

      el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
    }

    return null;
  },
  // Introduced in DOM Level 3:
  lookupNamespaceURI: function (prefix) {
    var el = this;

    while (el) {
      var map = el._nsMap; //console.dir(map)

      if (map) {
        if (prefix in map) {
          return map[prefix];
        }
      }

      el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
    }

    return null;
  },
  // Introduced in DOM Level 3:
  isDefaultNamespace: function (namespaceURI) {
    var prefix = this.lookupPrefix(namespaceURI);
    return prefix == null;
  }
};

function _xmlEncoder(c) {
  return c == '<' && '&lt;' || c == '>' && '&gt;' || c == '&' && '&amp;' || c == '"' && '&quot;' || '&#' + c.charCodeAt() + ';';
}

copy(NodeType, Node);
copy(NodeType, Node.prototype);
/**
 * @param callback return true for continue,false for break
 * @return boolean true: break visit;
 */

function _visitNode(node, callback) {
  if (callback(node)) {
    return true;
  }

  if (node = node.firstChild) {
    do {
      if (_visitNode(node, callback)) {
        return true;
      }
    } while (node = node.nextSibling);
  }
}

function Document() {}

function _onAddAttribute(doc, el, newAttr) {
  doc && doc._inc++;
  var ns = newAttr.namespaceURI;

  if (ns == 'http://www.w3.org/2000/xmlns/') {
    //update namespace
    el._nsMap[newAttr.prefix ? newAttr.localName : ''] = newAttr.value;
  }
}

function _onRemoveAttribute(doc, el, newAttr, remove) {
  doc && doc._inc++;
  var ns = newAttr.namespaceURI;

  if (ns == 'http://www.w3.org/2000/xmlns/') {
    //update namespace
    delete el._nsMap[newAttr.prefix ? newAttr.localName : ''];
  }
}

function _onUpdateChild(doc, el, newChild) {
  if (doc && doc._inc) {
    doc._inc++; //update childNodes

    var cs = el.childNodes;

    if (newChild) {
      cs[cs.length++] = newChild;
    } else {
      //console.log(1)
      var child = el.firstChild;
      var i = 0;

      while (child) {
        cs[i++] = child;
        child = child.nextSibling;
      }

      cs.length = i;
    }
  }
}
/**
 * attributes;
 * children;
 * 
 * writeable properties:
 * nodeValue,Attr:value,CharacterData:data
 * prefix
 */


function _removeChild(parentNode, child) {
  var previous = child.previousSibling;
  var next = child.nextSibling;

  if (previous) {
    previous.nextSibling = next;
  } else {
    parentNode.firstChild = next;
  }

  if (next) {
    next.previousSibling = previous;
  } else {
    parentNode.lastChild = previous;
  }

  _onUpdateChild(parentNode.ownerDocument, parentNode);

  return child;
}
/**
 * preformance key(refChild == null)
 */


function _insertBefore(parentNode, newChild, nextChild) {
  var cp = newChild.parentNode;

  if (cp) {
    cp.removeChild(newChild); //remove and update
  }

  if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {
    var newFirst = newChild.firstChild;

    if (newFirst == null) {
      return newChild;
    }

    var newLast = newChild.lastChild;
  } else {
    newFirst = newLast = newChild;
  }

  var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
  newFirst.previousSibling = pre;
  newLast.nextSibling = nextChild;

  if (pre) {
    pre.nextSibling = newFirst;
  } else {
    parentNode.firstChild = newFirst;
  }

  if (nextChild == null) {
    parentNode.lastChild = newLast;
  } else {
    nextChild.previousSibling = newLast;
  }

  do {
    newFirst.parentNode = parentNode;
  } while (newFirst !== newLast && (newFirst = newFirst.nextSibling));

  _onUpdateChild(parentNode.ownerDocument || parentNode, parentNode); //console.log(parentNode.lastChild.nextSibling == null)


  if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
    newChild.firstChild = newChild.lastChild = null;
  }

  return newChild;
}

function _appendSingleChild(parentNode, newChild) {
  var cp = newChild.parentNode;

  if (cp) {
    var pre = parentNode.lastChild;
    cp.removeChild(newChild); //remove and update

    var pre = parentNode.lastChild;
  }

  var pre = parentNode.lastChild;
  newChild.parentNode = parentNode;
  newChild.previousSibling = pre;
  newChild.nextSibling = null;

  if (pre) {
    pre.nextSibling = newChild;
  } else {
    parentNode.firstChild = newChild;
  }

  parentNode.lastChild = newChild;

  _onUpdateChild(parentNode.ownerDocument, parentNode, newChild);

  return newChild; //console.log("__aa",parentNode.lastChild.nextSibling == null)
}

Document.prototype = {
  //implementation : null,
  nodeName: '#document',
  nodeType: DOCUMENT_NODE,
  doctype: null,
  documentElement: null,
  _inc: 1,
  insertBefore: function (newChild, refChild) {
    //raises 
    if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
      var child = newChild.firstChild;

      while (child) {
        var next = child.nextSibling;
        this.insertBefore(child, refChild);
        child = next;
      }

      return newChild;
    }

    if (this.documentElement == null && newChild.nodeType == ELEMENT_NODE) {
      this.documentElement = newChild;
    }

    return _insertBefore(this, newChild, refChild), newChild.ownerDocument = this, newChild;
  },
  removeChild: function (oldChild) {
    if (this.documentElement == oldChild) {
      this.documentElement = null;
    }

    return _removeChild(this, oldChild);
  },
  // Introduced in DOM Level 2:
  importNode: function (importedNode, deep) {
    return importNode(this, importedNode, deep);
  },
  // Introduced in DOM Level 2:
  getElementById: function (id) {
    var rtv = null;

    _visitNode(this.documentElement, function (node) {
      if (node.nodeType == ELEMENT_NODE) {
        if (node.getAttribute('id') == id) {
          rtv = node;
          return true;
        }
      }
    });

    return rtv;
  },
  getElementsByClassName: function (className) {
    var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
    return new LiveNodeList(this, function (base) {
      var ls = [];

      _visitNode(base.documentElement, function (node) {
        if (node !== base && node.nodeType == ELEMENT_NODE) {
          if (pattern.test(node.getAttribute('class'))) {
            ls.push(node);
          }
        }
      });

      return ls;
    });
  },
  //document factory method:
  createElement: function (tagName) {
    var node = new Element();
    node.ownerDocument = this;
    node.nodeName = tagName;
    node.tagName = tagName;
    node.childNodes = new NodeList();
    var attrs = node.attributes = new NamedNodeMap();
    attrs._ownerElement = node;
    return node;
  },
  createDocumentFragment: function () {
    var node = new DocumentFragment();
    node.ownerDocument = this;
    node.childNodes = new NodeList();
    return node;
  },
  createTextNode: function (data) {
    var node = new Text();
    node.ownerDocument = this;
    node.appendData(data);
    return node;
  },
  createComment: function (data) {
    var node = new Comment();
    node.ownerDocument = this;
    node.appendData(data);
    return node;
  },
  createCDATASection: function (data) {
    var node = new CDATASection();
    node.ownerDocument = this;
    node.appendData(data);
    return node;
  },
  createProcessingInstruction: function (target, data) {
    var node = new ProcessingInstruction();
    node.ownerDocument = this;
    node.tagName = node.target = target;
    node.nodeValue = node.data = data;
    return node;
  },
  createAttribute: function (name) {
    var node = new Attr();
    node.ownerDocument = this;
    node.name = name;
    node.nodeName = name;
    node.localName = name;
    node.specified = true;
    return node;
  },
  createEntityReference: function (name) {
    var node = new EntityReference();
    node.ownerDocument = this;
    node.nodeName = name;
    return node;
  },
  // Introduced in DOM Level 2:
  createElementNS: function (namespaceURI, qualifiedName) {
    var node = new Element();
    var pl = qualifiedName.split(':');
    var attrs = node.attributes = new NamedNodeMap();
    node.childNodes = new NodeList();
    node.ownerDocument = this;
    node.nodeName = qualifiedName;
    node.tagName = qualifiedName;
    node.namespaceURI = namespaceURI;

    if (pl.length == 2) {
      node.prefix = pl[0];
      node.localName = pl[1];
    } else {
      //el.prefix = null;
      node.localName = qualifiedName;
    }

    attrs._ownerElement = node;
    return node;
  },
  // Introduced in DOM Level 2:
  createAttributeNS: function (namespaceURI, qualifiedName) {
    var node = new Attr();
    var pl = qualifiedName.split(':');
    node.ownerDocument = this;
    node.nodeName = qualifiedName;
    node.name = qualifiedName;
    node.namespaceURI = namespaceURI;
    node.specified = true;

    if (pl.length == 2) {
      node.prefix = pl[0];
      node.localName = pl[1];
    } else {
      //el.prefix = null;
      node.localName = qualifiedName;
    }

    return node;
  }
};

_extends(Document, Node);

function Element() {
  this._nsMap = {};
}

;
Element.prototype = {
  nodeType: ELEMENT_NODE,
  hasAttribute: function (name) {
    return this.getAttributeNode(name) != null;
  },
  getAttribute: function (name) {
    var attr = this.getAttributeNode(name);
    return attr && attr.value || '';
  },
  getAttributeNode: function (name) {
    return this.attributes.getNamedItem(name);
  },
  setAttribute: function (name, value) {
    var attr = this.ownerDocument.createAttribute(name);
    attr.value = attr.nodeValue = "" + value;
    this.setAttributeNode(attr);
  },
  removeAttribute: function (name) {
    var attr = this.getAttributeNode(name);
    attr && this.removeAttributeNode(attr);
  },
  //four real opeartion method
  appendChild: function (newChild) {
    if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {
      return this.insertBefore(newChild, null);
    } else {
      return _appendSingleChild(this, newChild);
    }
  },
  setAttributeNode: function (newAttr) {
    return this.attributes.setNamedItem(newAttr);
  },
  setAttributeNodeNS: function (newAttr) {
    return this.attributes.setNamedItemNS(newAttr);
  },
  removeAttributeNode: function (oldAttr) {
    //console.log(this == oldAttr.ownerElement)
    return this.attributes.removeNamedItem(oldAttr.nodeName);
  },
  //get real attribute name,and remove it by removeAttributeNode
  removeAttributeNS: function (namespaceURI, localName) {
    var old = this.getAttributeNodeNS(namespaceURI, localName);
    old && this.removeAttributeNode(old);
  },
  hasAttributeNS: function (namespaceURI, localName) {
    return this.getAttributeNodeNS(namespaceURI, localName) != null;
  },
  getAttributeNS: function (namespaceURI, localName) {
    var attr = this.getAttributeNodeNS(namespaceURI, localName);
    return attr && attr.value || '';
  },
  setAttributeNS: function (namespaceURI, qualifiedName, value) {
    var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
    attr.value = attr.nodeValue = "" + value;
    this.setAttributeNode(attr);
  },
  getAttributeNodeNS: function (namespaceURI, localName) {
    return this.attributes.getNamedItemNS(namespaceURI, localName);
  },
  getElementsByTagName: function (tagName) {
    return new LiveNodeList(this, function (base) {
      var ls = [];

      _visitNode(base, function (node) {
        if (node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)) {
          ls.push(node);
        }
      });

      return ls;
    });
  },
  getElementsByTagNameNS: function (namespaceURI, localName) {
    return new LiveNodeList(this, function (base) {
      var ls = [];

      _visitNode(base, function (node) {
        if (node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)) {
          ls.push(node);
        }
      });

      return ls;
    });
  }
};
Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;

_extends(Element, Node);

function Attr() {}

;
Attr.prototype.nodeType = ATTRIBUTE_NODE;

_extends(Attr, Node);

function CharacterData() {}

;
CharacterData.prototype = {
  data: '',
  substringData: function (offset, count) {
    return this.data.substring(offset, offset + count);
  },
  appendData: function (text) {
    text = this.data + text;
    this.nodeValue = this.data = text;
    this.length = text.length;
  },
  insertData: function (offset, text) {
    this.replaceData(offset, 0, text);
  },
  appendChild: function (newChild) {
    throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]);
  },
  deleteData: function (offset, count) {
    this.replaceData(offset, count, "");
  },
  replaceData: function (offset, count, text) {
    var start = this.data.substring(0, offset);
    var end = this.data.substring(offset + count);
    text = start + text + end;
    this.nodeValue = this.data = text;
    this.length = text.length;
  }
};

_extends(CharacterData, Node);

function Text() {}

;
Text.prototype = {
  nodeName: "#text",
  nodeType: TEXT_NODE,
  splitText: function (offset) {
    var text = this.data;
    var newText = text.substring(offset);
    text = text.substring(0, offset);
    this.data = this.nodeValue = text;
    this.length = text.length;
    var newNode = this.ownerDocument.createTextNode(newText);

    if (this.parentNode) {
      this.parentNode.insertBefore(newNode, this.nextSibling);
    }

    return newNode;
  }
};

_extends(Text, CharacterData);

function Comment() {}

;
Comment.prototype = {
  nodeName: "#comment",
  nodeType: COMMENT_NODE
};

_extends(Comment, CharacterData);

function CDATASection() {}

;
CDATASection.prototype = {
  nodeName: "#cdata-section",
  nodeType: CDATA_SECTION_NODE
};

_extends(CDATASection, CharacterData);

function DocumentType() {}

;
DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;

_extends(DocumentType, Node);

function Notation() {}

;
Notation.prototype.nodeType = NOTATION_NODE;

_extends(Notation, Node);

function Entity() {}

;
Entity.prototype.nodeType = ENTITY_NODE;

_extends(Entity, Node);

function EntityReference() {}

;
EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;

_extends(EntityReference, Node);

function DocumentFragment() {}

;
DocumentFragment.prototype.nodeName = "#document-fragment";
DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;

_extends(DocumentFragment, Node);

function ProcessingInstruction() {}

ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;

_extends(ProcessingInstruction, Node);

function XMLSerializer() {}

XMLSerializer.prototype.serializeToString = function (node, isHtml, nodeFilter) {
  return nodeSerializeToString.call(node, isHtml, nodeFilter);
};

Node.prototype.toString = nodeSerializeToString;

function nodeSerializeToString(isHtml, nodeFilter) {
  var buf = [];
  var refNode = this.nodeType == 9 && this.documentElement || this;
  var prefix = refNode.prefix;
  var uri = refNode.namespaceURI;

  if (uri && prefix == null) {
    //console.log(prefix)
    var prefix = refNode.lookupPrefix(uri);

    if (prefix == null) {
      //isHTML = true;
      var visibleNamespaces = [{
        namespace: uri,
        prefix: null
      } //{namespace:uri,prefix:''}
      ];
    }
  }

  serializeToString(this, buf, isHtml, nodeFilter, visibleNamespaces); //console.log('###',this.nodeType,uri,prefix,buf.join(''))

  return buf.join('');
}

function needNamespaceDefine(node, isHTML, visibleNamespaces) {
  var prefix = node.prefix || '';
  var uri = node.namespaceURI;

  if (!prefix && !uri) {
    return false;
  }

  if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace" || uri == 'http://www.w3.org/2000/xmlns/') {
    return false;
  }

  var i = visibleNamespaces.length; //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)

  while (i--) {
    var ns = visibleNamespaces[i]; // get namespace prefix
    //console.log(node.nodeType,node.tagName,ns.prefix,prefix)

    if (ns.prefix == prefix) {
      return ns.namespace != uri;
    }
  } //console.log(isHTML,uri,prefix=='')
  //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
  //	return false;
  //}
  //node.flag = '11111'
  //console.error(3,true,node.flag,node.prefix,node.namespaceURI)


  return true;
}

function serializeToString(node, buf, isHTML, nodeFilter, visibleNamespaces) {
  if (nodeFilter) {
    node = nodeFilter(node);

    if (node) {
      if (typeof node == 'string') {
        buf.push(node);
        return;
      }
    } else {
      return;
    } //buf.sort.apply(attrs, attributeSorter);

  }

  switch (node.nodeType) {
    case ELEMENT_NODE:
      if (!visibleNamespaces) visibleNamespaces = [];
      var startVisibleNamespaces = visibleNamespaces.length;
      var attrs = node.attributes;
      var len = attrs.length;
      var child = node.firstChild;
      var nodeName = node.tagName;
      isHTML = htmlns === node.namespaceURI || isHTML;
      buf.push('<', nodeName);

      for (var i = 0; i < len; i++) {
        // add namespaces for attributes
        var attr = attrs.item(i);

        if (attr.prefix == 'xmlns') {
          visibleNamespaces.push({
            prefix: attr.localName,
            namespace: attr.value
          });
        } else if (attr.nodeName == 'xmlns') {
          visibleNamespaces.push({
            prefix: '',
            namespace: attr.value
          });
        }
      }

      for (var i = 0; i < len; i++) {
        var attr = attrs.item(i);

        if (needNamespaceDefine(attr, isHTML, visibleNamespaces)) {
          var prefix = attr.prefix || '';
          var uri = attr.namespaceURI;
          var ns = prefix ? ' xmlns:' + prefix : " xmlns";
          buf.push(ns, '="', uri, '"');
          visibleNamespaces.push({
            prefix: prefix,
            namespace: uri
          });
        }

        serializeToString(attr, buf, isHTML, nodeFilter, visibleNamespaces);
      } // add namespace for current node		


      if (needNamespaceDefine(node, isHTML, visibleNamespaces)) {
        var prefix = node.prefix || '';
        var uri = node.namespaceURI;
        var ns = prefix ? ' xmlns:' + prefix : " xmlns";
        buf.push(ns, '="', uri, '"');
        visibleNamespaces.push({
          prefix: prefix,
          namespace: uri
        });
      }

      if (child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)) {
        buf.push('>'); //if is cdata child node

        if (isHTML && /^script$/i.test(nodeName)) {
          while (child) {
            if (child.data) {
              buf.push(child.data);
            } else {
              serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces);
            }

            child = child.nextSibling;
          }
        } else {
          while (child) {
            serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces);
            child = child.nextSibling;
          }
        }

        buf.push('</', nodeName, '>');
      } else {
        buf.push('/>');
      } // remove added visible namespaces
      //visibleNamespaces.length = startVisibleNamespaces;


      return;

    case DOCUMENT_NODE:
    case DOCUMENT_FRAGMENT_NODE:
      var child = node.firstChild;

      while (child) {
        serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces);
        child = child.nextSibling;
      }

      return;

    case ATTRIBUTE_NODE:
      return buf.push(' ', node.name, '="', node.value.replace(/[&"]/g, _xmlEncoder), '"');

    case TEXT_NODE:
      /**
       * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
       * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
       * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
       * `&amp;` and `&lt;` respectively.
       * The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility,
       * be escaped using either `&gt;` or a character reference when it appears in the string `]]>` in content,
       * when that string is not marking the end of a CDATA section.
       *
       * In the content of elements, character data is any string of characters
       * which does not contain the start-delimiter of any markup
       * and does not include the CDATA-section-close delimiter, `]]>`.
       *
       * @see https://www.w3.org/TR/xml/#NT-CharData
       */
      return buf.push(node.data.replace(/[<&]/g, _xmlEncoder).replace(/]]>/g, ']]&gt;'));

    case CDATA_SECTION_NODE:
      return buf.push('<![CDATA[', node.data, ']]>');

    case COMMENT_NODE:
      return buf.push("<!--", node.data, "-->");

    case DOCUMENT_TYPE_NODE:
      var pubid = node.publicId;
      var sysid = node.systemId;
      buf.push('<!DOCTYPE ', node.name);

      if (pubid) {
        buf.push(' PUBLIC ', pubid);

        if (sysid && sysid != '.') {
          buf.push(' ', sysid);
        }

        buf.push('>');
      } else if (sysid && sysid != '.') {
        buf.push(' SYSTEM ', sysid, '>');
      } else {
        var sub = node.internalSubset;

        if (sub) {
          buf.push(" [", sub, "]");
        }

        buf.push(">");
      }

      return;

    case PROCESSING_INSTRUCTION_NODE:
      return buf.push("<?", node.target, " ", node.data, "?>");

    case ENTITY_REFERENCE_NODE:
      return buf.push('&', node.nodeName, ';');
    //case ENTITY_NODE:
    //case NOTATION_NODE:

    default:
      buf.push('??', node.nodeName);
  }
}

function importNode(doc, node, deep) {
  var node2;

  switch (node.nodeType) {
    case ELEMENT_NODE:
      node2 = node.cloneNode(false);
      node2.ownerDocument = doc;
    //var attrs = node2.attributes;
    //var len = attrs.length;
    //for(var i=0;i<len;i++){
    //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
    //}

    case DOCUMENT_FRAGMENT_NODE:
      break;

    case ATTRIBUTE_NODE:
      deep = true;
      break;
    //case ENTITY_REFERENCE_NODE:
    //case PROCESSING_INSTRUCTION_NODE:
    ////case TEXT_NODE:
    //case CDATA_SECTION_NODE:
    //case COMMENT_NODE:
    //	deep = false;
    //	break;
    //case DOCUMENT_NODE:
    //case DOCUMENT_TYPE_NODE:
    //cannot be imported.
    //case ENTITY_NODE:
    //case NOTATION_NODE：
    //can not hit in level3
    //default:throw e;
  }

  if (!node2) {
    node2 = node.cloneNode(false); //false
  }

  node2.ownerDocument = doc;
  node2.parentNode = null;

  if (deep) {
    var child = node.firstChild;

    while (child) {
      node2.appendChild(importNode(doc, child, deep));
      child = child.nextSibling;
    }
  }

  return node2;
} //
//var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
//					attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};


function cloneNode(doc, node, deep) {
  var node2 = new node.constructor();

  for (var n in node) {
    var v = node[n];

    if (typeof v != 'object') {
      if (v != node2[n]) {
        node2[n] = v;
      }
    }
  }

  if (node.childNodes) {
    node2.childNodes = new NodeList();
  }

  node2.ownerDocument = doc;

  switch (node2.nodeType) {
    case ELEMENT_NODE:
      var attrs = node.attributes;
      var attrs2 = node2.attributes = new NamedNodeMap();
      var len = attrs.length;
      attrs2._ownerElement = node2;

      for (var i = 0; i < len; i++) {
        node2.setAttributeNode(cloneNode(doc, attrs.item(i), true));
      }

      break;
      ;

    case ATTRIBUTE_NODE:
      deep = true;
  }

  if (deep) {
    var child = node.firstChild;

    while (child) {
      node2.appendChild(cloneNode(doc, child, deep));
      child = child.nextSibling;
    }
  }

  return node2;
}

function __set__(object, key, value) {
  object[key] = value;
} //do dynamic


try {
  if (Object.defineProperty) {
    Object.defineProperty(LiveNodeList.prototype, 'length', {
      get: function () {
        _updateLiveList(this);

        return this.$$length;
      }
    });
    Object.defineProperty(Node.prototype, 'textContent', {
      get: function () {
        return getTextContent(this);
      },
      set: function (data) {
        switch (this.nodeType) {
          case ELEMENT_NODE:
          case DOCUMENT_FRAGMENT_NODE:
            while (this.firstChild) {
              this.removeChild(this.firstChild);
            }

            if (data || String(data)) {
              this.appendChild(this.ownerDocument.createTextNode(data));
            }

            break;

          default:
            //TODO:
            this.data = data;
            this.value = data;
            this.nodeValue = data;
        }
      }
    });

    function getTextContent(node) {
      switch (node.nodeType) {
        case ELEMENT_NODE:
        case DOCUMENT_FRAGMENT_NODE:
          var buf = [];
          node = node.firstChild;

          while (node) {
            if (node.nodeType !== 7 && node.nodeType !== 8) {
              buf.push(getTextContent(node));
            }

            node = node.nextSibling;
          }

          return buf.join('');

        default:
          return node.nodeValue;
      }
    }

    __set__ = function (object, key, value) {
      //console.log(value)
      object['$$' + key] = value;
    };
  }
} catch (e) {//ie8
} //if(typeof require == 'function'){


exports.Node = Node;
exports.DOMException = DOMException;
exports.DOMImplementation = DOMImplementation;
exports.XMLSerializer = XMLSerializer; //}

/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
module.exports = freeGlobal;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(18)))

/***/ }),
/* 95 */
/***/ (function(module, exports) {

/**
 * A specialized version of `_.forEach` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns `array`.
 */
function arrayEach(array, iteratee) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    if (iteratee(array[index], index, array) === false) {
      break;
    }
  }

  return array;
}

module.exports = arrayEach;

/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {

var baseTimes = __webpack_require__(340),
    isArguments = __webpack_require__(97),
    isArray = __webpack_require__(12),
    isBuffer = __webpack_require__(98),
    isIndex = __webpack_require__(33),
    isTypedArray = __webpack_require__(99);
/** Used for built-in method references. */


var objectProto = Object.prototype;
/** Used to check objects for own properties. */

var hasOwnProperty = objectProto.hasOwnProperty;
/**
 * Creates an array of the enumerable property names of the array-like `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @param {boolean} inherited Specify returning inherited property names.
 * @returns {Array} Returns the array of property names.
 */

function arrayLikeKeys(value, inherited) {
  var isArr = isArray(value),
      isArg = !isArr && isArguments(value),
      isBuff = !isArr && !isArg && isBuffer(value),
      isType = !isArr && !isArg && !isBuff && isTypedArray(value),
      skipIndexes = isArr || isArg || isBuff || isType,
      result = skipIndexes ? baseTimes(value.length, String) : [],
      length = result.length;

  for (var key in value) {
    if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode.
    key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers.
    isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays.
    isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties.
    isIndex(key, length)))) {
      result.push(key);
    }
  }

  return result;
}

module.exports = arrayLikeKeys;

/***/ }),
/* 97 */
/***/ (function(module, exports, __webpack_require__) {

var baseIsArguments = __webpack_require__(341),
    isObjectLike = __webpack_require__(19);
/** Used for built-in method references. */


var objectProto = Object.prototype;
/** Used to check objects for own properties. */

var hasOwnProperty = objectProto.hasOwnProperty;
/** Built-in value references. */

var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
 * Checks if `value` is likely an `arguments` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 *  else `false`.
 * @example
 *
 * _.isArguments(function() { return arguments; }());
 * // => true
 *
 * _.isArguments([1, 2, 3]);
 * // => false
 */

var isArguments = baseIsArguments(function () {
  return arguments;
}()) ? baseIsArguments : function (value) {
  return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
};
module.exports = isArguments;

/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(9),
    stubFalse = __webpack_require__(342);
/** Detect free variable `exports`. */


var freeExports =  true && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */

var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */

var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */

var Buffer = moduleExports ? root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */

var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
 * Checks if `value` is a buffer.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
 * @example
 *
 * _.isBuffer(new Buffer(2));
 * // => true
 *
 * _.isBuffer(new Uint8Array(2));
 * // => false
 */

var isBuffer = nativeIsBuffer || stubFalse;
module.exports = isBuffer;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(43)(module)))

/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {

var baseIsTypedArray = __webpack_require__(343),
    baseUnary = __webpack_require__(344),
    nodeUtil = __webpack_require__(345);
/* Node.js helper references. */


var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/**
 * Checks if `value` is classified as a typed array.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 * @example
 *
 * _.isTypedArray(new Uint8Array);
 * // => true
 *
 * _.isTypedArray([]);
 * // => false
 */

var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
module.exports = isTypedArray;

/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {

var isPrototype = __webpack_require__(101),
    nativeKeys = __webpack_require__(346);
/** Used for built-in method references. */


var objectProto = Object.prototype;
/** Used to check objects for own properties. */

var hasOwnProperty = objectProto.hasOwnProperty;
/**
 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */

function baseKeys(object) {
  if (!isPrototype(object)) {
    return nativeKeys(object);
  }

  var result = [];

  for (var key in Object(object)) {
    if (hasOwnProperty.call(object, key) && key != 'constructor') {
      result.push(key);
    }
  }

  return result;
}

module.exports = baseKeys;

/***/ }),
/* 101 */
/***/ (function(module, exports) {

/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
 * Checks if `value` is likely a prototype object.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
 */

function isPrototype(value) {
  var Ctor = value && value.constructor,
      proto = typeof Ctor == 'function' && Ctor.prototype || objectProto;
  return value === proto;
}

module.exports = isPrototype;

/***/ }),
/* 102 */
/***/ (function(module, exports) {

/**
 * Creates a unary function that invokes `func` with its argument transformed.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {Function} transform The argument transform.
 * @returns {Function} Returns the new function.
 */
function overArg(func, transform) {
  return function (arg) {
    return func(transform(arg));
  };
}

module.exports = overArg;

/***/ }),
/* 103 */
/***/ (function(module, exports, __webpack_require__) {

var baseAssignValue = __webpack_require__(104),
    eq = __webpack_require__(46);
/** Used for built-in method references. */


var objectProto = Object.prototype;
/** Used to check objects for own properties. */

var hasOwnProperty = objectProto.hasOwnProperty;
/**
 * Assigns `value` to `key` of `object` if the existing value is not equivalent
 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */

function assignValue(object, key, value) {
  var objValue = object[key];

  if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || value === undefined && !(key in object)) {
    baseAssignValue(object, key, value);
  }
}

module.exports = assignValue;

/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {

var defineProperty = __webpack_require__(105);
/**
 * The base implementation of `assignValue` and `assignMergeValue` without
 * value checks.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */


function baseAssignValue(object, key, value) {
  if (key == '__proto__' && defineProperty) {
    defineProperty(object, key, {
      'configurable': true,
      'enumerable': true,
      'value': value,
      'writable': true
    });
  } else {
    object[key] = value;
  }
}

module.exports = baseAssignValue;

/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(21);

var defineProperty = function () {
  try {
    var func = getNative(Object, 'defineProperty');
    func({}, '', {});
    return func;
  } catch (e) {}
}();

module.exports = defineProperty;

/***/ }),
/* 106 */
/***/ (function(module, exports) {

/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */

var funcToString = funcProto.toString;
/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to convert.
 * @returns {string} Returns the source code.
 */

function toSource(func) {
  if (func != null) {
    try {
      return funcToString.call(func);
    } catch (e) {}

    try {
      return func + '';
    } catch (e) {}
  }

  return '';
}

module.exports = toSource;

/***/ }),
/* 107 */
/***/ (function(module, exports, __webpack_require__) {

var identity = __webpack_require__(34),
    overRest = __webpack_require__(356),
    setToString = __webpack_require__(108);
/**
 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @returns {Function} Returns the new function.
 */


function baseRest(func, start) {
  return setToString(overRest(func, start, identity), func + '');
}

module.exports = baseRest;

/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {

var baseSetToString = __webpack_require__(357),
    shortOut = __webpack_require__(109);
/**
 * Sets the `toString` method of `func` to return `string`.
 *
 * @private
 * @param {Function} func The function to modify.
 * @param {Function} string The `toString` result.
 * @returns {Function} Returns `func`.
 */


var setToString = shortOut(baseSetToString);
module.exports = setToString;

/***/ }),
/* 109 */
/***/ (function(module, exports) {

/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
    HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */

var nativeNow = Date.now;
/**
 * Creates a function that'll short out and invoke `identity` instead
 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
 * milliseconds.
 *
 * @private
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new shortable function.
 */

function shortOut(func) {
  var count = 0,
      lastCalled = 0;
  return function () {
    var stamp = nativeNow(),
        remaining = HOT_SPAN - (stamp - lastCalled);
    lastCalled = stamp;

    if (remaining > 0) {
      if (++count >= HOT_COUNT) {
        return arguments[0];
      }
    } else {
      count = 0;
    }

    return func.apply(undefined, arguments);
  };
}

module.exports = shortOut;

/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {

var arrayLikeKeys = __webpack_require__(96),
    baseKeysIn = __webpack_require__(360),
    isArrayLike = __webpack_require__(25);
/**
 * Creates an array of the own and inherited enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keysIn(new Foo);
 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
 */


function keysIn(object) {
  return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}

module.exports = keysIn;

/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {

var baseFindIndex = __webpack_require__(362),
    baseIsNaN = __webpack_require__(363),
    strictIndexOf = __webpack_require__(364);
/**
 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */


function baseIndexOf(array, value, fromIndex) {
  return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex);
}

module.exports = baseIndexOf;

/***/ }),
/* 112 */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(20),
    isArray = __webpack_require__(12),
    isObjectLike = __webpack_require__(19);
/** `Object#toString` result references. */


var stringTag = '[object String]';
/**
 * Checks if `value` is classified as a `String` primitive or object.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a string, else `false`.
 * @example
 *
 * _.isString('abc');
 * // => true
 *
 * _.isString(1);
 * // => false
 */

function isString(value) {
  return typeof value == 'string' || !isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag;
}

module.exports = isString;

/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {

var identity = __webpack_require__(34),
    metaMap = __webpack_require__(114);
/**
 * The base implementation of `setData` without support for hot loop shorting.
 *
 * @private
 * @param {Function} func The function to associate metadata with.
 * @param {*} data The metadata.
 * @returns {Function} Returns `func`.
 */


var baseSetData = !metaMap ? identity : function (func, data) {
  metaMap.set(func, data);
  return func;
};
module.exports = baseSetData;

/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {

var WeakMap = __webpack_require__(115);
/** Used to store function metadata. */


var metaMap = WeakMap && new WeakMap();
module.exports = metaMap;

/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(21),
    root = __webpack_require__(9);
/* Built-in method references that are verified to be native. */


var WeakMap = getNative(root, 'WeakMap');
module.exports = WeakMap;

/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {

var composeArgs = __webpack_require__(117),
    composeArgsRight = __webpack_require__(118),
    countHolders = __webpack_require__(369),
    createCtor = __webpack_require__(47),
    createRecurry = __webpack_require__(119),
    getHolder = __webpack_require__(74),
    reorder = __webpack_require__(380),
    replaceHolders = __webpack_require__(48),
    root = __webpack_require__(9);
/** Used to compose bitmasks for function metadata. */


var WRAP_BIND_FLAG = 1,
    WRAP_BIND_KEY_FLAG = 2,
    WRAP_CURRY_FLAG = 8,
    WRAP_CURRY_RIGHT_FLAG = 16,
    WRAP_ARY_FLAG = 128,
    WRAP_FLIP_FLAG = 512;
/**
 * Creates a function that wraps `func` to invoke it with optional `this`
 * binding of `thisArg`, partial application, and currying.
 *
 * @private
 * @param {Function|string} func The function or method name to wrap.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @param {*} [thisArg] The `this` binding of `func`.
 * @param {Array} [partials] The arguments to prepend to those provided to
 *  the new function.
 * @param {Array} [holders] The `partials` placeholder indexes.
 * @param {Array} [partialsRight] The arguments to append to those provided
 *  to the new function.
 * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
 * @param {Array} [argPos] The argument positions of the new function.
 * @param {number} [ary] The arity cap of `func`.
 * @param {number} [arity] The arity of `func`.
 * @returns {Function} Returns the new wrapped function.
 */

function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
  var isAry = bitmask & WRAP_ARY_FLAG,
      isBind = bitmask & WRAP_BIND_FLAG,
      isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
      isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
      isFlip = bitmask & WRAP_FLIP_FLAG,
      Ctor = isBindKey ? undefined : createCtor(func);

  function wrapper() {
    var length = arguments.length,
        args = Array(length),
        index = length;

    while (index--) {
      args[index] = arguments[index];
    }

    if (isCurried) {
      var placeholder = getHolder(wrapper),
          holdersCount = countHolders(args, placeholder);
    }

    if (partials) {
      args = composeArgs(args, partials, holders, isCurried);
    }

    if (partialsRight) {
      args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
    }

    length -= holdersCount;

    if (isCurried && length < arity) {
      var newHolders = replaceHolders(args, placeholder);
      return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length);
    }

    var thisBinding = isBind ? thisArg : this,
        fn = isBindKey ? thisBinding[func] : func;
    length = args.length;

    if (argPos) {
      args = reorder(args, argPos);
    } else if (isFlip && length > 1) {
      args.reverse();
    }

    if (isAry && ary < length) {
      args.length = ary;
    }

    if (this && this !== root && this instanceof wrapper) {
      fn = Ctor || createCtor(fn);
    }

    return fn.apply(thisBinding, args);
  }

  return wrapper;
}

module.exports = createHybrid;

/***/ }),
/* 117 */
/***/ (function(module, exports) {

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
 * Creates an array that is the composition of partially applied arguments,
 * placeholders, and provided arguments into a single array of arguments.
 *
 * @private
 * @param {Array} args The provided arguments.
 * @param {Array} partials The arguments to prepend to those provided.
 * @param {Array} holders The `partials` placeholder indexes.
 * @params {boolean} [isCurried] Specify composing for a curried function.
 * @returns {Array} Returns the new array of composed arguments.
 */

function composeArgs(args, partials, holders, isCurried) {
  var argsIndex = -1,
      argsLength = args.length,
      holdersLength = holders.length,
      leftIndex = -1,
      leftLength = partials.length,
      rangeLength = nativeMax(argsLength - holdersLength, 0),
      result = Array(leftLength + rangeLength),
      isUncurried = !isCurried;

  while (++leftIndex < leftLength) {
    result[leftIndex] = partials[leftIndex];
  }

  while (++argsIndex < holdersLength) {
    if (isUncurried || argsIndex < argsLength) {
      result[holders[argsIndex]] = args[argsIndex];
    }
  }

  while (rangeLength--) {
    result[leftIndex++] = args[argsIndex++];
  }

  return result;
}

module.exports = composeArgs;

/***/ }),
/* 118 */
/***/ (function(module, exports) {

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
 * This function is like `composeArgs` except that the arguments composition
 * is tailored for `_.partialRight`.
 *
 * @private
 * @param {Array} args The provided arguments.
 * @param {Array} partials The arguments to append to those provided.
 * @param {Array} holders The `partials` placeholder indexes.
 * @params {boolean} [isCurried] Specify composing for a curried function.
 * @returns {Array} Returns the new array of composed arguments.
 */

function composeArgsRight(args, partials, holders, isCurried) {
  var argsIndex = -1,
      argsLength = args.length,
      holdersIndex = -1,
      holdersLength = holders.length,
      rightIndex = -1,
      rightLength = partials.length,
      rangeLength = nativeMax(argsLength - holdersLength, 0),
      result = Array(rangeLength + rightLength),
      isUncurried = !isCurried;

  while (++argsIndex < rangeLength) {
    result[argsIndex] = args[argsIndex];
  }

  var offset = argsIndex;

  while (++rightIndex < rightLength) {
    result[offset + rightIndex] = partials[rightIndex];
  }

  while (++holdersIndex < holdersLength) {
    if (isUncurried || argsIndex < argsLength) {
      result[offset + holders[holdersIndex]] = args[argsIndex++];
    }
  }

  return result;
}

module.exports = composeArgsRight;

/***/ }),
/* 119 */
/***/ (function(module, exports, __webpack_require__) {

var isLaziable = __webpack_require__(370),
    setData = __webpack_require__(123),
    setWrapToString = __webpack_require__(124);
/** Used to compose bitmasks for function metadata. */


var WRAP_BIND_FLAG = 1,
    WRAP_BIND_KEY_FLAG = 2,
    WRAP_CURRY_BOUND_FLAG = 4,
    WRAP_CURRY_FLAG = 8,
    WRAP_PARTIAL_FLAG = 32,
    WRAP_PARTIAL_RIGHT_FLAG = 64;
/**
 * Creates a function that wraps `func` to continue currying.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @param {Function} wrapFunc The function to create the `func` wrapper.
 * @param {*} placeholder The placeholder value.
 * @param {*} [thisArg] The `this` binding of `func`.
 * @param {Array} [partials] The arguments to prepend to those provided to
 *  the new function.
 * @param {Array} [holders] The `partials` placeholder indexes.
 * @param {Array} [argPos] The argument positions of the new function.
 * @param {number} [ary] The arity cap of `func`.
 * @param {number} [arity] The arity of `func`.
 * @returns {Function} Returns the new wrapped function.
 */

function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
  var isCurry = bitmask & WRAP_CURRY_FLAG,
      newHolders = isCurry ? holders : undefined,
      newHoldersRight = isCurry ? undefined : holders,
      newPartials = isCurry ? partials : undefined,
      newPartialsRight = isCurry ? undefined : partials;
  bitmask |= isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG;
  bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);

  if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
    bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
  }

  var newData = [func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity];
  var result = wrapFunc.apply(undefined, newData);

  if (isLaziable(func)) {
    setData(result, newData);
  }

  result.placeholder = placeholder;
  return setWrapToString(result, func, bitmask);
}

module.exports = createRecurry;

/***/ }),
/* 120 */
/***/ (function(module, exports, __webpack_require__) {

var metaMap = __webpack_require__(114),
    noop = __webpack_require__(371);
/**
 * Gets metadata for `func`.
 *
 * @private
 * @param {Function} func The function to query.
 * @returns {*} Returns the metadata for `func`.
 */


var getData = !metaMap ? noop : function (func) {
  return metaMap.get(func);
};
module.exports = getData;

/***/ }),
/* 121 */
/***/ (function(module, exports, __webpack_require__) {

var baseCreate = __webpack_require__(71),
    baseLodash = __webpack_require__(73);
/**
 * The base constructor for creating `lodash` wrapper objects.
 *
 * @private
 * @param {*} value The value to wrap.
 * @param {boolean} [chainAll] Enable explicit method chain sequences.
 */


function LodashWrapper(value, chainAll) {
  this.__wrapped__ = value;
  this.__actions__ = [];
  this.__chain__ = !!chainAll;
  this.__index__ = 0;
  this.__values__ = undefined;
}

LodashWrapper.prototype = baseCreate(baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
module.exports = LodashWrapper;

/***/ }),
/* 122 */
/***/ (function(module, exports) {

/**
 * Copies the values of `source` to `array`.
 *
 * @private
 * @param {Array} source The array to copy values from.
 * @param {Array} [array=[]] The array to copy values to.
 * @returns {Array} Returns `array`.
 */
function copyArray(source, array) {
  var index = -1,
      length = source.length;
  array || (array = Array(length));

  while (++index < length) {
    array[index] = source[index];
  }

  return array;
}

module.exports = copyArray;

/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {

var baseSetData = __webpack_require__(113),
    shortOut = __webpack_require__(109);
/**
 * Sets metadata for `func`.
 *
 * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
 * period of time, it will trip its breaker and transition to an identity
 * function to avoid garbage collection pauses in V8. See
 * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
 * for more details.
 *
 * @private
 * @param {Function} func The function to associate metadata with.
 * @param {*} data The metadata.
 * @returns {Function} Returns `func`.
 */


var setData = shortOut(baseSetData);
module.exports = setData;

/***/ }),
/* 124 */
/***/ (function(module, exports, __webpack_require__) {

var getWrapDetails = __webpack_require__(376),
    insertWrapDetails = __webpack_require__(377),
    setToString = __webpack_require__(108),
    updateWrapDetails = __webpack_require__(378);
/**
 * Sets the `toString` method of `wrapper` to mimic the source of `reference`
 * with wrapper details in a comment at the top of the source body.
 *
 * @private
 * @param {Function} wrapper The function to modify.
 * @param {Function} reference The reference function.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @returns {Function} Returns `wrapper`.
 */


function setWrapToString(wrapper, reference, bitmask) {
  var source = reference + '';
  return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
}

module.exports = setWrapToString;

/***/ }),
/* 125 */
/***/ (function(module, exports, __webpack_require__) {

var ListCache = __webpack_require__(49),
    stackClear = __webpack_require__(391),
    stackDelete = __webpack_require__(392),
    stackGet = __webpack_require__(393),
    stackHas = __webpack_require__(394),
    stackSet = __webpack_require__(395);
/**
 * Creates a stack cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */


function Stack(entries) {
  var data = this.__data__ = new ListCache(entries);
  this.size = data.size;
} // Add methods to `Stack`.


Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
module.exports = Stack;

/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {

var baseIsEqualDeep = __webpack_require__(408),
    isObjectLike = __webpack_require__(19);
/**
 * The base implementation of `_.isEqual` which supports partial comparisons
 * and tracks traversed objects.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @param {boolean} bitmask The bitmask flags.
 *  1 - Unordered comparison
 *  2 - Partial comparison
 * @param {Function} [customizer] The function to customize comparisons.
 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 */


function baseIsEqual(value, other, bitmask, customizer, stack) {
  if (value === other) {
    return true;
  }

  if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) {
    return value !== value && other !== other;
  }

  return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}

module.exports = baseIsEqual;

/***/ }),
/* 127 */
/***/ (function(module, exports, __webpack_require__) {

var SetCache = __webpack_require__(409),
    arraySome = __webpack_require__(412),
    cacheHas = __webpack_require__(413);
/** Used to compose bitmasks for value comparisons. */


var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;
/**
 * A specialized version of `baseIsEqualDeep` for arrays with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Array} array The array to compare.
 * @param {Array} other The other array to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `array` and `other` objects.
 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
 */

function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
      arrLength = array.length,
      othLength = other.length;

  if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
    return false;
  } // Check that cyclic values are equal.


  var arrStacked = stack.get(array);
  var othStacked = stack.get(other);

  if (arrStacked && othStacked) {
    return arrStacked == other && othStacked == array;
  }

  var index = -1,
      result = true,
      seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : undefined;
  stack.set(array, other);
  stack.set(other, array); // Ignore non-index properties.

  while (++index < arrLength) {
    var arrValue = array[index],
        othValue = other[index];

    if (customizer) {
      var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
    }

    if (compared !== undefined) {
      if (compared) {
        continue;
      }

      result = false;
      break;
    } // Recursively compare arrays (susceptible to call stack limits).


    if (seen) {
      if (!arraySome(other, function (othValue, othIndex) {
        if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
          return seen.push(othIndex);
        }
      })) {
        result = false;
        break;
      }
    } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
      result = false;
      break;
    }
  }

  stack['delete'](array);
  stack['delete'](other);
  return result;
}

module.exports = equalArrays;

/***/ }),
/* 128 */
/***/ (function(module, exports, __webpack_require__) {

var arrayPush = __webpack_require__(129),
    isArray = __webpack_require__(12);
/**
 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @param {Function} symbolsFunc The function to get the symbols of `object`.
 * @returns {Array} Returns the array of property names and symbols.
 */


function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  var result = keysFunc(object);
  return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}

module.exports = baseGetAllKeys;

/***/ }),
/* 129 */
/***/ (function(module, exports) {

/**
 * Appends the elements of `values` to `array`.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {Array} values The values to append.
 * @returns {Array} Returns `array`.
 */
function arrayPush(array, values) {
  var index = -1,
      length = values.length,
      offset = array.length;

  while (++index < length) {
    array[offset + index] = values[index];
  }

  return array;
}

module.exports = arrayPush;

/***/ }),
/* 130 */
/***/ (function(module, exports, __webpack_require__) {

var arrayFilter = __webpack_require__(420),
    stubArray = __webpack_require__(131);
/** Used for built-in method references. */


var objectProto = Object.prototype;
/** Built-in value references. */

var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */

var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
 * Creates an array of the own enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */

var getSymbols = !nativeGetSymbols ? stubArray : function (object) {
  if (object == null) {
    return [];
  }

  object = Object(object);
  return arrayFilter(nativeGetSymbols(object), function (symbol) {
    return propertyIsEnumerable.call(object, symbol);
  });
};
module.exports = getSymbols;

/***/ }),
/* 131 */
/***/ (function(module, exports) {

/**
 * This method returns a new empty array.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {Array} Returns the new empty array.
 * @example
 *
 * var arrays = _.times(2, _.stubArray);
 *
 * console.log(arrays);
 * // => [[], []]
 *
 * console.log(arrays[0] === arrays[1]);
 * // => false
 */
function stubArray() {
  return [];
}

module.exports = stubArray;

/***/ }),
/* 132 */
/***/ (function(module, exports, __webpack_require__) {

var DataView = __webpack_require__(421),
    Map = __webpack_require__(75),
    Promise = __webpack_require__(422),
    Set = __webpack_require__(423),
    WeakMap = __webpack_require__(115),
    baseGetTag = __webpack_require__(20),
    toSource = __webpack_require__(106);
/** `Object#toString` result references. */


var mapTag = '[object Map]',
    objectTag = '[object Object]',
    promiseTag = '[object Promise]',
    setTag = '[object Set]',
    weakMapTag = '[object WeakMap]';
var dataViewTag = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */

var dataViewCtorString = toSource(DataView),
    mapCtorString = toSource(Map),
    promiseCtorString = toSource(Promise),
    setCtorString = toSource(Set),
    weakMapCtorString = toSource(WeakMap);
/**
 * Gets the `toStringTag` of `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */

var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.

if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag || Promise && getTag(Promise.resolve()) != promiseTag || Set && getTag(new Set()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) {
  getTag = function (value) {
    var result = baseGetTag(value),
        Ctor = result == objectTag ? value.constructor : undefined,
        ctorString = Ctor ? toSource(Ctor) : '';

    if (ctorString) {
      switch (ctorString) {
        case dataViewCtorString:
          return dataViewTag;

        case mapCtorString:
          return mapTag;

        case promiseCtorString:
          return promiseTag;

        case setCtorString:
          return setTag;

        case weakMapCtorString:
          return weakMapTag;
      }
    }

    return result;
  };
}

module.exports = getTag;

/***/ }),
/* 133 */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(16);
/**
 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` if suitable for strict
 *  equality comparisons, else `false`.
 */


function isStrictComparable(value) {
  return value === value && !isObject(value);
}

module.exports = isStrictComparable;

/***/ }),
/* 134 */
/***/ (function(module, exports) {

/**
 * A specialized version of `matchesProperty` for source values suitable
 * for strict equality comparisons, i.e. `===`.
 *
 * @private
 * @param {string} key The key of the property to get.
 * @param {*} srcValue The value to match.
 * @returns {Function} Returns the new spec function.
 */
function matchesStrictComparable(key, srcValue) {
  return function (object) {
    if (object == null) {
      return false;
    }

    return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
  };
}

module.exports = matchesStrictComparable;

/***/ }),
/* 135 */
/***/ (function(module, exports, __webpack_require__) {

var baseToString = __webpack_require__(430);
/**
 * Converts `value` to a string. An empty string is returned for `null`
 * and `undefined` values. The sign of `-0` is preserved.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 * @example
 *
 * _.toString(null);
 * // => ''
 *
 * _.toString(-0);
 * // => '-0'
 *
 * _.toString([1, 2, 3]);
 * // => '1,2,3'
 */


function toString(value) {
  return value == null ? '' : baseToString(value);
}

module.exports = toString;

/***/ }),
/* 136 */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.property` without support for deep paths.
 *
 * @private
 * @param {string} key The key of the property to get.
 * @returns {Function} Returns the new accessor function.
 */
function baseProperty(key) {
  return function (object) {
    return object == null ? undefined : object[key];
  };
}

module.exports = baseProperty;

/***/ }),
/* 137 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _defineProperty2 = __webpack_require__(445);

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

var _keys = __webpack_require__(451);

var _keys2 = _interopRequireDefault(_keys);

var _regenerator = __webpack_require__(459);

var _regenerator2 = _interopRequireDefault(_regenerator);

var _asyncToGenerator2 = __webpack_require__(462);

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _promise = __webpack_require__(86);

var _promise2 = _interopRequireDefault(_promise);

exports.default = createDriver;

var _utils = __webpack_require__(490);

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {
    default: obj
  };
}

function createDriver(name, property) {
  var storage = (0, _utils.getStorage)();
  var support = !!(storage && storage[property]);
  var driver = support ? storage[property] : {
    clear: function clear() {},
    get: function get() {},
    remove: function remove() {},
    set: function set() {}
  };

  var _clear = driver.clear.bind(driver);

  var get = driver.get.bind(driver);
  var remove = driver.remove.bind(driver);
  var set = driver.set.bind(driver);
  return {
    _driver: name,
    _support: support,
    _initStorage: function _initStorage() {
      return _promise2.default.resolve();
    },
    clear: function clear(callback) {
      var _this = this;

      return (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee() {
        return _regenerator2.default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _clear();

                if (callback) callback();

              case 2:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, _this);
      }))();
    },
    iterate: function iterate(iterator, callback) {
      var _this2 = this;

      return (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee2() {
        var items, keys;
        return _regenerator2.default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.next = 2;
                return (0, _utils.usePromise)(get, null);

              case 2:
                items = _context2.sent;
                keys = (0, _keys2.default)(items);
                keys.forEach(function (key, i) {
                  return iterator(items[key], key, i);
                });
                if (callback) callback();

              case 6:
              case 'end':
                return _context2.stop();
            }
          }
        }, _callee2, _this2);
      }))();
    },
    getItem: function getItem(key, callback) {
      var _this3 = this;

      return (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee3() {
        var result;
        return _regenerator2.default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.prev = 0;
                _context3.next = 3;
                return (0, _utils.usePromise)(get, key);

              case 3:
                result = _context3.sent;
                result = typeof key === 'string' ? result[key] : result;
                result = result === undefined ? null : result;
                if (callback) callback(null, result);
                return _context3.abrupt('return', result);

              case 10:
                _context3.prev = 10;
                _context3.t0 = _context3['catch'](0);
                if (callback) callback(_context3.t0);
                throw _context3.t0;

              case 14:
              case 'end':
                return _context3.stop();
            }
          }
        }, _callee3, _this3, [[0, 10]]);
      }))();
    },
    key: function key(n, callback) {
      var _this4 = this;

      return (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee4() {
        var results, key;
        return _regenerator2.default.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                _context4.next = 2;
                return (0, _utils.usePromise)(get, null);

              case 2:
                results = _context4.sent;
                key = (0, _keys2.default)(results)[n];
                if (callback) callback(key);
                return _context4.abrupt('return', key);

              case 6:
              case 'end':
                return _context4.stop();
            }
          }
        }, _callee4, _this4);
      }))();
    },
    keys: function keys(callback) {
      var _this5 = this;

      return (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee5() {
        var results, keys;
        return _regenerator2.default.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                _context5.next = 2;
                return (0, _utils.usePromise)(get, null);

              case 2:
                results = _context5.sent;
                keys = (0, _keys2.default)(results);
                if (callback) callback(keys);
                return _context5.abrupt('return', keys);

              case 6:
              case 'end':
                return _context5.stop();
            }
          }
        }, _callee5, _this5);
      }))();
    },
    length: function length(callback) {
      var _this6 = this;

      return (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee6() {
        var results, length;
        return _regenerator2.default.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                _context6.next = 2;
                return (0, _utils.usePromise)(get, null);

              case 2:
                results = _context6.sent;
                length = (0, _keys2.default)(results).length;
                if (callback) callback(length);
                return _context6.abrupt('return', length);

              case 6:
              case 'end':
                return _context6.stop();
            }
          }
        }, _callee6, _this6);
      }))();
    },
    removeItem: function removeItem(key, callback) {
      var _this7 = this;

      return (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee7() {
        return _regenerator2.default.wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                _context7.next = 2;
                return (0, _utils.usePromise)(remove, key);

              case 2:
                if (callback) callback();

              case 3:
              case 'end':
                return _context7.stop();
            }
          }
        }, _callee7, _this7);
      }))();
    },
    setItem: function setItem(key, value, callback) {
      var _this8 = this;

      return (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee8() {
        return _regenerator2.default.wrap(function _callee8$(_context8) {
          while (1) {
            switch (_context8.prev = _context8.next) {
              case 0:
                _context8.next = 2;
                return (0, _utils.usePromise)(set, (0, _defineProperty3.default)({}, key, value));

              case 2:
                if (callback) callback();

              case 3:
              case 'end':
                return _context8.stop();
            }
          }
        }, _callee8, _this8);
      }))();
    }
  };
}

/***/ }),
/* 138 */
/***/ (function(module, exports) {

module.exports = function (bitmap, value) {
  return {
    enumerable: !(bitmap & 1),
    configurable: !(bitmap & 2),
    writable: !(bitmap & 4),
    value: value
  };
};

/***/ }),
/* 139 */
/***/ (function(module, exports, __webpack_require__) {

// 7.1.13 ToObject(argument)
var defined = __webpack_require__(81);

module.exports = function (it) {
  return Object(defined(it));
};

/***/ }),
/* 140 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(454);

var enumBugKeys = __webpack_require__(144);

module.exports = Object.keys || function keys(O) {
  return $keys(O, enumBugKeys);
};

/***/ }),
/* 141 */
/***/ (function(module, exports, __webpack_require__) {

// 7.1.15 ToLength
var toInteger = __webpack_require__(83);

var min = Math.min;

module.exports = function (it) {
  return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};

/***/ }),
/* 142 */
/***/ (function(module, exports, __webpack_require__) {

var core = __webpack_require__(15);

var global = __webpack_require__(10);

var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});
(module.exports = function (key, value) {
  return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
  version: core.version,
  mode: __webpack_require__(85) ? 'pure' : 'global',
  copyright: '© 2020 Denis Pushkarev (zloirock.ru)'
});

/***/ }),
/* 143 */
/***/ (function(module, exports) {

var id = 0;
var px = Math.random();

module.exports = function (key) {
  return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};

/***/ }),
/* 144 */
/***/ (function(module, exports) {

// IE 8- don't enum bug keys
module.exports = 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'.split(',');

/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var LIBRARY = __webpack_require__(85);

var $export = __webpack_require__(26);

var redefine = __webpack_require__(467);

var hide = __webpack_require__(27);

var Iterators = __webpack_require__(38);

var $iterCreate = __webpack_require__(468);

var setToStringTag = __webpack_require__(87);

var getPrototypeOf = __webpack_require__(471);

var ITERATOR = __webpack_require__(13)('iterator');

var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`

var FF_ITERATOR = '@@iterator';
var KEYS = 'keys';
var VALUES = 'values';

var returnThis = function () {
  return this;
};

module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
  $iterCreate(Constructor, NAME, next);

  var getMethod = function (kind) {
    if (!BUGGY && kind in proto) return proto[kind];

    switch (kind) {
      case KEYS:
        return function keys() {
          return new Constructor(this, kind);
        };

      case VALUES:
        return function values() {
          return new Constructor(this, kind);
        };
    }

    return function entries() {
      return new Constructor(this, kind);
    };
  };

  var TAG = NAME + ' Iterator';
  var DEF_VALUES = DEFAULT == VALUES;
  var VALUES_BUG = false;
  var proto = Base.prototype;
  var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
  var $default = $native || getMethod(DEFAULT);
  var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
  var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
  var methods, key, IteratorPrototype; // Fix native

  if ($anyNative) {
    IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));

    if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
      // Set @@toStringTag to native iterators
      setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines

      if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis);
    }
  } // fix Array#{values, @@iterator}.name in V8 / FF


  if (DEF_VALUES && $native && $native.name !== VALUES) {
    VALUES_BUG = true;

    $default = function values() {
      return $native.call(this);
    };
  } // Define iterator


  if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
    hide(proto, ITERATOR, $default);
  } // Plug for library


  Iterators[NAME] = $default;
  Iterators[TAG] = returnThis;

  if (DEFAULT) {
    methods = {
      values: DEF_VALUES ? $default : getMethod(VALUES),
      keys: IS_SET ? $default : getMethod(KEYS),
      entries: $entries
    };
    if (FORCED) for (key in methods) {
      if (!(key in proto)) redefine(proto, key, methods[key]);
    } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
  }

  return methods;
};

/***/ }),
/* 146 */
/***/ (function(module, exports, __webpack_require__) {

var document = __webpack_require__(10).document;

module.exports = document && document.documentElement;

/***/ }),
/* 147 */
/***/ (function(module, exports, __webpack_require__) {

// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__(57);

var TAG = __webpack_require__(13)('toStringTag'); // ES3 wrong here


var ARG = cof(function () {
  return arguments;
}()) == 'Arguments'; // fallback for IE11 Script Access Denied error

var tryGet = function (it, key) {
  try {
    return it[key];
  } catch (e) {
    /* empty */
  }
};

module.exports = function (it) {
  var O, T, B;
  return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case
  : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case
  : ARG ? cof(O) // ES3 arguments fallback
  : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};

/***/ }),
/* 148 */
/***/ (function(module, exports, __webpack_require__) {

// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = __webpack_require__(22);

var aFunction = __webpack_require__(55);

var SPECIES = __webpack_require__(13)('species');

module.exports = function (O, D) {
  var C = anObject(O).constructor;
  var S;
  return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};

/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {

var ctx = __webpack_require__(54);

var invoke = __webpack_require__(482);

var html = __webpack_require__(146);

var cel = __webpack_require__(80);

var global = __webpack_require__(10);

var process = global.process;
var setTask = global.setImmediate;
var clearTask = global.clearImmediate;
var MessageChannel = global.MessageChannel;
var Dispatch = global.Dispatch;
var counter = 0;
var queue = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var defer, channel, port;

var run = function () {
  var id = +this; // eslint-disable-next-line no-prototype-builtins

  if (queue.hasOwnProperty(id)) {
    var fn = queue[id];
    delete queue[id];
    fn();
  }
};

var listener = function (event) {
  run.call(event.data);
}; // Node.js 0.9+ & IE10+ has setImmediate, otherwise:


if (!setTask || !clearTask) {
  setTask = function setImmediate(fn) {
    var args = [];
    var i = 1;

    while (arguments.length > i) args.push(arguments[i++]);

    queue[++counter] = function () {
      // eslint-disable-next-line no-new-func
      invoke(typeof fn == 'function' ? fn : Function(fn), args);
    };

    defer(counter);
    return counter;
  };

  clearTask = function clearImmediate(id) {
    delete queue[id];
  }; // Node.js 0.8-


  if (__webpack_require__(57)(process) == 'process') {
    defer = function (id) {
      process.nextTick(ctx(run, id, 1));
    }; // Sphere (JS game engine) Dispatch API

  } else if (Dispatch && Dispatch.now) {
    defer = function (id) {
      Dispatch.now(ctx(run, id, 1));
    }; // Browsers with MessageChannel, includes WebWorkers

  } else if (MessageChannel) {
    channel = new MessageChannel();
    port = channel.port2;
    channel.port1.onmessage = listener;
    defer = ctx(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers
    // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
  } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) {
    defer = function (id) {
      global.postMessage(id + '', '*');
    };

    global.addEventListener('message', listener, false); // IE8-
  } else if (ONREADYSTATECHANGE in cel('script')) {
    defer = function (id) {
      html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () {
        html.removeChild(this);
        run.call(id);
      };
    }; // Rest old browsers

  } else {
    defer = function (id) {
      setTimeout(ctx(run, id, 1), 0);
    };
  }
}

module.exports = {
  set: setTask,
  clear: clearTask
};

/***/ }),
/* 150 */
/***/ (function(module, exports) {

module.exports = function (exec) {
  try {
    return {
      e: false,
      v: exec()
    };
  } catch (e) {
    return {
      e: true,
      v: e
    };
  }
};

/***/ }),
/* 151 */
/***/ (function(module, exports, __webpack_require__) {

var anObject = __webpack_require__(22);

var isObject = __webpack_require__(37);

var newPromiseCapability = __webpack_require__(88);

module.exports = function (C, x) {
  anObject(C);
  if (isObject(x) && x.constructor === C) return x;
  var promiseCapability = newPromiseCapability.f(C);
  var resolve = promiseCapability.resolve;
  resolve(x);
  return promiseCapability.promise;
};

/***/ }),
/* 152 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _shims__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(0);
/*
    This program is distributed under the terms of the MIT license.
    Please see the LICENSE file for details.

    Copyright 2006-2008, OGG, LLC
*/

/* global ActiveXObject */


/** PrivateClass: Strophe.Request
 *  _Private_ helper class that provides a cross implementation abstraction
 *  for a BOSH related XMLHttpRequest.
 *
 *  The Strophe.Request class is used internally to encapsulate BOSH request
 *  information.  It is not meant to be used from user's code.
 */

_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Request = class Request {
  /** PrivateConstructor: Strophe.Request
   *  Create and initialize a new Strophe.Request object.
   *
   *  Parameters:
   *    (XMLElement) elem - The XML data to be sent in the request.
   *    (Function) func - The function that will be called when the
   *      XMLHttpRequest readyState changes.
   *    (Integer) rid - The BOSH rid attribute associated with this request.
   *    (Integer) sends - The number of times this same request has been sent.
   */
  constructor(elem, func, rid, sends) {
    this.id = ++_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"]._requestId;
    this.xmlData = elem;
    this.data = _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].serialize(elem); // save original function in case we need to make a new request
    // from this one.

    this.origFunc = func;
    this.func = func;
    this.rid = rid;
    this.date = NaN;
    this.sends = sends || 0;
    this.abort = false;
    this.dead = null;

    this.age = function () {
      if (!this.date) {
        return 0;
      }

      const now = new Date();
      return (now - this.date) / 1000;
    };

    this.timeDead = function () {
      if (!this.dead) {
        return 0;
      }

      const now = new Date();
      return (now - this.dead) / 1000;
    };

    this.xhr = this._newXHR();
  }
  /** PrivateFunction: getResponse
   *  Get a response from the underlying XMLHttpRequest.
   *
   *  This function attempts to get a response from the request and checks
   *  for errors.
   *
   *  Throws:
   *    "parsererror" - A parser error occured.
   *    "bad-format" - The entity has sent XML that cannot be processed.
   *
   *  Returns:
   *    The DOM element tree of the response.
   */


  getResponse() {
    let node = null;

    if (this.xhr.responseXML && this.xhr.responseXML.documentElement) {
      node = this.xhr.responseXML.documentElement;

      if (node.tagName === "parsererror") {
        _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("invalid response received");
        _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("responseText: " + this.xhr.responseText);
        _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("responseXML: " + _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].serialize(this.xhr.responseXML));
        throw new Error("parsererror");
      }
    } else if (this.xhr.responseText) {
      // In React Native, we may get responseText but no responseXML.  We can try to parse it manually.
      _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug("Got responseText but no responseXML; attempting to parse it with DOMParser...");
      node = new _shims__WEBPACK_IMPORTED_MODULE_0__[/* DOMParser */ "a"]().parseFromString(this.xhr.responseText, 'application/xml').documentElement;

      if (!node) {
        throw new Error('Parsing produced null node');
      } else if (node.querySelector('parsererror')) {
        _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("invalid response received: " + node.querySelector('parsererror').textContent);
        _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("responseText: " + this.xhr.responseText);
        const error = new Error();
        error.name = _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].ErrorCondition.BAD_FORMAT;
        throw error;
      }
    }

    return node;
  }
  /** PrivateFunction: _newXHR
   *  _Private_ helper function to create XMLHttpRequests.
   *
   *  This function creates XMLHttpRequests across all implementations.
   *
   *  Returns:
   *    A new XMLHttpRequest.
   */


  _newXHR() {
    let xhr = null;

    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest();

      if (xhr.overrideMimeType) {
        xhr.overrideMimeType("text/xml; charset=utf-8");
      }
    } else if (window.ActiveXObject) {
      xhr = new ActiveXObject("Microsoft.XMLHTTP");
    } // use Function.bind() to prepend ourselves as an argument


    xhr.onreadystatechange = this.func.bind(null, this);
    return xhr;
  }

};
/** Class: Strophe.Bosh
 *  _Private_ helper class that handles BOSH Connections
 *
 *  The Strophe.Bosh class is used internally by Strophe.Connection
 *  to encapsulate BOSH sessions. It is not meant to be used from user's code.
 */

/** File: bosh.js
 *  A JavaScript library to enable BOSH in Strophejs.
 *
 *  this library uses Bidirectional-streams Over Synchronous HTTP (BOSH)
 *  to emulate a persistent, stateful, two-way connection to an XMPP server.
 *  More information on BOSH can be found in XEP 124.
 */

/** PrivateConstructor: Strophe.Bosh
 *  Create and initialize a Strophe.Bosh object.
 *
 *  Parameters:
 *    (Strophe.Connection) connection - The Strophe.Connection that will use BOSH.
 *
 *  Returns:
 *    A new Strophe.Bosh object.
 */

_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Bosh = class Bosh {
  constructor(connection) {
    this._conn = connection;
    /* request id for body tags */

    this.rid = Math.floor(Math.random() * 4294967295);
    /* The current session ID. */

    this.sid = null; // default BOSH values

    this.hold = 1;
    this.wait = 60;
    this.window = 5;
    this.errors = 0;
    this.inactivity = null;
    this.lastResponseHeaders = null;
    this._requests = [];
  }
  /** PrivateFunction: _buildBody
   *  _Private_ helper function to generate the <body/> wrapper for BOSH.
   *
   *  Returns:
   *    A Strophe.Builder with a <body/> element.
   */


  _buildBody() {
    const bodyWrap = Object(_core__WEBPACK_IMPORTED_MODULE_1__[/* $build */ "a"])('body', {
      'rid': this.rid++,
      'xmlns': _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].NS.HTTPBIND
    });

    if (this.sid !== null) {
      bodyWrap.attrs({
        'sid': this.sid
      });
    }

    if (this._conn.options.keepalive && this._conn._sessionCachingSupported()) {
      this._cacheSession();
    }

    return bodyWrap;
  }
  /** PrivateFunction: _reset
   *  Reset the connection.
   *
   *  This function is called by the reset function of the Strophe Connection
   */


  _reset() {
    this.rid = Math.floor(Math.random() * 4294967295);
    this.sid = null;
    this.errors = 0;

    if (this._conn._sessionCachingSupported()) {
      window.sessionStorage.removeItem('strophe-bosh-session');
    }

    this._conn.nextValidRid(this.rid);
  }
  /** PrivateFunction: _connect
   *  _Private_ function that initializes the BOSH connection.
   *
   *  Creates and sends the Request that initializes the BOSH connection.
   */


  _connect(wait, hold, route) {
    this.wait = wait || this.wait;
    this.hold = hold || this.hold;
    this.errors = 0;

    const body = this._buildBody().attrs({
      "to": this._conn.domain,
      "xml:lang": "en",
      "wait": this.wait,
      "hold": this.hold,
      "content": "text/xml; charset=utf-8",
      "ver": "1.6",
      "xmpp:version": "1.0",
      "xmlns:xmpp": _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].NS.BOSH
    });

    if (route) {
      body.attrs({
        'route': route
      });
    }

    const _connect_cb = this._conn._connect_cb;

    this._requests.push(new _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Request(body.tree(), this._onRequestStateChange.bind(this, _connect_cb.bind(this._conn)), body.tree().getAttribute("rid")));

    this._throttledRequestHandler();
  }
  /** PrivateFunction: _attach
   *  Attach to an already created and authenticated BOSH session.
   *
   *  This function is provided to allow Strophe to attach to BOSH
   *  sessions which have been created externally, perhaps by a Web
   *  application.  This is often used to support auto-login type features
   *  without putting user credentials into the page.
   *
   *  Parameters:
   *    (String) jid - The full JID that is bound by the session.
   *    (String) sid - The SID of the BOSH session.
   *    (String) rid - The current RID of the BOSH session.  This RID
   *      will be used by the next request.
   *    (Function) callback The connect callback function.
   *    (Integer) wait - The optional HTTPBIND wait value.  This is the
   *      time the server will wait before returning an empty result for
   *      a request.  The default setting of 60 seconds is recommended.
   *      Other settings will require tweaks to the Strophe.TIMEOUT value.
   *    (Integer) hold - The optional HTTPBIND hold value.  This is the
   *      number of connections the server will hold at one time.  This
   *      should almost always be set to 1 (the default).
   *    (Integer) wind - The optional HTTBIND window value.  This is the
   *      allowed range of request ids that are valid.  The default is 5.
   */


  _attach(jid, sid, rid, callback, wait, hold, wind) {
    this._conn.jid = jid;
    this.sid = sid;
    this.rid = rid;
    this._conn.connect_callback = callback;
    this._conn.domain = _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].getDomainFromJid(this._conn.jid);
    this._conn.authenticated = true;
    this._conn.connected = true;
    this.wait = wait || this.wait;
    this.hold = hold || this.hold;
    this.window = wind || this.window;

    this._conn._changeConnectStatus(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.ATTACHED, null);
  }
  /** PrivateFunction: _restore
   *  Attempt to restore a cached BOSH session
   *
   *  Parameters:
   *    (String) jid - The full JID that is bound by the session.
   *      This parameter is optional but recommended, specifically in cases
   *      where prebinded BOSH sessions are used where it's important to know
   *      that the right session is being restored.
   *    (Function) callback The connect callback function.
   *    (Integer) wait - The optional HTTPBIND wait value.  This is the
   *      time the server will wait before returning an empty result for
   *      a request.  The default setting of 60 seconds is recommended.
   *      Other settings will require tweaks to the Strophe.TIMEOUT value.
   *    (Integer) hold - The optional HTTPBIND hold value.  This is the
   *      number of connections the server will hold at one time.  This
   *      should almost always be set to 1 (the default).
   *    (Integer) wind - The optional HTTBIND window value.  This is the
   *      allowed range of request ids that are valid.  The default is 5.
   */


  _restore(jid, callback, wait, hold, wind) {
    const session = JSON.parse(window.sessionStorage.getItem('strophe-bosh-session'));

    if (typeof session !== "undefined" && session !== null && session.rid && session.sid && session.jid && (typeof jid === "undefined" || jid === null || _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].getBareJidFromJid(session.jid) === _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].getBareJidFromJid(jid) || // If authcid is null, then it's an anonymous login, so
    // we compare only the domains:
    _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].getNodeFromJid(jid) === null && _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].getDomainFromJid(session.jid) === jid)) {
      this._conn.restored = true;

      this._attach(session.jid, session.sid, session.rid, callback, wait, hold, wind);
    } else {
      const error = new Error("_restore: no restoreable session.");
      error.name = "StropheSessionError";
      throw error;
    }
  }
  /** PrivateFunction: _cacheSession
   *  _Private_ handler for the beforeunload event.
   *
   *  This handler is used to process the Bosh-part of the initial request.
   *  Parameters:
   *    (Strophe.Request) bodyWrap - The received stanza.
   */


  _cacheSession() {
    if (this._conn.authenticated) {
      if (this._conn.jid && this.rid && this.sid) {
        window.sessionStorage.setItem('strophe-bosh-session', JSON.stringify({
          'jid': this._conn.jid,
          'rid': this.rid,
          'sid': this.sid
        }));
      }
    } else {
      window.sessionStorage.removeItem('strophe-bosh-session');
    }
  }
  /** PrivateFunction: _connect_cb
   *  _Private_ handler for initial connection request.
   *
   *  This handler is used to process the Bosh-part of the initial request.
   *  Parameters:
   *    (Strophe.Request) bodyWrap - The received stanza.
   */


  _connect_cb(bodyWrap) {
    const typ = bodyWrap.getAttribute("type");

    if (typ !== null && typ === "terminate") {
      // an error occurred
      let cond = bodyWrap.getAttribute("condition");
      _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("BOSH-Connection failed: " + cond);
      const conflict = bodyWrap.getElementsByTagName("conflict");

      if (cond !== null) {
        if (cond === "remote-stream-error" && conflict.length > 0) {
          cond = "conflict";
        }

        this._conn._changeConnectStatus(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.CONNFAIL, cond);
      } else {
        this._conn._changeConnectStatus(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.CONNFAIL, "unknown");
      }

      this._conn._doDisconnect(cond);

      return _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.CONNFAIL;
    } // check to make sure we don't overwrite these if _connect_cb is
    // called multiple times in the case of missing stream:features


    if (!this.sid) {
      this.sid = bodyWrap.getAttribute("sid");
    }

    const wind = bodyWrap.getAttribute('requests');

    if (wind) {
      this.window = parseInt(wind, 10);
    }

    const hold = bodyWrap.getAttribute('hold');

    if (hold) {
      this.hold = parseInt(hold, 10);
    }

    const wait = bodyWrap.getAttribute('wait');

    if (wait) {
      this.wait = parseInt(wait, 10);
    }

    const inactivity = bodyWrap.getAttribute('inactivity');

    if (inactivity) {
      this.inactivity = parseInt(inactivity, 10);
    }
  }
  /** PrivateFunction: _disconnect
   *  _Private_ part of Connection.disconnect for Bosh
   *
   *  Parameters:
   *    (Request) pres - This stanza will be sent before disconnecting.
   */


  _disconnect(pres) {
    this._sendTerminate(pres);
  }
  /** PrivateFunction: _doDisconnect
   *  _Private_ function to disconnect.
   *
   *  Resets the SID and RID.
   */


  _doDisconnect() {
    this.sid = null;
    this.rid = Math.floor(Math.random() * 4294967295);

    if (this._conn._sessionCachingSupported()) {
      window.sessionStorage.removeItem('strophe-bosh-session');
    }

    this._conn.nextValidRid(this.rid);
  }
  /** PrivateFunction: _emptyQueue
   * _Private_ function to check if the Request queue is empty.
   *
   *  Returns:
   *    True, if there are no Requests queued, False otherwise.
   */


  _emptyQueue() {
    return this._requests.length === 0;
  }
  /** PrivateFunction: _callProtocolErrorHandlers
   *  _Private_ function to call error handlers registered for HTTP errors.
   *
   *  Parameters:
   *    (Strophe.Request) req - The request that is changing readyState.
   */


  _callProtocolErrorHandlers(req) {
    const reqStatus = Bosh._getRequestStatus(req);

    const err_callback = this._conn.protocolErrorHandlers.HTTP[reqStatus];

    if (err_callback) {
      err_callback.call(this, reqStatus);
    }
  }
  /** PrivateFunction: _hitError
   *  _Private_ function to handle the error count.
   *
   *  Requests are resent automatically until their error count reaches
   *  5.  Each time an error is encountered, this function is called to
   *  increment the count and disconnect if the count is too high.
   *
   *  Parameters:
   *    (Integer) reqStatus - The request status.
   */


  _hitError(reqStatus) {
    this.errors++;
    _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].warn("request errored, status: " + reqStatus + ", number of errors: " + this.errors);

    if (this.errors > 4) {
      this._conn._onDisconnectTimeout();
    }
  }
  /** PrivateFunction: _no_auth_received
   *
   * Called on stream start/restart when no stream:features
   * has been received and sends a blank poll request.
   */


  _no_auth_received(callback) {
    _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].warn("Server did not yet offer a supported authentication " + "mechanism. Sending a blank poll request.");

    if (callback) {
      callback = callback.bind(this._conn);
    } else {
      callback = this._conn._connect_cb.bind(this._conn);
    }

    const body = this._buildBody();

    this._requests.push(new _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Request(body.tree(), this._onRequestStateChange.bind(this, callback), body.tree().getAttribute("rid")));

    this._throttledRequestHandler();
  }
  /** PrivateFunction: _onDisconnectTimeout
   *  _Private_ timeout handler for handling non-graceful disconnection.
   *
   *  Cancels all remaining Requests and clears the queue.
   */


  _onDisconnectTimeout() {
    this._abortAllRequests();
  }
  /** PrivateFunction: _abortAllRequests
   *  _Private_ helper function that makes sure all pending requests are aborted.
   */


  _abortAllRequests() {
    while (this._requests.length > 0) {
      const req = this._requests.pop();

      req.abort = true;
      req.xhr.abort();

      req.xhr.onreadystatechange = function () {};
    }
  }
  /** PrivateFunction: _onIdle
   *  _Private_ handler called by Strophe.Connection._onIdle
   *
   *  Sends all queued Requests or polls with empty Request if there are none.
   */


  _onIdle() {
    const data = this._conn._data; // if no requests are in progress, poll

    if (this._conn.authenticated && this._requests.length === 0 && data.length === 0 && !this._conn.disconnecting) {
      _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug("no requests during idle cycle, sending blank request");
      data.push(null);
    }

    if (this._conn.paused) {
      return;
    }

    if (this._requests.length < 2 && data.length > 0) {
      const body = this._buildBody();

      for (let i = 0; i < data.length; i++) {
        if (data[i] !== null) {
          if (data[i] === "restart") {
            body.attrs({
              "to": this._conn.domain,
              "xml:lang": "en",
              "xmpp:restart": "true",
              "xmlns:xmpp": _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].NS.BOSH
            });
          } else {
            body.cnode(data[i]).up();
          }
        }
      }

      delete this._conn._data;
      this._conn._data = [];

      this._requests.push(new _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Request(body.tree(), this._onRequestStateChange.bind(this, this._conn._dataRecv.bind(this._conn)), body.tree().getAttribute("rid")));

      this._throttledRequestHandler();
    }

    if (this._requests.length > 0) {
      const time_elapsed = this._requests[0].age();

      if (this._requests[0].dead !== null) {
        if (this._requests[0].timeDead() > Math.floor(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].SECONDARY_TIMEOUT * this.wait)) {
          this._throttledRequestHandler();
        }
      }

      if (time_elapsed > Math.floor(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].TIMEOUT * this.wait)) {
        _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].warn("Request " + this._requests[0].id + " timed out, over " + Math.floor(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].TIMEOUT * this.wait) + " seconds since last activity");

        this._throttledRequestHandler();
      }
    }
  }
  /** PrivateFunction: _getRequestStatus
   *
   *  Returns the HTTP status code from a Strophe.Request
   *
   *  Parameters:
   *    (Strophe.Request) req - The Strophe.Request instance.
   *    (Integer) def - The default value that should be returned if no
   *          status value was found.
   */


  static _getRequestStatus(req, def) {
    let reqStatus;

    if (req.xhr.readyState === 4) {
      try {
        reqStatus = req.xhr.status;
      } catch (e) {
        // ignore errors from undefined status attribute. Works
        // around a browser bug
        _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("Caught an error while retrieving a request's status, " + "reqStatus: " + reqStatus);
      }
    }

    if (typeof reqStatus === "undefined") {
      reqStatus = typeof def === 'number' ? def : 0;
    }

    return reqStatus;
  }
  /** PrivateFunction: _onRequestStateChange
   *  _Private_ handler for Strophe.Request state changes.
   *
   *  This function is called when the XMLHttpRequest readyState changes.
   *  It contains a lot of error handling logic for the many ways that
   *  requests can fail, and calls the request callback when requests
   *  succeed.
   *
   *  Parameters:
   *    (Function) func - The handler for the request.
   *    (Strophe.Request) req - The request that is changing readyState.
   */


  _onRequestStateChange(func, req) {
    _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug("request id " + req.id + "." + req.sends + " state changed to " + req.xhr.readyState);

    if (req.abort) {
      req.abort = false;
      return;
    }

    if (req.xhr.readyState !== 4) {
      // The request is not yet complete
      return;
    }

    const reqStatus = Bosh._getRequestStatus(req);

    this.lastResponseHeaders = req.xhr.getAllResponseHeaders();

    if (this._conn.disconnecting && reqStatus >= 400) {
      this._hitError(reqStatus);

      this._callProtocolErrorHandlers(req);

      return;
    }

    const valid_request = reqStatus > 0 && reqStatus < 500;
    const too_many_retries = req.sends > this._conn.maxRetries;

    if (valid_request || too_many_retries) {
      // remove from internal queue
      this._removeRequest(req);

      _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug("request id " + req.id + " should now be removed");
    }

    if (reqStatus === 200) {
      // request succeeded
      const reqIs0 = this._requests[0] === req;
      const reqIs1 = this._requests[1] === req; // if request 1 finished, or request 0 finished and request
      // 1 is over Strophe.SECONDARY_TIMEOUT seconds old, we need to
      // restart the other - both will be in the first spot, as the
      // completed request has been removed from the queue already

      if (reqIs1 || reqIs0 && this._requests.length > 0 && this._requests[0].age() > Math.floor(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].SECONDARY_TIMEOUT * this.wait)) {
        this._restartRequest(0);
      }

      this._conn.nextValidRid(Number(req.rid) + 1);

      _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug("request id " + req.id + "." + req.sends + " got 200");
      func(req); // call handler

      this.errors = 0;
    } else if (reqStatus === 0 || reqStatus >= 400 && reqStatus < 600 || reqStatus >= 12000) {
      // request failed
      _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("request id " + req.id + "." + req.sends + " error " + reqStatus + " happened");

      this._hitError(reqStatus);

      this._callProtocolErrorHandlers(req);

      if (reqStatus >= 400 && reqStatus < 500) {
        this._conn._changeConnectStatus(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.DISCONNECTING, null);

        this._conn._doDisconnect();
      }
    } else {
      _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("request id " + req.id + "." + req.sends + " error " + reqStatus + " happened");
    }

    if (!valid_request && !too_many_retries) {
      this._throttledRequestHandler();
    } else if (too_many_retries && !this._conn.connected) {
      this._conn._changeConnectStatus(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.CONNFAIL, "giving-up");
    }
  }
  /** PrivateFunction: _processRequest
   *  _Private_ function to process a request in the queue.
   *
   *  This function takes requests off the queue and sends them and
   *  restarts dead requests.
   *
   *  Parameters:
   *    (Integer) i - The index of the request in the queue.
   */


  _processRequest(i) {
    let req = this._requests[i];

    const reqStatus = Bosh._getRequestStatus(req, -1); // make sure we limit the number of retries


    if (req.sends > this._conn.maxRetries) {
      this._conn._onDisconnectTimeout();

      return;
    }

    const time_elapsed = req.age();
    const primary_timeout = !isNaN(time_elapsed) && time_elapsed > Math.floor(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].TIMEOUT * this.wait);
    const secondary_timeout = req.dead !== null && req.timeDead() > Math.floor(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].SECONDARY_TIMEOUT * this.wait);
    const server_error = req.xhr.readyState === 4 && (reqStatus < 1 || reqStatus >= 500);

    if (primary_timeout || secondary_timeout || server_error) {
      if (secondary_timeout) {
        _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error(`Request ${this._requests[i].id} timed out (secondary), restarting`);
      }

      req.abort = true;
      req.xhr.abort(); // setting to null fails on IE6, so set to empty function

      req.xhr.onreadystatechange = function () {};

      this._requests[i] = new _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Request(req.xmlData, req.origFunc, req.rid, req.sends);
      req = this._requests[i];
    }

    if (req.xhr.readyState === 0) {
      _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug("request id " + req.id + "." + req.sends + " posting");

      try {
        const content_type = this._conn.options.contentType || "text/xml; charset=utf-8";
        req.xhr.open("POST", this._conn.service, this._conn.options.sync ? false : true);

        if (typeof req.xhr.setRequestHeader !== 'undefined') {
          // IE9 doesn't have setRequestHeader
          req.xhr.setRequestHeader("Content-Type", content_type);
        }

        if (this._conn.options.withCredentials) {
          req.xhr.withCredentials = true;
        }
      } catch (e2) {
        _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("XHR open failed: " + e2.toString());

        if (!this._conn.connected) {
          this._conn._changeConnectStatus(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.CONNFAIL, "bad-service");
        }

        this._conn.disconnect();

        return;
      } // Fires the XHR request -- may be invoked immediately
      // or on a gradually expanding retry window for reconnects


      const sendFunc = () => {
        req.date = new Date();

        if (this._conn.options.customHeaders) {
          const headers = this._conn.options.customHeaders;

          for (const header in headers) {
            if (Object.prototype.hasOwnProperty.call(headers, header)) {
              req.xhr.setRequestHeader(header, headers[header]);
            }
          }
        }

        req.xhr.send(req.data);
      }; // Implement progressive backoff for reconnects --
      // First retry (send === 1) should also be instantaneous


      if (req.sends > 1) {
        // Using a cube of the retry number creates a nicely
        // expanding retry window
        const backoff = Math.min(Math.floor(_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].TIMEOUT * this.wait), Math.pow(req.sends, 3)) * 1000;
        setTimeout(function () {
          // XXX: setTimeout should be called only with function expressions (23974bc1)
          sendFunc();
        }, backoff);
      } else {
        sendFunc();
      }

      req.sends++;

      if (this._conn.xmlOutput !== _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Connection.prototype.xmlOutput) {
        if (req.xmlData.nodeName === this.strip && req.xmlData.childNodes.length) {
          this._conn.xmlOutput(req.xmlData.childNodes[0]);
        } else {
          this._conn.xmlOutput(req.xmlData);
        }
      }

      if (this._conn.rawOutput !== _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Connection.prototype.rawOutput) {
        this._conn.rawOutput(req.data);
      }
    } else {
      _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug("_processRequest: " + (i === 0 ? "first" : "second") + " request has readyState of " + req.xhr.readyState);
    }
  }
  /** PrivateFunction: _removeRequest
   *  _Private_ function to remove a request from the queue.
   *
   *  Parameters:
   *    (Strophe.Request) req - The request to remove.
   */


  _removeRequest(req) {
    _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug("removing request");

    for (let i = this._requests.length - 1; i >= 0; i--) {
      if (req === this._requests[i]) {
        this._requests.splice(i, 1);
      }
    } // IE6 fails on setting to null, so set to empty function


    req.xhr.onreadystatechange = function () {};

    this._throttledRequestHandler();
  }
  /** PrivateFunction: _restartRequest
   *  _Private_ function to restart a request that is presumed dead.
   *
   *  Parameters:
   *    (Integer) i - The index of the request in the queue.
   */


  _restartRequest(i) {
    const req = this._requests[i];

    if (req.dead === null) {
      req.dead = new Date();
    }

    this._processRequest(i);
  }
  /** PrivateFunction: _reqToData
   * _Private_ function to get a stanza out of a request.
   *
   * Tries to extract a stanza out of a Request Object.
   * When this fails the current connection will be disconnected.
   *
   *  Parameters:
   *    (Object) req - The Request.
   *
   *  Returns:
   *    The stanza that was passed.
   */


  _reqToData(req) {
    try {
      return req.getResponse();
    } catch (e) {
      if (e.message !== "parsererror") {
        throw e;
      }

      this._conn.disconnect("strophe-parsererror");
    }
  }
  /** PrivateFunction: _sendTerminate
   *  _Private_ function to send initial disconnect sequence.
   *
   *  This is the first step in a graceful disconnect.  It sends
   *  the BOSH server a terminate body and includes an unavailable
   *  presence if authentication has completed.
   */


  _sendTerminate(pres) {
    _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug("_sendTerminate was called");

    const body = this._buildBody().attrs({
      type: "terminate"
    });

    if (pres) {
      body.cnode(pres.tree());
    }

    const req = new _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Request(body.tree(), this._onRequestStateChange.bind(this, this._conn._dataRecv.bind(this._conn)), body.tree().getAttribute("rid"));

    this._requests.push(req);

    this._throttledRequestHandler();
  }
  /** PrivateFunction: _send
   *  _Private_ part of the Connection.send function for BOSH
   *
   * Just triggers the RequestHandler to send the messages that are in the queue
   */


  _send() {
    clearTimeout(this._conn._idleTimeout);

    this._throttledRequestHandler();

    this._conn._idleTimeout = setTimeout(() => this._conn._onIdle(), 100);
  }
  /** PrivateFunction: _sendRestart
   *
   *  Send an xmpp:restart stanza.
   */


  _sendRestart() {
    this._throttledRequestHandler();

    clearTimeout(this._conn._idleTimeout);
  }
  /** PrivateFunction: _throttledRequestHandler
   *  _Private_ function to throttle requests to the connection window.
   *
   *  This function makes sure we don't send requests so fast that the
   *  request ids overflow the connection window in the case that one
   *  request died.
   */


  _throttledRequestHandler() {
    if (!this._requests) {
      _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug("_throttledRequestHandler called with " + "undefined requests");
    } else {
      _core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug("_throttledRequestHandler called with " + this._requests.length + " requests");
    }

    if (!this._requests || this._requests.length === 0) {
      return;
    }

    if (this._requests.length > 0) {
      this._processRequest(0);
    }

    if (this._requests.length > 1 && Math.abs(this._requests[0].rid - this._requests[1].rid) < this.window) {
      this._processRequest(1);
    }
  }

};
/** Variable: strip
 *
 *  BOSH-Connections will have all stanzas wrapped in a <body> tag when
 *  passed to <Strophe.Connection.xmlInput> or <Strophe.Connection.xmlOutput>.
 *  To strip this tag, User code can set <Strophe.Bosh.strip> to "body":
 *
 *  > Strophe.Bosh.prototype.strip = "body";
 *
 *  This will enable stripping of the body tag in both
 *  <Strophe.Connection.xmlInput> and <Strophe.Connection.xmlOutput>.
 */

_core__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Bosh.prototype.strip = null;

/***/ }),
/* 153 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.0 by @mathias */
;

(function (root) {
  /** Detect free variables */
  var freeExports =  true && exports && !exports.nodeType && exports;
  var freeModule =  true && module && !module.nodeType && module;
  var freeGlobal = typeof global == 'object' && global;

  if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal) {
    root = freeGlobal;
  }
  /**
   * The `punycode` object.
   * @name punycode
   * @type Object
   */


  var punycode,

  /** Highest positive signed 32-bit float value */
  maxInt = 2147483647,
      // aka. 0x7FFFFFFF or 2^31-1

  /** Bootstring parameters */
  base = 36,
      tMin = 1,
      tMax = 26,
      skew = 38,
      damp = 700,
      initialBias = 72,
      initialN = 128,
      // 0x80
  delimiter = '-',
      // '\x2D'

  /** Regular expressions */
  regexPunycode = /^xn--/,
      regexNonASCII = /[^\x20-\x7E]/,
      // unprintable ASCII chars + non-ASCII chars
  regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g,
      // RFC 3490 separators

  /** Error messages */
  errors = {
    'overflow': 'Overflow: input needs wider integers to process',
    'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
    'invalid-input': 'Invalid input'
  },

  /** Convenience shortcuts */
  baseMinusTMin = base - tMin,
      floor = Math.floor,
      stringFromCharCode = String.fromCharCode,

  /** Temporary variable */
  key;
  /*--------------------------------------------------------------------------*/

  /**
   * A generic error utility function.
   * @private
   * @param {String} type The error type.
   * @returns {Error} Throws a `RangeError` with the applicable error message.
   */

  function error(type) {
    throw new RangeError(errors[type]);
  }
  /**
   * A generic `Array#map` utility function.
   * @private
   * @param {Array} array The array to iterate over.
   * @param {Function} callback The function that gets called for every array
   * item.
   * @returns {Array} A new array of values returned by the callback function.
   */


  function map(array, fn) {
    var length = array.length;
    var result = [];

    while (length--) {
      result[length] = fn(array[length]);
    }

    return result;
  }
  /**
   * A simple `Array#map`-like wrapper to work with domain name strings or email
   * addresses.
   * @private
   * @param {String} domain The domain name or email address.
   * @param {Function} callback The function that gets called for every
   * character.
   * @returns {Array} A new string of characters returned by the callback
   * function.
   */


  function mapDomain(string, fn) {
    var parts = string.split('@');
    var result = '';

    if (parts.length > 1) {
      // In email addresses, only the domain name should be punycoded. Leave
      // the local part (i.e. everything up to `@`) intact.
      result = parts[0] + '@';
      string = parts[1];
    } // Avoid `split(regex)` for IE8 compatibility. See #17.


    string = string.replace(regexSeparators, '\x2E');
    var labels = string.split('.');
    var encoded = map(labels, fn).join('.');
    return result + encoded;
  }
  /**
   * Creates an array containing the numeric code points of each Unicode
   * character in the string. While JavaScript uses UCS-2 internally,
   * this function will convert a pair of surrogate halves (each of which
   * UCS-2 exposes as separate characters) into a single code point,
   * matching UTF-16.
   * @see `punycode.ucs2.encode`
   * @see <https://mathiasbynens.be/notes/javascript-encoding>
   * @memberOf punycode.ucs2
   * @name decode
   * @param {String} string The Unicode input string (UCS-2).
   * @returns {Array} The new array of code points.
   */


  function ucs2decode(string) {
    var output = [],
        counter = 0,
        length = string.length,
        value,
        extra;

    while (counter < length) {
      value = string.charCodeAt(counter++);

      if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
        // high surrogate, and there is a next character
        extra = string.charCodeAt(counter++);

        if ((extra & 0xFC00) == 0xDC00) {
          // low surrogate
          output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
        } else {
          // unmatched surrogate; only append this code unit, in case the next
          // code unit is the high surrogate of a surrogate pair
          output.push(value);
          counter--;
        }
      } else {
        output.push(value);
      }
    }

    return output;
  }
  /**
   * Creates a string based on an array of numeric code points.
   * @see `punycode.ucs2.decode`
   * @memberOf punycode.ucs2
   * @name encode
   * @param {Array} codePoints The array of numeric code points.
   * @returns {String} The new Unicode string (UCS-2).
   */


  function ucs2encode(array) {
    return map(array, function (value) {
      var output = '';

      if (value > 0xFFFF) {
        value -= 0x10000;
        output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
        value = 0xDC00 | value & 0x3FF;
      }

      output += stringFromCharCode(value);
      return output;
    }).join('');
  }
  /**
   * Converts a basic code point into a digit/integer.
   * @see `digitToBasic()`
   * @private
   * @param {Number} codePoint The basic numeric code point value.
   * @returns {Number} The numeric value of a basic code point (for use in
   * representing integers) in the range `0` to `base - 1`, or `base` if
   * the code point does not represent a value.
   */


  function basicToDigit(codePoint) {
    if (codePoint - 48 < 10) {
      return codePoint - 22;
    }

    if (codePoint - 65 < 26) {
      return codePoint - 65;
    }

    if (codePoint - 97 < 26) {
      return codePoint - 97;
    }

    return base;
  }
  /**
   * Converts a digit/integer into a basic code point.
   * @see `basicToDigit()`
   * @private
   * @param {Number} digit The numeric value of a basic code point.
   * @returns {Number} The basic code point whose value (when used for
   * representing integers) is `digit`, which needs to be in the range
   * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
   * used; else, the lowercase form is used. The behavior is undefined
   * if `flag` is non-zero and `digit` has no uppercase form.
   */


  function digitToBasic(digit, flag) {
    //  0..25 map to ASCII a..z or A..Z
    // 26..35 map to ASCII 0..9
    return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  }
  /**
   * Bias adaptation function as per section 3.4 of RFC 3492.
   * https://tools.ietf.org/html/rfc3492#section-3.4
   * @private
   */


  function adapt(delta, numPoints, firstTime) {
    var k = 0;
    delta = firstTime ? floor(delta / damp) : delta >> 1;
    delta += floor(delta / numPoints);

    for (;
    /* no initialization */
    delta > baseMinusTMin * tMax >> 1; k += base) {
      delta = floor(delta / baseMinusTMin);
    }

    return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  }
  /**
   * Converts a Punycode string of ASCII-only symbols to a string of Unicode
   * symbols.
   * @memberOf punycode
   * @param {String} input The Punycode string of ASCII-only symbols.
   * @returns {String} The resulting string of Unicode symbols.
   */


  function decode(input) {
    // Don't use UCS-2
    var output = [],
        inputLength = input.length,
        out,
        i = 0,
        n = initialN,
        bias = initialBias,
        basic,
        j,
        index,
        oldi,
        w,
        k,
        digit,
        t,

    /** Cached calculation results */
    baseMinusT; // Handle the basic code points: let `basic` be the number of input code
    // points before the last delimiter, or `0` if there is none, then copy
    // the first basic code points to the output.

    basic = input.lastIndexOf(delimiter);

    if (basic < 0) {
      basic = 0;
    }

    for (j = 0; j < basic; ++j) {
      // if it's not a basic code point
      if (input.charCodeAt(j) >= 0x80) {
        error('not-basic');
      }

      output.push(input.charCodeAt(j));
    } // Main decoding loop: start just after the last delimiter if any basic code
    // points were copied; start at the beginning otherwise.


    for (index = basic > 0 ? basic + 1 : 0; index < inputLength;)
    /* no final expression */
    {
      // `index` is the index of the next character to be consumed.
      // Decode a generalized variable-length integer into `delta`,
      // which gets added to `i`. The overflow checking is easier
      // if we increase `i` as we go, then subtract off its starting
      // value at the end to obtain `delta`.
      for (oldi = i, w = 1, k = base;;
      /* no condition */
      k += base) {
        if (index >= inputLength) {
          error('invalid-input');
        }

        digit = basicToDigit(input.charCodeAt(index++));

        if (digit >= base || digit > floor((maxInt - i) / w)) {
          error('overflow');
        }

        i += digit * w;
        t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;

        if (digit < t) {
          break;
        }

        baseMinusT = base - t;

        if (w > floor(maxInt / baseMinusT)) {
          error('overflow');
        }

        w *= baseMinusT;
      }

      out = output.length + 1;
      bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`,
      // incrementing `n` each time, so we'll fix that now:

      if (floor(i / out) > maxInt - n) {
        error('overflow');
      }

      n += floor(i / out);
      i %= out; // Insert `n` at position `i` of the output

      output.splice(i++, 0, n);
    }

    return ucs2encode(output);
  }
  /**
   * Converts a string of Unicode symbols (e.g. a domain name label) to a
   * Punycode string of ASCII-only symbols.
   * @memberOf punycode
   * @param {String} input The string of Unicode symbols.
   * @returns {String} The resulting Punycode string of ASCII-only symbols.
   */


  function encode(input) {
    var n,
        delta,
        handledCPCount,
        basicLength,
        bias,
        j,
        m,
        q,
        k,
        t,
        currentValue,
        output = [],

    /** `inputLength` will hold the number of code points in `input`. */
    inputLength,

    /** Cached calculation results */
    handledCPCountPlusOne,
        baseMinusT,
        qMinusT; // Convert the input in UCS-2 to Unicode

    input = ucs2decode(input); // Cache the length

    inputLength = input.length; // Initialize the state

    n = initialN;
    delta = 0;
    bias = initialBias; // Handle the basic code points

    for (j = 0; j < inputLength; ++j) {
      currentValue = input[j];

      if (currentValue < 0x80) {
        output.push(stringFromCharCode(currentValue));
      }
    }

    handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled;
    // `basicLength` is the number of basic code points.
    // Finish the basic string - if it is not empty - with a delimiter

    if (basicLength) {
      output.push(delimiter);
    } // Main encoding loop:


    while (handledCPCount < inputLength) {
      // All non-basic code points < n have been handled already. Find the next
      // larger one:
      for (m = maxInt, j = 0; j < inputLength; ++j) {
        currentValue = input[j];

        if (currentValue >= n && currentValue < m) {
          m = currentValue;
        }
      } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
      // but guard against overflow


      handledCPCountPlusOne = handledCPCount + 1;

      if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
        error('overflow');
      }

      delta += (m - n) * handledCPCountPlusOne;
      n = m;

      for (j = 0; j < inputLength; ++j) {
        currentValue = input[j];

        if (currentValue < n && ++delta > maxInt) {
          error('overflow');
        }

        if (currentValue == n) {
          // Represent delta as a generalized variable-length integer
          for (q = delta, k = base;;
          /* no condition */
          k += base) {
            t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;

            if (q < t) {
              break;
            }

            qMinusT = q - t;
            baseMinusT = base - t;
            output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
            q = floor(qMinusT / baseMinusT);
          }

          output.push(stringFromCharCode(digitToBasic(q, 0)));
          bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
          delta = 0;
          ++handledCPCount;
        }
      }

      ++delta;
      ++n;
    }

    return output.join('');
  }
  /**
   * Converts a Punycode string representing a domain name or an email address
   * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
   * it doesn't matter if you call it on a string that has already been
   * converted to Unicode.
   * @memberOf punycode
   * @param {String} input The Punycoded domain name or email address to
   * convert to Unicode.
   * @returns {String} The Unicode representation of the given Punycode
   * string.
   */


  function toUnicode(input) {
    return mapDomain(input, function (string) {
      return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
    });
  }
  /**
   * Converts a Unicode string representing a domain name or an email address to
   * Punycode. Only the non-ASCII parts of the domain name will be converted,
   * i.e. it doesn't matter if you call it with a domain that's already in
   * ASCII.
   * @memberOf punycode
   * @param {String} input The domain name or email address to convert, as a
   * Unicode string.
   * @returns {String} The Punycode representation of the given domain name or
   * email address.
   */


  function toASCII(input) {
    return mapDomain(input, function (string) {
      return regexNonASCII.test(string) ? 'xn--' + encode(string) : string;
    });
  }
  /*--------------------------------------------------------------------------*/

  /** Define the public API */


  punycode = {
    /**
     * A string representing the current Punycode.js version number.
     * @memberOf punycode
     * @type String
     */
    'version': '1.3.2',

    /**
     * An object of methods to convert from JavaScript's internal character
     * representation (UCS-2) to Unicode code points, and back.
     * @see <https://mathiasbynens.be/notes/javascript-encoding>
     * @memberOf punycode
     * @type Object
     */
    'ucs2': {
      'decode': ucs2decode,
      'encode': ucs2encode
    },
    'decode': decode,
    'encode': encode,
    'toASCII': toASCII,
    'toUnicode': toUnicode
  };
  /** Expose `punycode` */
  // Some AMD build optimizers, like r.js, check for specific condition patterns
  // like the following:

  if (true) {
    !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
      return punycode;
    }).call(exports, __webpack_require__, exports, module),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  } else {}
})(this);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(43)(module), __webpack_require__(18)))

/***/ }),
/* 154 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * URI.js - Mutating URLs
 * IPv6 Support
 *
 * Version: 1.19.6
 *
 * Author: Rodney Rehm
 * Web: http://medialize.github.io/URI.js/
 *
 * Licensed under
 *   MIT License http://www.opensource.org/licenses/mit-license
 *
 */
(function (root, factory) {
  'use strict'; // https://github.com/umdjs/umd/blob/master/returnExports.js

  if ( true && module.exports) {
    // Node
    module.exports = factory();
  } else if (true) {
    // AMD. Register as an anonymous module.
    !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
				__WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  } else {}
})(this, function (root) {
  'use strict';
  /*
  var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156";
  var _out = IPv6.best(_in);
  var _expected = "fe80::204:61ff:fe9d:f156";
   console.log(_in, _out, _expected, _out === _expected);
  */
  // save current IPv6 variable, if any

  var _IPv6 = root && root.IPv6;

  function bestPresentation(address) {
    // based on:
    // Javascript to test an IPv6 address for proper format, and to
    // present the "best text representation" according to IETF Draft RFC at
    // http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04
    // 8 Feb 2010 Rich Brown, Dartware, LLC
    // Please feel free to use this code as long as you provide a link to
    // http://www.intermapper.com
    // http://intermapper.com/support/tools/IPV6-Validator.aspx
    // http://download.dartware.com/thirdparty/ipv6validator.js
    var _address = address.toLowerCase();

    var segments = _address.split(':');

    var length = segments.length;
    var total = 8; // trim colons (:: or ::a:b:c… or …a:b:c::)

    if (segments[0] === '' && segments[1] === '' && segments[2] === '') {
      // must have been ::
      // remove first two items
      segments.shift();
      segments.shift();
    } else if (segments[0] === '' && segments[1] === '') {
      // must have been ::xxxx
      // remove the first item
      segments.shift();
    } else if (segments[length - 1] === '' && segments[length - 2] === '') {
      // must have been xxxx::
      segments.pop();
    }

    length = segments.length; // adjust total segments for IPv4 trailer

    if (segments[length - 1].indexOf('.') !== -1) {
      // found a "." which means IPv4
      total = 7;
    } // fill empty segments them with "0000"


    var pos;

    for (pos = 0; pos < length; pos++) {
      if (segments[pos] === '') {
        break;
      }
    }

    if (pos < total) {
      segments.splice(pos, 1, '0000');

      while (segments.length < total) {
        segments.splice(pos, 0, '0000');
      }
    } // strip leading zeros


    var _segments;

    for (var i = 0; i < total; i++) {
      _segments = segments[i].split('');

      for (var j = 0; j < 3; j++) {
        if (_segments[0] === '0' && _segments.length > 1) {
          _segments.splice(0, 1);
        } else {
          break;
        }
      }

      segments[i] = _segments.join('');
    } // find longest sequence of zeroes and coalesce them into one segment


    var best = -1;
    var _best = 0;
    var _current = 0;
    var current = -1;
    var inzeroes = false; // i; already declared

    for (i = 0; i < total; i++) {
      if (inzeroes) {
        if (segments[i] === '0') {
          _current += 1;
        } else {
          inzeroes = false;

          if (_current > _best) {
            best = current;
            _best = _current;
          }
        }
      } else {
        if (segments[i] === '0') {
          inzeroes = true;
          current = i;
          _current = 1;
        }
      }
    }

    if (_current > _best) {
      best = current;
      _best = _current;
    }

    if (_best > 1) {
      segments.splice(best, _best, '');
    }

    length = segments.length; // assemble remaining segments

    var result = '';

    if (segments[0] === '') {
      result = ':';
    }

    for (i = 0; i < length; i++) {
      result += segments[i];

      if (i === length - 1) {
        break;
      }

      result += ':';
    }

    if (segments[length - 1] === '') {
      result += ':';
    }

    return result;
  }

  function noConflict() {
    /*jshint validthis: true */
    if (root.IPv6 === this) {
      root.IPv6 = _IPv6;
    }

    return this;
  }

  return {
    best: bestPresentation,
    noConflict: noConflict
  };
});

/***/ }),
/* 155 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * URI.js - Mutating URLs
 * Second Level Domain (SLD) Support
 *
 * Version: 1.19.6
 *
 * Author: Rodney Rehm
 * Web: http://medialize.github.io/URI.js/
 *
 * Licensed under
 *   MIT License http://www.opensource.org/licenses/mit-license
 *
 */
(function (root, factory) {
  'use strict'; // https://github.com/umdjs/umd/blob/master/returnExports.js

  if ( true && module.exports) {
    // Node
    module.exports = factory();
  } else if (true) {
    // AMD. Register as an anonymous module.
    !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
				__WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  } else {}
})(this, function (root) {
  'use strict'; // save current SecondLevelDomains variable, if any

  var _SecondLevelDomains = root && root.SecondLevelDomains;

  var SLD = {
    // list of known Second Level Domains
    // converted list of SLDs from https://github.com/gavingmiller/second-level-domains
    // ----
    // publicsuffix.org is more current and actually used by a couple of browsers internally.
    // downside is it also contains domains like "dyndns.org" - which is fine for the security
    // issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js
    // ----
    list: {
      'ac': ' com gov mil net org ',
      'ae': ' ac co gov mil name net org pro sch ',
      'af': ' com edu gov net org ',
      'al': ' com edu gov mil net org ',
      'ao': ' co ed gv it og pb ',
      'ar': ' com edu gob gov int mil net org tur ',
      'at': ' ac co gv or ',
      'au': ' asn com csiro edu gov id net org ',
      'ba': ' co com edu gov mil net org rs unbi unmo unsa untz unze ',
      'bb': ' biz co com edu gov info net org store tv ',
      'bh': ' biz cc com edu gov info net org ',
      'bn': ' com edu gov net org ',
      'bo': ' com edu gob gov int mil net org tv ',
      'br': ' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ',
      'bs': ' com edu gov net org ',
      'bz': ' du et om ov rg ',
      'ca': ' ab bc mb nb nf nl ns nt nu on pe qc sk yk ',
      'ck': ' biz co edu gen gov info net org ',
      'cn': ' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ',
      'co': ' com edu gov mil net nom org ',
      'cr': ' ac c co ed fi go or sa ',
      'cy': ' ac biz com ekloges gov ltd name net org parliament press pro tm ',
      'do': ' art com edu gob gov mil net org sld web ',
      'dz': ' art asso com edu gov net org pol ',
      'ec': ' com edu fin gov info med mil net org pro ',
      'eg': ' com edu eun gov mil name net org sci ',
      'er': ' com edu gov ind mil net org rochest w ',
      'es': ' com edu gob nom org ',
      'et': ' biz com edu gov info name net org ',
      'fj': ' ac biz com info mil name net org pro ',
      'fk': ' ac co gov net nom org ',
      'fr': ' asso com f gouv nom prd presse tm ',
      'gg': ' co net org ',
      'gh': ' com edu gov mil org ',
      'gn': ' ac com gov net org ',
      'gr': ' com edu gov mil net org ',
      'gt': ' com edu gob ind mil net org ',
      'gu': ' com edu gov net org ',
      'hk': ' com edu gov idv net org ',
      'hu': ' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ',
      'id': ' ac co go mil net or sch web ',
      'il': ' ac co gov idf k12 muni net org ',
      'in': ' ac co edu ernet firm gen gov i ind mil net nic org res ',
      'iq': ' com edu gov i mil net org ',
      'ir': ' ac co dnssec gov i id net org sch ',
      'it': ' edu gov ',
      'je': ' co net org ',
      'jo': ' com edu gov mil name net org sch ',
      'jp': ' ac ad co ed go gr lg ne or ',
      'ke': ' ac co go info me mobi ne or sc ',
      'kh': ' com edu gov mil net org per ',
      'ki': ' biz com de edu gov info mob net org tel ',
      'km': ' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ',
      'kn': ' edu gov net org ',
      'kr': ' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ',
      'kw': ' com edu gov net org ',
      'ky': ' com edu gov net org ',
      'kz': ' com edu gov mil net org ',
      'lb': ' com edu gov net org ',
      'lk': ' assn com edu gov grp hotel int ltd net ngo org sch soc web ',
      'lr': ' com edu gov net org ',
      'lv': ' asn com conf edu gov id mil net org ',
      'ly': ' com edu gov id med net org plc sch ',
      'ma': ' ac co gov m net org press ',
      'mc': ' asso tm ',
      'me': ' ac co edu gov its net org priv ',
      'mg': ' com edu gov mil nom org prd tm ',
      'mk': ' com edu gov inf name net org pro ',
      'ml': ' com edu gov net org presse ',
      'mn': ' edu gov org ',
      'mo': ' com edu gov net org ',
      'mt': ' com edu gov net org ',
      'mv': ' aero biz com coop edu gov info int mil museum name net org pro ',
      'mw': ' ac co com coop edu gov int museum net org ',
      'mx': ' com edu gob net org ',
      'my': ' com edu gov mil name net org sch ',
      'nf': ' arts com firm info net other per rec store web ',
      'ng': ' biz com edu gov mil mobi name net org sch ',
      'ni': ' ac co com edu gob mil net nom org ',
      'np': ' com edu gov mil net org ',
      'nr': ' biz com edu gov info net org ',
      'om': ' ac biz co com edu gov med mil museum net org pro sch ',
      'pe': ' com edu gob mil net nom org sld ',
      'ph': ' com edu gov i mil net ngo org ',
      'pk': ' biz com edu fam gob gok gon gop gos gov net org web ',
      'pl': ' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ',
      'pr': ' ac biz com edu est gov info isla name net org pro prof ',
      'ps': ' com edu gov net org plo sec ',
      'pw': ' belau co ed go ne or ',
      'ro': ' arts com firm info nom nt org rec store tm www ',
      'rs': ' ac co edu gov in org ',
      'sb': ' com edu gov net org ',
      'sc': ' com edu gov net org ',
      'sh': ' co com edu gov net nom org ',
      'sl': ' com edu gov net org ',
      'st': ' co com consulado edu embaixada gov mil net org principe saotome store ',
      'sv': ' com edu gob org red ',
      'sz': ' ac co org ',
      'tr': ' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ',
      'tt': ' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ',
      'tw': ' club com ebiz edu game gov idv mil net org ',
      'mu': ' ac co com gov net or org ',
      'mz': ' ac co edu gov org ',
      'na': ' co com ',
      'nz': ' ac co cri geek gen govt health iwi maori mil net org parliament school ',
      'pa': ' abo ac com edu gob ing med net nom org sld ',
      'pt': ' com edu gov int net nome org publ ',
      'py': ' com edu gov mil net org ',
      'qa': ' com edu gov mil net org ',
      're': ' asso com nom ',
      'ru': ' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ',
      'rw': ' ac co com edu gouv gov int mil net ',
      'sa': ' com edu gov med net org pub sch ',
      'sd': ' com edu gov info med net org tv ',
      'se': ' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ',
      'sg': ' com edu gov idn net org per ',
      'sn': ' art com edu gouv org perso univ ',
      'sy': ' com edu gov mil net news org ',
      'th': ' ac co go in mi net or ',
      'tj': ' ac biz co com edu go gov info int mil name net nic org test web ',
      'tn': ' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ',
      'tz': ' ac co go ne or ',
      'ua': ' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ',
      'ug': ' ac co go ne or org sc ',
      'uk': ' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ',
      'us': ' dni fed isa kids nsn ',
      'uy': ' com edu gub mil net org ',
      've': ' co com edu gob info mil net org web ',
      'vi': ' co com k12 net org ',
      'vn': ' ac biz com edu gov health info int name net org pro ',
      'ye': ' co com gov ltd me net org plc ',
      'yu': ' ac co edu gov org ',
      'za': ' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ',
      'zm': ' ac co com edu gov net org sch ',
      // https://en.wikipedia.org/wiki/CentralNic#Second-level_domains
      'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ',
      'net': 'gb jp se uk ',
      'org': 'ae',
      'de': 'com '
    },
    // gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost
    // in both performance and memory footprint. No initialization required.
    // http://jsperf.com/uri-js-sld-regex-vs-binary-search/4
    // Following methods use lastIndexOf() rather than array.split() in order
    // to avoid any memory allocations.
    has: function (domain) {
      var tldOffset = domain.lastIndexOf('.');

      if (tldOffset <= 0 || tldOffset >= domain.length - 1) {
        return false;
      }

      var sldOffset = domain.lastIndexOf('.', tldOffset - 1);

      if (sldOffset <= 0 || sldOffset >= tldOffset - 1) {
        return false;
      }

      var sldList = SLD.list[domain.slice(tldOffset + 1)];

      if (!sldList) {
        return false;
      }

      return sldList.indexOf(' ' + domain.slice(sldOffset + 1, tldOffset) + ' ') >= 0;
    },
    is: function (domain) {
      var tldOffset = domain.lastIndexOf('.');

      if (tldOffset <= 0 || tldOffset >= domain.length - 1) {
        return false;
      }

      var sldOffset = domain.lastIndexOf('.', tldOffset - 1);

      if (sldOffset >= 0) {
        return false;
      }

      var sldList = SLD.list[domain.slice(tldOffset + 1)];

      if (!sldList) {
        return false;
      }

      return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0;
    },
    get: function (domain) {
      var tldOffset = domain.lastIndexOf('.');

      if (tldOffset <= 0 || tldOffset >= domain.length - 1) {
        return null;
      }

      var sldOffset = domain.lastIndexOf('.', tldOffset - 1);

      if (sldOffset <= 0 || sldOffset >= tldOffset - 1) {
        return null;
      }

      var sldList = SLD.list[domain.slice(tldOffset + 1)];

      if (!sldList) {
        return null;
      }

      if (sldList.indexOf(' ' + domain.slice(sldOffset + 1, tldOffset) + ' ') < 0) {
        return null;
      }

      return domain.slice(sldOffset + 1);
    },
    noConflict: function () {
      if (root.SecondLevelDomains === this) {
        root.SecondLevelDomains = _SecondLevelDomains;
      }

      return this;
    }
  };
  return SLD;
});

/***/ }),
/* 156 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/**
 * This method returns `false`.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {boolean} Returns `false`.
 * @example
 *
 * _.times(2, _.stubFalse);
 * // => [false, false]
 */
function stubFalse() {
  return false;
}

/* harmony default export */ __webpack_exports__["a"] = (stubFalse);

/***/ }),
/* 157 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(module) {/* harmony import */ var _root_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4);

/** Detect free variable `exports`. */

var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */

var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */

var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */

var Buffer = moduleExports ? _root_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Buffer : undefined,
    allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
/**
 * Creates a clone of  `buffer`.
 *
 * @private
 * @param {Buffer} buffer The buffer to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Buffer} Returns the cloned buffer.
 */

function cloneBuffer(buffer, isDeep) {
  if (isDeep) {
    return buffer.slice();
  }

  var length = buffer.length,
      result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
  buffer.copy(result);
  return result;
}

/* harmony default export */ __webpack_exports__["a"] = (cloneBuffer);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(66)(module)))

/***/ }),
/* 158 */
/***/ (function(module, exports, __webpack_require__) {

!function (e, t) {
   true ? module.exports = t() : undefined;
}(this, function () {
  "use strict";

  return function (e, t, r) {
    var n = t.prototype,
        o = n.format;
    r.en.ordinal = function (e) {
      var t = ["th", "st", "nd", "rd"],
          r = e % 100;
      return "[" + e + (t[(r - 20) % 10] || t[r] || t[0]) + "]";
    }, n.format = function (e) {
      var t = this,
          r = this.$locale(),
          n = this.$utils(),
          a = (e || "YYYY-MM-DDTHH:mm:ssZ").replace(/\[([^\]]+)]|Q|wo|ww|w|gggg|Do|X|x|k{1,2}|S/g, function (e) {
        switch (e) {
          case "Q":
            return Math.ceil((t.$M + 1) / 3);

          case "Do":
            return r.ordinal(t.$D);

          case "gggg":
            return t.weekYear();

          case "wo":
            return r.ordinal(t.week(), "W");

          case "w":
          case "ww":
            return n.s(t.week(), "w" === e ? 1 : 2, "0");

          case "k":
          case "kk":
            return n.s(String(0 === t.$H ? 24 : t.$H), "k" === e ? 1 : 2, "0");

          case "X":
            return Math.floor(t.$d.getTime() / 1e3);

          case "x":
            return t.$d.getTime();

          default:
            return e;
        }
      });
      return o.bind(this)(a);
    };
  };
});

/***/ }),
/* 159 */
/***/ (function(module, exports, __webpack_require__) {

var baseSlice = __webpack_require__(328),
    toInteger = __webpack_require__(67);
/**
 * Creates a slice of `array` with `n` elements dropped from the beginning.
 *
 * @static
 * @memberOf _
 * @since 0.5.0
 * @category Array
 * @param {Array} array The array to query.
 * @param {number} [n=1] The number of elements to drop.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
 * @returns {Array} Returns the slice of `array`.
 * @example
 *
 * _.drop([1, 2, 3]);
 * // => [2, 3]
 *
 * _.drop([1, 2, 3], 2);
 * // => [3]
 *
 * _.drop([1, 2, 3], 5);
 * // => []
 *
 * _.drop([1, 2, 3], 0);
 * // => [1, 2, 3]
 */


function drop(array, n, guard) {
  var length = array == null ? 0 : array.length;

  if (!length) {
    return [];
  }

  n = guard || n === undefined ? 1 : toInteger(n);
  return baseSlice(array, n < 0 ? 0 : n, length);
}

module.exports = drop;

/***/ }),
/* 160 */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(20),
    isObjectLike = __webpack_require__(19);
/** `Object#toString` result references. */


var boolTag = '[object Boolean]';
/**
 * Checks if `value` is classified as a boolean primitive or object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
 * @example
 *
 * _.isBoolean(false);
 * // => true
 *
 * _.isBoolean(null);
 * // => false
 */

function isBoolean(value) {
  return value === true || value === false || isObjectLike(value) && baseGetTag(value) == boolTag;
}

module.exports = isBoolean;

/***/ }),
/* 161 */
/***/ (function(module, exports) {

/**
 * Checks if `value` is `null` or `undefined`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is nullish, else `false`.
 * @example
 *
 * _.isNil(null);
 * // => true
 *
 * _.isNil(void 0);
 * // => true
 *
 * _.isNil(NaN);
 * // => false
 */
function isNil(value) {
  return value == null;
}

module.exports = isNil;

/***/ }),
/* 162 */
/***/ (function(module, exports, __webpack_require__) {

var arrayMap = __webpack_require__(70),
    baseIteratee = __webpack_require__(383),
    basePickBy = __webpack_require__(436),
    getAllKeysIn = __webpack_require__(438);
/**
 * Creates an object composed of the `object` properties `predicate` returns
 * truthy for. The predicate is invoked with two arguments: (value, key).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Object
 * @param {Object} object The source object.
 * @param {Function} [predicate=_.identity] The function invoked per property.
 * @returns {Object} Returns the new object.
 * @example
 *
 * var object = { 'a': 1, 'b': '2', 'c': 3 };
 *
 * _.pickBy(object, _.isNumber);
 * // => { 'a': 1, 'c': 3 }
 */


function pickBy(object, predicate) {
  if (object == null) {
    return {};
  }

  var props = arrayMap(getAllKeysIn(object), function (prop) {
    return [prop];
  });
  predicate = baseIteratee(predicate);
  return basePickBy(object, props, function (value, path) {
    return predicate(value, path[0]);
  });
}

module.exports = pickBy;

/***/ }),
/* 163 */
/***/ (function(module, exports, __webpack_require__) {

var baseKeys = __webpack_require__(100),
    getTag = __webpack_require__(132),
    isArrayLike = __webpack_require__(25),
    isString = __webpack_require__(112),
    stringSize = __webpack_require__(441);
/** `Object#toString` result references. */


var mapTag = '[object Map]',
    setTag = '[object Set]';
/**
 * Gets the size of `collection` by returning its length for array-like
 * values or the number of own enumerable string keyed properties for objects.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object|string} collection The collection to inspect.
 * @returns {number} Returns the collection size.
 * @example
 *
 * _.size([1, 2, 3]);
 * // => 3
 *
 * _.size({ 'a': 1, 'b': 2 });
 * // => 2
 *
 * _.size('pebbles');
 * // => 7
 */

function size(collection) {
  if (collection == null) {
    return 0;
  }

  if (isArrayLike(collection)) {
    return isString(collection) ? stringSize(collection) : collection.length;
  }

  var tag = getTag(collection);

  if (tag == mapTag || tag == setTag) {
    return collection.size;
  }

  return baseKeys(collection).length;
}

module.exports = size;

/***/ }),
/* 164 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _driver = __webpack_require__(137);

var _driver2 = _interopRequireDefault(_driver);

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {
    default: obj
  };
}

exports.default = (0, _driver2.default)('webExtensionSyncStorage', 'sync');

/***/ }),
/* 165 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _driver = __webpack_require__(137);

var _driver2 = _interopRequireDefault(_driver);

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {
    default: obj
  };
}

exports.default = (0, _driver2.default)('webExtensionLocalStorage', 'local');

/***/ }),
/* 166 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
__p += '<!-- src/templates/form_captcha.html -->\n';
 if (o.label) { ;
__p += '\n<label>\n    ' +
__e(o.label) +
'\n</label>\n';
 } ;
__p += '\n<img src="data:' +
__e(o.type) +
';base64,' +
__e(o.data) +
'">\n<input name="' +
__e(o.name) +
'" type="text" ';
 if (o.required) { ;
__p += ' required="required" ';
 } ;
__p += ' />\n\n\n';
return __p
};

/***/ }),
/* 167 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
__p += '<!-- src/templates/form_checkbox.html -->\n<div class="form-group">\n    <input id="' +
__e(o.id) +
'" name="' +
__e(o.name) +
'" type="checkbox" ' +
__e(o.checked) +
' ';
 if (o.required) { ;
__p += ' required ';
 } ;
__p += ' />\n    <label class="form-check-label" for="' +
__e(o.id) +
'">' +
__e(o.label) +
'</label>\n</div>\n';
return __p
};

/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
__p += '<!-- src/templates/form_select.html -->\n<div class="form-group">\n    <label for="' +
__e(o.id) +
'">' +
__e(o.label) +
'</label>\n    <select class="form-control" id="' +
__e(o.id) +
'" name="' +
__e(o.name) +
'" ';
 if (o.multiple) { ;
__p += ' multiple="multiple" ';
 } ;
__p += '>' +
((__t = (o.options)) == null ? '' : __t) +
'</select>\n</div>\n';
return __p
};

/***/ }),
/* 169 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape;
__p += '<!-- src/templates/form_textarea.html -->\n<label class="label-ta">' +
__e(o.label) +
'</label>\n<textarea name="' +
__e(o.name) +
'">' +
__e(o.value) +
'</textarea>\n';
return __p
};

/***/ }),
/* 170 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape;
__p += '<!-- src/templates/form_url.html -->\n<label>\n    ' +
__e(o.label) +
'\n    <a class="form-url" target="_blank" rel="noopener" href="' +
__e(o.value) +
'">' +
__e(o.value) +
'</a>\n</label>\n';
return __p
};

/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
__p += '<!-- src/templates/select_option.html -->\n<option value="' +
__e(o.value) +
'" ';
 if (o.selected) { ;
__p += ' selected="selected" ';
 } ;
__p += ' >' +
__e(o.label) +
'</option>\n';
return __p
};

/***/ }),
/* 172 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape;
__p += '<!-- src/templates/controlbox_toggle.html -->\n<span class="toggle-feedback">' +
__e(o.label_toggle) +
'</span>\n';
return __p
};

/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '';
__p += '<!-- src/templates/dragresize.html -->\n<div class="dragresize dragresize-top"></div>\n<div class="dragresize dragresize-topleft"></div>\n<div class="dragresize dragresize-left"></div>\n';
return __p
};

/***/ }),
/* 174 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
__p += '<!-- src/templates/room_description.html -->\n<!-- FIXME: check markup in mockup -->\n<div class="room-info">\n<p class="room-info"><strong>' +
__e(o.label_jid) +
'</strong> ' +
__e(o.jid) +
'</p>\n<p class="room-info"><strong>' +
__e(o.label_desc) +
'</strong> ' +
__e(o.desc) +
'</p>\n<p class="room-info"><strong>' +
__e(o.label_occ) +
'</strong> ' +
__e(o.occ) +
'</p>\n<p class="room-info"><strong>' +
__e(o.label_features) +
'</strong>\n    <ul>\n        ';
 if (o.passwordprotected) { ;
__p += '\n        <li class="room-info locked">' +
__e(o.label_requires_auth) +
'</li>\n        ';
 } ;
__p += '\n        ';
 if (o.hidden) { ;
__p += '\n        <li class="room-info">' +
__e(o.label_hidden) +
'</li>\n        ';
 } ;
__p += '\n        ';
 if (o.membersonly) { ;
__p += '\n        <li class="room-info">' +
__e(o.label_requires_invite) +
'</li>\n        ';
 } ;
__p += '\n        ';
 if (o.moderated) { ;
__p += '\n        <li class="room-info">' +
__e(o.label_moderated) +
'</li>\n        ';
 } ;
__p += '\n        ';
 if (o.nonanonymous) { ;
__p += '\n        <li class="room-info">' +
__e(o.label_non_anon) +
'</li>\n        ';
 } ;
__p += '\n        ';
 if (o.open) { ;
__p += '\n        <li class="room-info">' +
__e(o.label_open_room) +
'</li>\n        ';
 } ;
__p += '\n        ';
 if (o.persistent) { ;
__p += '\n        <li class="room-info">' +
__e(o.label_permanent_room) +
'</li>\n        ';
 } ;
__p += '\n        ';
 if (o.publicroom) { ;
__p += '\n        <li class="room-info">' +
__e(o.label_public) +
'</li>\n        ';
 } ;
__p += '\n        ';
 if (o.semianonymous) { ;
__p += '\n        <li class="room-info">' +
__e(o.label_semi_anon) +
'</li>\n        ';
 } ;
__p += '\n        ';
 if (o.temporary) { ;
__p += '\n        <li class="room-info">' +
__e(o.label_temp_room) +
'</li>\n        ';
 } ;
__p += '\n        ';
 if (o.unmoderated) { ;
__p += '\n        <li class="room-info">' +
__e(o.label_unmoderated) +
'</li>\n        ';
 } ;
__p += '\n    </ul>\n</p>\n</div>\n';
return __p
};

/***/ }),
/* 175 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
 * @license MIT or GPL-2.0
 * @fileOverview Favico animations
 * @author Miroslav Magda, http://blog.ejci.net
 * @source: https://github.com/ejci/favico.js
 * @version 0.3.10
 */

/**
 * Create new favico instance
 * @param {Object} Options
 * @return {Object} Favico object
 * @example
 * var favico = new Favico({
 *    bgColor : '#d00',
 *    textColor : '#fff',
 *    fontFamily : 'sans-serif',
 *    fontStyle : 'bold',
 *    type : 'circle',
 *    position : 'down',
 *    animation : 'slide',
 *    elementId: false,
 *    element: null,
 *    dataUrl: function(url){},
 *    win: window
 * });
 */
(function () {
  var Favico = function (opt) {
    'use strict';

    opt = opt ? opt : {};
    var _def = {
      bgColor: '#d00',
      textColor: '#fff',
      fontFamily: 'sans-serif',
      //Arial,Verdana,Times New Roman,serif,sans-serif,...
      fontStyle: 'bold',
      //normal,italic,oblique,bold,bolder,lighter,100,200,300,400,500,600,700,800,900
      type: 'circle',
      position: 'down',
      // down, up, left, leftup (upleft)
      animation: 'slide',
      elementId: false,
      element: null,
      dataUrl: false,
      win: window
    };

    var _opt, _orig, _h, _w, _canvas, _context, _img, _ready, _lastBadge, _running, _readyCb, _stop, _browser, _animTimeout, _drawTimeout, _doc;

    _browser = {};
    _browser.ff = typeof InstallTrigger != 'undefined';
    _browser.chrome = !!window.chrome;
    _browser.opera = !!window.opera || navigator.userAgent.indexOf('Opera') >= 0;
    _browser.ie =
    /*@cc_on!@*/
    false;
    _browser.safari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
    _browser.supported = _browser.chrome || _browser.ff || _browser.opera;
    var _queue = [];

    _readyCb = function () {};

    _ready = _stop = false;
    /**
     * Initialize favico
     */

    var init = function () {
      //merge initial options
      _opt = merge(_def, opt);
      _opt.bgColor = hexToRgb(_opt.bgColor);
      _opt.textColor = hexToRgb(_opt.textColor);
      _opt.position = _opt.position.toLowerCase();
      _opt.animation = animation.types['' + _opt.animation] ? _opt.animation : _def.animation;
      _doc = _opt.win.document;
      var isUp = _opt.position.indexOf('up') > -1;
      var isLeft = _opt.position.indexOf('left') > -1; //transform the animations

      if (isUp || isLeft) {
        for (var a in animation.types) {
          for (var i = 0; i < animation.types[a].length; i++) {
            var step = animation.types[a][i];

            if (isUp) {
              if (step.y < 0.6) {
                step.y = step.y - 0.4;
              } else {
                step.y = step.y - 2 * step.y + (1 - step.w);
              }
            }

            if (isLeft) {
              if (step.x < 0.6) {
                step.x = step.x - 0.4;
              } else {
                step.x = step.x - 2 * step.x + (1 - step.h);
              }
            }

            animation.types[a][i] = step;
          }
        }
      }

      _opt.type = type['' + _opt.type] ? _opt.type : _def.type;
      _orig = link.getIcons(); //create temp canvas

      _canvas = document.createElement('canvas'); //create temp image

      _img = document.createElement('img');
      var lastIcon = _orig[_orig.length - 1];

      if (lastIcon.hasAttribute('href')) {
        _img.setAttribute('crossOrigin', 'anonymous'); //get width/height


        _img.onload = function () {
          _h = _img.height > 0 ? _img.height : 32;
          _w = _img.width > 0 ? _img.width : 32;
          _canvas.height = _h;
          _canvas.width = _w;
          _context = _canvas.getContext('2d');
          icon.ready();
        };

        _img.setAttribute('src', lastIcon.getAttribute('href'));
      } else {
        _h = 32;
        _w = 32;
        _img.height = _h;
        _img.width = _w;
        _canvas.height = _h;
        _canvas.width = _w;
        _context = _canvas.getContext('2d');
        icon.ready();
      }
    };
    /**
     * Icon namespace
     */


    var icon = {};
    /**
     * Icon is ready (reset icon) and start animation (if ther is any)
     */

    icon.ready = function () {
      _ready = true;
      icon.reset();

      _readyCb();
    };
    /**
     * Reset icon to default state
     */


    icon.reset = function () {
      //reset
      if (!_ready) {
        return;
      }

      _queue = [];
      _lastBadge = false;
      _running = false;

      _context.clearRect(0, 0, _w, _h);

      _context.drawImage(_img, 0, 0, _w, _h); //_stop=true;


      link.setIcon(_canvas); //webcam('stop');
      //video('stop');

      window.clearTimeout(_animTimeout);
      window.clearTimeout(_drawTimeout);
    };
    /**
     * Start animation
     */


    icon.start = function () {
      if (!_ready || _running) {
        return;
      }

      var finished = function () {
        _lastBadge = _queue[0];
        _running = false;

        if (_queue.length > 0) {
          _queue.shift();

          icon.start();
        } else {}
      };

      if (_queue.length > 0) {
        _running = true;

        var run = function () {
          // apply options for this animation
          ['type', 'animation', 'bgColor', 'textColor', 'fontFamily', 'fontStyle'].forEach(function (a) {
            if (a in _queue[0].options) {
              _opt[a] = _queue[0].options[a];
            }
          });
          animation.run(_queue[0].options, function () {
            finished();
          }, false);
        };

        if (_lastBadge) {
          animation.run(_lastBadge.options, function () {
            run();
          }, true);
        } else {
          run();
        }
      }
    };
    /**
     * Badge types
     */


    var type = {};

    var options = function (opt) {
      opt.n = typeof opt.n === 'number' ? Math.abs(opt.n | 0) : opt.n;
      opt.x = _w * opt.x;
      opt.y = _h * opt.y;
      opt.w = _w * opt.w;
      opt.h = _h * opt.h;
      opt.len = ("" + opt.n).length;
      return opt;
    };
    /**
     * Generate circle
     * @param {Object} opt Badge options
     */


    type.circle = function (opt) {
      opt = options(opt);
      var more = false;

      if (opt.len === 2) {
        opt.x = opt.x - opt.w * 0.4;
        opt.w = opt.w * 1.4;
        more = true;
      } else if (opt.len >= 3) {
        opt.x = opt.x - opt.w * 0.65;
        opt.w = opt.w * 1.65;
        more = true;
      }

      _context.clearRect(0, 0, _w, _h);

      _context.drawImage(_img, 0, 0, _w, _h);

      _context.beginPath();

      _context.font = _opt.fontStyle + " " + Math.floor(opt.h * (opt.n > 99 ? 0.85 : 1)) + "px " + _opt.fontFamily;
      _context.textAlign = 'center';

      if (more) {
        _context.moveTo(opt.x + opt.w / 2, opt.y);

        _context.lineTo(opt.x + opt.w - opt.h / 2, opt.y);

        _context.quadraticCurveTo(opt.x + opt.w, opt.y, opt.x + opt.w, opt.y + opt.h / 2);

        _context.lineTo(opt.x + opt.w, opt.y + opt.h - opt.h / 2);

        _context.quadraticCurveTo(opt.x + opt.w, opt.y + opt.h, opt.x + opt.w - opt.h / 2, opt.y + opt.h);

        _context.lineTo(opt.x + opt.h / 2, opt.y + opt.h);

        _context.quadraticCurveTo(opt.x, opt.y + opt.h, opt.x, opt.y + opt.h - opt.h / 2);

        _context.lineTo(opt.x, opt.y + opt.h / 2);

        _context.quadraticCurveTo(opt.x, opt.y, opt.x + opt.h / 2, opt.y);
      } else {
        _context.arc(opt.x + opt.w / 2, opt.y + opt.h / 2, opt.h / 2, 0, 2 * Math.PI);
      }

      _context.fillStyle = 'rgba(' + _opt.bgColor.r + ',' + _opt.bgColor.g + ',' + _opt.bgColor.b + ',' + opt.o + ')';

      _context.fill();

      _context.closePath();

      _context.beginPath();

      _context.stroke();

      _context.fillStyle = 'rgba(' + _opt.textColor.r + ',' + _opt.textColor.g + ',' + _opt.textColor.b + ',' + opt.o + ')'; //_context.fillText((more) ? '9+' : opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));

      if (typeof opt.n === 'number' && opt.n > 999) {
        _context.fillText((opt.n > 9999 ? 9 : Math.floor(opt.n / 1000)) + 'k+', Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.2));
      } else {
        _context.fillText(opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));
      }

      _context.closePath();
    };
    /**
     * Generate rectangle
     * @param {Object} opt Badge options
     */


    type.rectangle = function (opt) {
      opt = options(opt);
      var more = false;

      if (opt.len === 2) {
        opt.x = opt.x - opt.w * 0.4;
        opt.w = opt.w * 1.4;
        more = true;
      } else if (opt.len >= 3) {
        opt.x = opt.x - opt.w * 0.65;
        opt.w = opt.w * 1.65;
        more = true;
      }

      _context.clearRect(0, 0, _w, _h);

      _context.drawImage(_img, 0, 0, _w, _h);

      _context.beginPath();

      _context.font = _opt.fontStyle + " " + Math.floor(opt.h * (opt.n > 99 ? 0.9 : 1)) + "px " + _opt.fontFamily;
      _context.textAlign = 'center';
      _context.fillStyle = 'rgba(' + _opt.bgColor.r + ',' + _opt.bgColor.g + ',' + _opt.bgColor.b + ',' + opt.o + ')';

      _context.fillRect(opt.x, opt.y, opt.w, opt.h);

      _context.fillStyle = 'rgba(' + _opt.textColor.r + ',' + _opt.textColor.g + ',' + _opt.textColor.b + ',' + opt.o + ')'; //_context.fillText((more) ? '9+' : opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));

      if (typeof opt.n === 'number' && opt.n > 999) {
        _context.fillText((opt.n > 9999 ? 9 : Math.floor(opt.n / 1000)) + 'k+', Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.2));
      } else {
        _context.fillText(opt.n, Math.floor(opt.x + opt.w / 2), Math.floor(opt.y + opt.h - opt.h * 0.15));
      }

      _context.closePath();
    };
    /**
     * Set badge
     */


    var badge = function (number, opts) {
      opts = (typeof opts === 'string' ? {
        animation: opts
      } : opts) || {};

      _readyCb = function () {
        try {
          if (typeof number === 'number' ? number > 0 : number !== '') {
            var q = {
              type: 'badge',
              options: {
                n: number
              }
            };

            if ('animation' in opts && animation.types['' + opts.animation]) {
              q.options.animation = '' + opts.animation;
            }

            if ('type' in opts && type['' + opts.type]) {
              q.options.type = '' + opts.type;
            }

            ['bgColor', 'textColor'].forEach(function (o) {
              if (o in opts) {
                q.options[o] = hexToRgb(opts[o]);
              }
            });
            ['fontStyle', 'fontFamily'].forEach(function (o) {
              if (o in opts) {
                q.options[o] = opts[o];
              }
            });

            _queue.push(q);

            if (_queue.length > 100) {
              throw new Error('Too many badges requests in queue.');
            }

            icon.start();
          } else {
            icon.reset();
          }
        } catch (e) {
          throw new Error('Error setting badge. Message: ' + e.message);
        }
      };

      if (_ready) {
        _readyCb();
      }
    };

    var setOpt = function (key, value) {
      var opts = key;

      if (!(value == null && Object.prototype.toString.call(key) == '[object Object]')) {
        opts = {};
        opts[key] = value;
      }

      var keys = Object.keys(opts);

      for (var i = 0; i < keys.length; i++) {
        if (keys[i] == 'bgColor' || keys[i] == 'textColor') {
          _opt[keys[i]] = hexToRgb(opts[keys[i]]);
        } else {
          _opt[keys[i]] = opts[keys[i]];
        }
      }

      _queue.push(_lastBadge);

      icon.start();
    };

    var link = {};
    /**
     * Get icons from HEAD tag or create a new <link> element
     */

    link.getIcons = function () {
      var elms = []; //get link element

      var getLinks = function () {
        var icons = [];

        var links = _doc.getElementsByTagName('head')[0].getElementsByTagName('link');

        for (var i = 0; i < links.length; i++) {
          if (/(^|\s)icon(\s|$)/i.test(links[i].getAttribute('rel'))) {
            icons.push(links[i]);
          }
        }

        return icons;
      };

      if (_opt.element) {
        elms = [_opt.element];
      } else if (_opt.elementId) {
        //if img element identified by elementId
        elms = [_doc.getElementById(_opt.elementId)];
        elms[0].setAttribute('href', elms[0].getAttribute('src'));
      } else {
        //if link element
        elms = getLinks();

        if (elms.length === 0) {
          elms = [_doc.createElement('link')];
          elms[0].setAttribute('rel', 'icon');

          _doc.getElementsByTagName('head')[0].appendChild(elms[0]);
        }
      }

      elms.forEach(function (item) {
        item.setAttribute('type', 'image/png');
      });
      return elms;
    };

    link.setIcon = function (canvas) {
      var url = canvas.toDataURL('image/png');
      link.setIconSrc(url);
    };

    link.setIconSrc = function (url) {
      if (_opt.dataUrl) {
        //if using custom exporter
        _opt.dataUrl(url);
      }

      if (_opt.element) {
        _opt.element.setAttribute('href', url);

        _opt.element.setAttribute('src', url);
      } else if (_opt.elementId) {
        //if is attached to element (image)
        var elm = _doc.getElementById(_opt.elementId);

        elm.setAttribute('href', url);
        elm.setAttribute('src', url);
      } else {
        //if is attached to fav icon
        if (_browser.ff || _browser.opera) {
          //for FF we need to "recreate" element, atach to dom and remove old <link>
          //var originalType = _orig.getAttribute('rel');
          var old = _orig[_orig.length - 1];

          var newIcon = _doc.createElement('link');

          _orig = [newIcon]; //_orig.setAttribute('rel', originalType);

          if (_browser.opera) {
            newIcon.setAttribute('rel', 'icon');
          }

          newIcon.setAttribute('rel', 'icon');
          newIcon.setAttribute('type', 'image/png');

          _doc.getElementsByTagName('head')[0].appendChild(newIcon);

          newIcon.setAttribute('href', url);

          if (old.parentNode) {
            old.parentNode.removeChild(old);
          }
        } else {
          _orig.forEach(function (icon) {
            icon.setAttribute('href', url);
          });
        }
      }
    }; //http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb#answer-5624139
    //HEX to RGB convertor


    function hexToRgb(hex) {
      var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
      hex = hex.replace(shorthandRegex, function (m, r, g, b) {
        return r + r + g + g + b + b;
      });
      var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
      return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      } : false;
    }
    /**
     * Merge options
     */


    function merge(def, opt) {
      var mergedOpt = {};
      var attrname;

      for (attrname in def) {
        mergedOpt[attrname] = def[attrname];
      }

      for (attrname in opt) {
        mergedOpt[attrname] = opt[attrname];
      }

      return mergedOpt;
    }
    /**
     * Cross-browser page visibility shim
     * http://stackoverflow.com/questions/12536562/detect-whether-a-window-is-visible
     */


    function isPageHidden() {
      return _doc.hidden || _doc.msHidden || _doc.webkitHidden || _doc.mozHidden;
    }
    /**
     * @namespace animation
     */


    var animation = {};
    /**
     * Animation "frame" duration
     */

    animation.duration = 40;
    /**
     * Animation types (none,fade,pop,slide)
     */

    animation.types = {};
    animation.types.fade = [{
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.0
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.1
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.2
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.3
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.4
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.5
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.6
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.7
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.8
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 0.9
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 1.0
    }];
    animation.types.none = [{
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 1
    }];
    animation.types.pop = [{
      x: 1,
      y: 1,
      w: 0,
      h: 0,
      o: 1
    }, {
      x: 0.9,
      y: 0.9,
      w: 0.1,
      h: 0.1,
      o: 1
    }, {
      x: 0.8,
      y: 0.8,
      w: 0.2,
      h: 0.2,
      o: 1
    }, {
      x: 0.7,
      y: 0.7,
      w: 0.3,
      h: 0.3,
      o: 1
    }, {
      x: 0.6,
      y: 0.6,
      w: 0.4,
      h: 0.4,
      o: 1
    }, {
      x: 0.5,
      y: 0.5,
      w: 0.5,
      h: 0.5,
      o: 1
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 1
    }];
    animation.types.popFade = [{
      x: 0.75,
      y: 0.75,
      w: 0,
      h: 0,
      o: 0
    }, {
      x: 0.65,
      y: 0.65,
      w: 0.1,
      h: 0.1,
      o: 0.2
    }, {
      x: 0.6,
      y: 0.6,
      w: 0.2,
      h: 0.2,
      o: 0.4
    }, {
      x: 0.55,
      y: 0.55,
      w: 0.3,
      h: 0.3,
      o: 0.6
    }, {
      x: 0.50,
      y: 0.50,
      w: 0.4,
      h: 0.4,
      o: 0.8
    }, {
      x: 0.45,
      y: 0.45,
      w: 0.5,
      h: 0.5,
      o: 0.9
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 1
    }];
    animation.types.slide = [{
      x: 0.4,
      y: 1,
      w: 0.6,
      h: 0.6,
      o: 1
    }, {
      x: 0.4,
      y: 0.9,
      w: 0.6,
      h: 0.6,
      o: 1
    }, {
      x: 0.4,
      y: 0.9,
      w: 0.6,
      h: 0.6,
      o: 1
    }, {
      x: 0.4,
      y: 0.8,
      w: 0.6,
      h: 0.6,
      o: 1
    }, {
      x: 0.4,
      y: 0.7,
      w: 0.6,
      h: 0.6,
      o: 1
    }, {
      x: 0.4,
      y: 0.6,
      w: 0.6,
      h: 0.6,
      o: 1
    }, {
      x: 0.4,
      y: 0.5,
      w: 0.6,
      h: 0.6,
      o: 1
    }, {
      x: 0.4,
      y: 0.4,
      w: 0.6,
      h: 0.6,
      o: 1
    }];
    /**
     * Run animation
     * @param {Object} opt Animation options
     * @param {Object} cb Callabak after all steps are done
     * @param {Object} revert Reverse order? true|false
     * @param {Object} step Optional step number (frame bumber)
     */

    animation.run = function (opt, cb, revert, step) {
      var animationType = animation.types[isPageHidden() ? 'none' : _opt.animation];

      if (revert === true) {
        step = typeof step !== 'undefined' ? step : animationType.length - 1;
      } else {
        step = typeof step !== 'undefined' ? step : 0;
      }

      cb = cb ? cb : function () {};

      if (step < animationType.length && step >= 0) {
        type[_opt.type](merge(opt, animationType[step]));

        _animTimeout = setTimeout(function () {
          if (revert) {
            step = step - 1;
          } else {
            step = step + 1;
          }

          animation.run(opt, cb, revert, step);
        }, animation.duration);
        link.setIcon(_canvas);
      } else {
        cb();
        return;
      }
    }; //auto init


    init();
    return {
      badge: badge,
      setOpt: setOpt,
      reset: icon.reset,
      browser: {
        supported: _browser.supported
      }
    };
  }; // AMD / RequireJS


  if (true) {
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {
      return Favico;
    }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  } // CommonJS
  else {}
})();

/***/ }),
/* 176 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
__p += '<!-- src/templates/register_panel.html -->\n<div>\n    <form id="converse-register" class="converse-form">\n        <legend class="col-form-label">' +
__e(o.__("Create your account")) +
'</legend>\n\n        <div class="form-group">\n            <label>' +
__e(o.__("Please enter the XMPP provider to register with:")) +
'</label>\n            <div class="form-errors hidden"></div>\n\n            ';
 if (o.default_domain) { ;
__p += '\n                ' +
__e(o.default_domain) +
'\n            </div>\n            ';
 } else { ;
__p += '\n                <input class="form-control" required="required" type="text" name="domain" placeholder="' +
__e(o.domain_placeholder) +
'"/>\n                <p class="form-text text-muted">' +
__e(o.help_providers) +
' <a href="' +
__e(o.href_providers) +
'" class="url" target="_blank" rel="noopener">' +
__e(o.help_providers_link) +
'</a>.</p>\n            </div>\n            <fieldset class="buttons">\n                <input class="btn btn-primary" type="submit" value="' +
__e(o.label_register) +
'"/>\n                <div class="switch-form">\n                    <p>' +
__e( o.__("Already have a chat account?") ) +
'</p>\n                    <p><a class="login-here toggle-register-login" href="#converse/login">' +
__e(o.__("Log in here")) +
'</a></p>\n                </div>\n            </fieldset>\n            ';
 } ;
__p += '\n        <!--</div>-->\n    </form>\n</div>\n';
return __p
};

/***/ }),
/* 177 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
__p += '<!-- src/templates/registration_form.html -->\n<legend class="col-form-label">' +
__e(o.__("Account Registration:")) +
' ' +
__e(o.domain) +
'</legend>\n<p class="title">' +
__e(o.title) +
'</p>\n<p class="form-help instructions">' +
__e(o.instructions) +
'</p>\n<div class="form-errors hidden"></div>\n\n<fieldset class="buttons">\n    <input type="submit" class="btn btn-primary" value="' +
__e(o.__('Register')) +
'"/>\n    ';
 if (!o.registration_domain) { ;
__p += '\n        <input type="button" class="btn btn-secondary button-cancel" value="' +
__e(o.__('Choose a different provider')) +
'"/>\n    ';
 } ;
__p += '\n    <div class="switch-form">\n        <p>' +
__e( o.__("Already have a chat account?") ) +
'</p>\n        <p><a class="login-here toggle-register-login" href="#converse/login">' +
__e(o.__("Log in here")) +
'</a></p>\n    </div>\n</fieldset>\n';
return __p
};

/***/ }),
/* 178 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
__p += '<!-- src/templates/registration_request.html -->\n<span class="spinner login-submit fa fa-spinner"></span>\n<p class="info">' +
__e(o.__("Hold tight, we're fetching the registration form…")) +
'</p>\n';
 if (o.cancel) { ;
__p += '\n    <button class="btn btn-secondary button-cancel hor_centered">' +
__e(o.__('Cancel')) +
'</button>\n';
 } ;
__p += '\n';
return __p
};

/***/ }),
/* 179 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
__p += '<!-- src/templates/group_header.html -->\n<a href="#" class="list-toggle group-toggle controlbox-padded" title="' +
__e(o.desc_group_toggle) +
'">\n    <span class="fa ';
 if (o.toggle_state === o._converse.OPENED) { ;
__p += ' fa-caret-down ';
 } else { ;
__p += ' fa-caret-right ';
 } ;
__p += '">\n    </span> ' +
__e(o.label_group) +
'</a>\n<ul class="items-list roster-group-contacts ';
 if (o.toggle_state === o._converse.CLOSED) { ;
__p += ' collapsed ';
 } ;
__p += '"></ul>\n';
return __p
};

/***/ }),
/* 180 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
__p += '<!-- src/templates/pending_contact.html -->\n';
 if (o.allow_chat_pending_contacts)  { ;
__p += '\n<a class="list-item-link open-chat w-100" href="#">\n';
 } ;
__p += '\n<span class="pending-contact-name" title="JID: ' +
__e(o.jid) +
'">' +
__e(o.display_name) +
'</span> \n';
 if (o.allow_chat_pending_contacts)  { ;
__p += '</a>';
 } ;
__p += '\n<a class="list-item-action remove-xmpp-contact far fa-trash-alt" title="' +
__e(o.desc_remove) +
'" href="#"></a>\n';
return __p
};

/***/ }),
/* 181 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
__p += '<!-- src/templates/requesting_contact.html -->\n';
 if (o.allow_chat_pending_contacts)  { ;
__p += '\n<a class="open-chat w-100"href="#">\n';
 } ;
__p += '\n<span class="req-contact-name w-100" title="JID: ' +
__e(o.jid) +
'">' +
__e(o.display_name) +
'</span>\n';
 if (o.allow_chat_pending_contacts)  { ;
__p += '\n</a>\n';
 } ;
__p += '\n<a class="accept-xmpp-request list-item-action list-item-action--visible fa fa-check"\n   aria-label="' +
__e(o.desc_accept) +
'" title="' +
__e(o.desc_accept) +
'" href="#"></a>\n<a class="decline-xmpp-request list-item-action list-item-action--visible  fa fa-times"\n   aria-label="' +
__e(o.desc_decline) +
'" title="' +
__e(o.desc_decline) +
'" href="#"></a>\n';
return __p
};

/***/ }),
/* 182 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
__p += '<!-- src/templates/roster.html -->\n<div class="d-flex controlbox-padded">\n    <span class="w-100 controlbox-heading controlbox-heading--contacts">' +
__e(o.heading_contacts) +
'</span>\n    <a class="controlbox-heading__btn sync-contacts fa fa-sync" title="' +
__e(o.title_sync_contacts) +
'"></a>\n    ';
 if (o.allow_contact_requests) { ;
__p += '\n        <a class="controlbox-heading__btn add-contact fa fa-user-plus"\n           title="' +
__e(o.title_add_contact) +
'"\n           data-toggle="modal"\n           data-target="#add-contact-modal"></a>\n    ';
 } ;
__p += '\n</div>\n\n<form class="roster-filter-form"></form>\n\n<div class="list-container roster-contacts"></div>\n';
return __p
};

/***/ }),
/* 183 */
/***/ (function(module, exports, __webpack_require__) {

var _ = {escape:__webpack_require__(7)};
module.exports = function(o) {
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
__p += '<!-- src/templates/roster_item.html -->\n<a class="list-item-link cbox-list-item open-chat w-100 ';
 if (o.num_unread) { ;
__p += ' unread-msgs ';
 } ;
__p += '"\n   title="' +
__e(o.desc_chat) +
'" href="#">\n\n    <canvas class="avatar" height="30" width="30"></canvas>\n    <span class="' +
__e(o.status_icon) +
'" title="' +
__e(o.desc_status) +
'"></span>\n    ';
 if (o.num_unread) { ;
__p += ' <span class="msgs-indicator">' +
__e( o.num_unread ) +
'</span> ';
 } ;
__p += '\n    <span class="contact-name contact-name--' +
__e(o.show) +
' ';
 if (o.num_unread) { ;
__p += ' unread-msgs ';
 } ;
__p += '">' +
__e(o.display_name) +
'</span>\n</a>\n';
 if (o.allow_contact_removal) { ;
__p += '\n<a class="list-item-action remove-xmpp-contact far fa-trash-alt" title="' +
__e(o.desc_remove) +
'" href="#"></a>\n';
 } ;
__p += '\n';
return __p
};

/***/ }),
/* 184 */,
/* 185 */,
/* 186 */,
/* 187 */,
/* 188 */,
/* 189 */,
/* 190 */,
/* 191 */,
/* 192 */,
/* 193 */,
/* 194 */,
/* 195 */,
/* 196 */,
/* 197 */,
/* 198 */,
/* 199 */,
/* 200 */,
/* 201 */,
/* 202 */,
/* 203 */,
/* 204 */,
/* 205 */,
/* 206 */,
/* 207 */,
/* 208 */,
/* 209 */,
/* 210 */,
/* 211 */,
/* 212 */,
/* 213 */,
/* 214 */,
/* 215 */,
/* 216 */,
/* 217 */,
/* 218 */,
/* 219 */,
/* 220 */,
/* 221 */,
/* 222 */,
/* 223 */,
/* 224 */,
/* 225 */,
/* 226 */,
/* 227 */,
/* 228 */,
/* 229 */,
/* 230 */,
/* 231 */,
/* 232 */,
/* 233 */,
/* 234 */,
/* 235 */,
/* 236 */,
/* 237 */,
/* 238 */,
/* 239 */,
/* 240 */,
/* 241 */,
/* 242 */,
/* 243 */,
/* 244 */,
/* 245 */,
/* 246 */,
/* 247 */,
/* 248 */,
/* 249 */,
/* 250 */,
/* 251 */,
/* 252 */,
/* 253 */,
/* 254 */,
/* 255 */,
/* 256 */,
/* 257 */,
/* 258 */,
/* 259 */,
/* 260 */,
/* 261 */,
/* 262 */,
/* 263 */,
/* 264 */,
/* 265 */,
/* 266 */,
/* 267 */,
/* 268 */,
/* 269 */,
/* 270 */,
/* 271 */,
/* 272 */,
/* 273 */,
/* 274 */,
/* 275 */,
/* 276 */,
/* 277 */,
/* 278 */,
/* 279 */,
/* 280 */,
/* 281 */,
/* 282 */,
/* 283 */,
/* 284 */,
/* 285 */,
/* 286 */,
/* 287 */,
/* 288 */,
/* 289 */,
/* 290 */,
/* 291 */,
/* 292 */,
/* 293 */,
/* 294 */,
/* 295 */,
/* 296 */,
/* 297 */,
/* 298 */,
/* 299 */,
/* 300 */,
/* 301 */,
/* 302 */,
/* 303 */,
/* 304 */,
/* 305 */,
/* 306 */,
/* 307 */,
/* 308 */,
/* 309 */,
/* 310 */,
/* 311 */,
/* 312 */,
/* 313 */,
/* 314 */,
/* 315 */,
/* 316 */,
/* 317 */,
/* 318 */,
/* 319 */,
/* 320 */,
/* 321 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
// Converse.js
// https://conversejs.org
//
// Copyright (c) 2020, the Converse.js contributors
// Licensed under the Mozilla Public License (MPLv2)
//
// Webpack entry file
//
// The purpose of this file is to provide an initial temporary public API
// (window.converse) for **before** the rest of converse.js is loaded so
// that we can set the __webpack_public_path__ global variable.
//
// Once the rest converse.js has been loaded, window.converse will be replaced
// with the full-fledged public API.
const plugins = {};
const converse = {
  plugins: {
    add(name, plugin) {
      if (plugins[name] !== undefined) {
        throw new TypeError(`Error: plugin with name "${name}" has already been ` + 'registered!');
      }

      plugins[name] = plugin;
    }

  },

  initialize(settings = {}) {
    converse.load(settings).initialize(settings);
  },

  /**
   * Public API method which explicitly loads Converse and allows you the
   * possibility to pass in configuration settings which need to be defined
   * before loading. Currently this is only the [assets_path](https://conversejs.org/docs/html/configuration.html#assets_path)
   * setting.
   *
   * If not called explicitly, this method will be called implicitly once
   * {@link converse.initialize} is called.
   *
   * In most cases, you probably don't need to explicitly call this method,
   * however, until converse.js has been loaded you won't have access to the
   * utility methods and globals exposed via {@link converse.env}. So if you
   * need to access `converse.env` outside of any plugins and before
   * `converse.initialize` has been called, then you need to call
   * `converse.load` first.
   *
   * @memberOf converse
   * @method load
   * @param {object} settings A map of configuration-settings that are needed at load time.
   * @example
   * converse.load({assets_path: '/path/to/assets/'});
   */
  load(settings = {}) {
    if (settings.assets_path) {
      __webpack_require__.p = settings.assets_path; // eslint-disable-line no-undef
    }

    __webpack_require__(501);

    Object.keys(plugins).forEach(name => converse.plugins.add(name, plugins[name]));
    return converse;
  }

};
window.converse = converse;
/* harmony default export */ __webpack_exports__["default"] = (converse);

/***/ }),
/* 322 */
/***/ (function(module, exports) {

function CustomEvent(event, params) {
  params = params || {
    bubbles: false,
    cancelable: false,
    detail: undefined
  };
  const evt = document.createEvent('CustomEvent');
  evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
  return evt;
}

if (typeof window.CustomEvent !== "function") {
  CustomEvent.prototype = window.Event.prototype;
  window.CustomEvent = CustomEvent;
}

if (!String.prototype.includes) {
  String.prototype.includes = function (search, start) {
    'use strict';

    if (typeof start !== 'number') {
      start = 0;
    }

    if (start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1; // eslint-disable-line lodash/prefer-includes
    }
  };
}

if (!String.prototype.endsWith) {
  String.prototype.endsWith = function (searchString, position) {
    const subjectString = this.toString();

    if (position === undefined || position > subjectString.length) {
      position = subjectString.length;
    }

    position -= searchString.length;
    const lastIndex = subjectString.indexOf(searchString, position);
    return lastIndex !== -1 && lastIndex === position;
  };
}

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function (searchString, position) {
    position = position || 0;
    return this.substr(position, searchString.length) === searchString;
  };
}

if (!String.prototype.splitOnce) {
  String.prototype.splitOnce = function (delimiter) {
    const components = this.split(delimiter);
    return [components.shift(), components.join(delimiter)];
  };
}

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}

/***/ }),
/* 323 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


module.exports = function () {
  throw new Error('ws does not work in the browser. Browser clients must use the native ' + 'WebSocket object');
};

/***/ }),
/* 324 */
/***/ (function(module, exports) {

exports.entityMap = {
  lt: '<',
  gt: '>',
  amp: '&',
  quot: '"',
  apos: "'",
  Agrave: "À",
  Aacute: "Á",
  Acirc: "Â",
  Atilde: "Ã",
  Auml: "Ä",
  Aring: "Å",
  AElig: "Æ",
  Ccedil: "Ç",
  Egrave: "È",
  Eacute: "É",
  Ecirc: "Ê",
  Euml: "Ë",
  Igrave: "Ì",
  Iacute: "Í",
  Icirc: "Î",
  Iuml: "Ï",
  ETH: "Ð",
  Ntilde: "Ñ",
  Ograve: "Ò",
  Oacute: "Ó",
  Ocirc: "Ô",
  Otilde: "Õ",
  Ouml: "Ö",
  Oslash: "Ø",
  Ugrave: "Ù",
  Uacute: "Ú",
  Ucirc: "Û",
  Uuml: "Ü",
  Yacute: "Ý",
  THORN: "Þ",
  szlig: "ß",
  agrave: "à",
  aacute: "á",
  acirc: "â",
  atilde: "ã",
  auml: "ä",
  aring: "å",
  aelig: "æ",
  ccedil: "ç",
  egrave: "è",
  eacute: "é",
  ecirc: "ê",
  euml: "ë",
  igrave: "ì",
  iacute: "í",
  icirc: "î",
  iuml: "ï",
  eth: "ð",
  ntilde: "ñ",
  ograve: "ò",
  oacute: "ó",
  ocirc: "ô",
  otilde: "õ",
  ouml: "ö",
  oslash: "ø",
  ugrave: "ù",
  uacute: "ú",
  ucirc: "û",
  uuml: "ü",
  yacute: "ý",
  thorn: "þ",
  yuml: "ÿ",
  nbsp: "\u00a0",
  iexcl: "¡",
  cent: "¢",
  pound: "£",
  curren: "¤",
  yen: "¥",
  brvbar: "¦",
  sect: "§",
  uml: "¨",
  copy: "©",
  ordf: "ª",
  laquo: "«",
  not: "¬",
  shy: "­­",
  reg: "®",
  macr: "¯",
  deg: "°",
  plusmn: "±",
  sup2: "²",
  sup3: "³",
  acute: "´",
  micro: "µ",
  para: "¶",
  middot: "·",
  cedil: "¸",
  sup1: "¹",
  ordm: "º",
  raquo: "»",
  frac14: "¼",
  frac12: "½",
  frac34: "¾",
  iquest: "¿",
  times: "×",
  divide: "÷",
  forall: "∀",
  part: "∂",
  exist: "∃",
  empty: "∅",
  nabla: "∇",
  isin: "∈",
  notin: "∉",
  ni: "∋",
  prod: "∏",
  sum: "∑",
  minus: "−",
  lowast: "∗",
  radic: "√",
  prop: "∝",
  infin: "∞",
  ang: "∠",
  and: "∧",
  or: "∨",
  cap: "∩",
  cup: "∪",
  'int': "∫",
  there4: "∴",
  sim: "∼",
  cong: "≅",
  asymp: "≈",
  ne: "≠",
  equiv: "≡",
  le: "≤",
  ge: "≥",
  sub: "⊂",
  sup: "⊃",
  nsub: "⊄",
  sube: "⊆",
  supe: "⊇",
  oplus: "⊕",
  otimes: "⊗",
  perp: "⊥",
  sdot: "⋅",
  Alpha: "Α",
  Beta: "Β",
  Gamma: "Γ",
  Delta: "Δ",
  Epsilon: "Ε",
  Zeta: "Ζ",
  Eta: "Η",
  Theta: "Θ",
  Iota: "Ι",
  Kappa: "Κ",
  Lambda: "Λ",
  Mu: "Μ",
  Nu: "Ν",
  Xi: "Ξ",
  Omicron: "Ο",
  Pi: "Π",
  Rho: "Ρ",
  Sigma: "Σ",
  Tau: "Τ",
  Upsilon: "Υ",
  Phi: "Φ",
  Chi: "Χ",
  Psi: "Ψ",
  Omega: "Ω",
  alpha: "α",
  beta: "β",
  gamma: "γ",
  delta: "δ",
  epsilon: "ε",
  zeta: "ζ",
  eta: "η",
  theta: "θ",
  iota: "ι",
  kappa: "κ",
  lambda: "λ",
  mu: "μ",
  nu: "ν",
  xi: "ξ",
  omicron: "ο",
  pi: "π",
  rho: "ρ",
  sigmaf: "ς",
  sigma: "σ",
  tau: "τ",
  upsilon: "υ",
  phi: "φ",
  chi: "χ",
  psi: "ψ",
  omega: "ω",
  thetasym: "ϑ",
  upsih: "ϒ",
  piv: "ϖ",
  OElig: "Œ",
  oelig: "œ",
  Scaron: "Š",
  scaron: "š",
  Yuml: "Ÿ",
  fnof: "ƒ",
  circ: "ˆ",
  tilde: "˜",
  ensp: " ",
  emsp: " ",
  thinsp: " ",
  zwnj: "‌",
  zwj: "‍",
  lrm: "‎",
  rlm: "‏",
  ndash: "–",
  mdash: "—",
  lsquo: "‘",
  rsquo: "’",
  sbquo: "‚",
  ldquo: "“",
  rdquo: "”",
  bdquo: "„",
  dagger: "†",
  Dagger: "‡",
  bull: "•",
  hellip: "…",
  permil: "‰",
  prime: "′",
  Prime: "″",
  lsaquo: "‹",
  rsaquo: "›",
  oline: "‾",
  euro: "€",
  trade: "™",
  larr: "←",
  uarr: "↑",
  rarr: "→",
  darr: "↓",
  harr: "↔",
  crarr: "↵",
  lceil: "⌈",
  rceil: "⌉",
  lfloor: "⌊",
  rfloor: "⌋",
  loz: "◊",
  spades: "♠",
  clubs: "♣",
  hearts: "♥",
  diams: "♦"
};

/***/ }),
/* 325 */
/***/ (function(module, exports) {

//[4]   	NameStartChar	   ::=   	":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
//[4a]   	NameChar	   ::=   	NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
//[5]   	Name	   ::=   	NameStartChar (NameChar)*
var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; //\u10000-\uEFFFF

var nameChar = new RegExp("[\\-\\.0-9" + nameStartChar.source.slice(1, -1) + "\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
var tagNamePattern = new RegExp('^' + nameStartChar.source + nameChar.source + '*(?:\:' + nameStartChar.source + nameChar.source + '*)?$'); //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
//var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
//S_TAG,	S_ATTR,	S_EQ,	S_ATTR_NOQUOT_VALUE
//S_ATTR_SPACE,	S_ATTR_END,	S_TAG_SPACE, S_TAG_CLOSE

var S_TAG = 0; //tag name offerring

var S_ATTR = 1; //attr name offerring 

var S_ATTR_SPACE = 2; //attr name end and space offer

var S_EQ = 3; //=space?

var S_ATTR_NOQUOT_VALUE = 4; //attr value(no quot value only)

var S_ATTR_END = 5; //attr value end and no space(quot end)

var S_TAG_SPACE = 6; //(attr value end || tag end ) && (space offer)

var S_TAG_CLOSE = 7; //closed el<el />

/**
 * Creates an error that will not be caught by XMLReader aka the SAX parser.
 *
 * @param {string} message
 * @param {any?} locator Optional, can provide details about the location in the source
 * @constructor
 */

function ParseError(message, locator) {
  this.message = message;
  this.locator = locator;
  if (Error.captureStackTrace) Error.captureStackTrace(this, ParseError);
}

ParseError.prototype = new Error();
ParseError.prototype.name = ParseError.name;

function XMLReader() {}

XMLReader.prototype = {
  parse: function (source, defaultNSMap, entityMap) {
    var domBuilder = this.domBuilder;
    domBuilder.startDocument();

    _copy(defaultNSMap, defaultNSMap = {});

    parse(source, defaultNSMap, entityMap, domBuilder, this.errorHandler);
    domBuilder.endDocument();
  }
};

function parse(source, defaultNSMapCopy, entityMap, domBuilder, errorHandler) {
  function fixedFromCharCode(code) {
    // String.prototype.fromCharCode does not supports
    // > 2 bytes unicode chars directly
    if (code > 0xffff) {
      code -= 0x10000;
      var surrogate1 = 0xd800 + (code >> 10),
          surrogate2 = 0xdc00 + (code & 0x3ff);
      return String.fromCharCode(surrogate1, surrogate2);
    } else {
      return String.fromCharCode(code);
    }
  }

  function entityReplacer(a) {
    var k = a.slice(1, -1);

    if (k in entityMap) {
      return entityMap[k];
    } else if (k.charAt(0) === '#') {
      return fixedFromCharCode(parseInt(k.substr(1).replace('x', '0x')));
    } else {
      errorHandler.error('entity not found:' + a);
      return a;
    }
  }

  function appendText(end) {
    //has some bugs
    if (end > start) {
      var xt = source.substring(start, end).replace(/&#?\w+;/g, entityReplacer);
      locator && position(start);
      domBuilder.characters(xt, 0, end - start);
      start = end;
    }
  }

  function position(p, m) {
    while (p >= lineEnd && (m = linePattern.exec(source))) {
      lineStart = m.index;
      lineEnd = lineStart + m[0].length;
      locator.lineNumber++; //console.log('line++:',locator,startPos,endPos)
    }

    locator.columnNumber = p - lineStart + 1;
  }

  var lineStart = 0;
  var lineEnd = 0;
  var linePattern = /.*(?:\r\n?|\n)|.*$/g;
  var locator = domBuilder.locator;
  var parseStack = [{
    currentNSMap: defaultNSMapCopy
  }];
  var closeMap = {};
  var start = 0;

  while (true) {
    try {
      var tagStart = source.indexOf('<', start);

      if (tagStart < 0) {
        if (!source.substr(start).match(/^\s*$/)) {
          var doc = domBuilder.doc;
          var text = doc.createTextNode(source.substr(start));
          doc.appendChild(text);
          domBuilder.currentElement = text;
        }

        return;
      }

      if (tagStart > start) {
        appendText(tagStart);
      }

      switch (source.charAt(tagStart + 1)) {
        case '/':
          var end = source.indexOf('>', tagStart + 3);
          var tagName = source.substring(tagStart + 2, end);
          var config = parseStack.pop();

          if (end < 0) {
            tagName = source.substring(tagStart + 2).replace(/[\s<].*/, ''); //console.error('#@@@@@@'+tagName)

            errorHandler.error("end tag name: " + tagName + ' is not complete:' + config.tagName);
            end = tagStart + 1 + tagName.length;
          } else if (tagName.match(/\s</)) {
            tagName = tagName.replace(/[\s<].*/, '');
            errorHandler.error("end tag name: " + tagName + ' maybe not complete');
            end = tagStart + 1 + tagName.length;
          } //console.error(parseStack.length,parseStack)
          //console.error(config);


          var localNSMap = config.localNSMap;
          var endMatch = config.tagName == tagName;
          var endIgnoreCaseMach = endMatch || config.tagName && config.tagName.toLowerCase() == tagName.toLowerCase();

          if (endIgnoreCaseMach) {
            domBuilder.endElement(config.uri, config.localName, tagName);

            if (localNSMap) {
              for (var prefix in localNSMap) {
                domBuilder.endPrefixMapping(prefix);
              }
            }

            if (!endMatch) {
              errorHandler.fatalError("end tag name: " + tagName + ' is not match the current start tagName:' + config.tagName); // No known test case
            }
          } else {
            parseStack.push(config);
          }

          end++;
          break;
        // end elment

        case '?':
          // <?...?>
          locator && position(tagStart);
          end = parseInstruction(source, tagStart, domBuilder);
          break;

        case '!':
          // <!doctype,<![CDATA,<!--
          locator && position(tagStart);
          end = parseDCC(source, tagStart, domBuilder, errorHandler);
          break;

        default:
          locator && position(tagStart);
          var el = new ElementAttributes();
          var currentNSMap = parseStack[parseStack.length - 1].currentNSMap; //elStartEnd

          var end = parseElementStartPart(source, tagStart, el, currentNSMap, entityReplacer, errorHandler);
          var len = el.length;

          if (!el.closed && fixSelfClosed(source, end, el.tagName, closeMap)) {
            el.closed = true;

            if (!entityMap.nbsp) {
              errorHandler.warning('unclosed xml attribute');
            }
          }

          if (locator && len) {
            var locator2 = copyLocator(locator, {}); //try{//attribute position fixed

            for (var i = 0; i < len; i++) {
              var a = el[i];
              position(a.offset);
              a.locator = copyLocator(locator, {});
            } //}catch(e){console.error('@@@@@'+e)}


            domBuilder.locator = locator2;

            if (appendElement(el, domBuilder, currentNSMap)) {
              parseStack.push(el);
            }

            domBuilder.locator = locator;
          } else {
            if (appendElement(el, domBuilder, currentNSMap)) {
              parseStack.push(el);
            }
          }

          if (el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed) {
            end = parseHtmlSpecialContent(source, end, el.tagName, entityReplacer, domBuilder);
          } else {
            end++;
          }

      }
    } catch (e) {
      if (e instanceof ParseError) {
        throw e;
      }

      errorHandler.error('element parse error: ' + e);
      end = -1;
    }

    if (end > start) {
      start = end;
    } else {
      //TODO: 这里有可能sax回退，有位置错误风险
      appendText(Math.max(tagStart, start) + 1);
    }
  }
}

function copyLocator(f, t) {
  t.lineNumber = f.lineNumber;
  t.columnNumber = f.columnNumber;
  return t;
}
/**
 * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
 * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
 */


function parseElementStartPart(source, start, el, currentNSMap, entityReplacer, errorHandler) {
  /**
   * @param {string} qname
   * @param {string} value
   * @param {number} startIndex
   */
  function addAttribute(qname, value, startIndex) {
    if (qname in el.attributeNames) errorHandler.fatalError('Attribute ' + qname + ' redefined');
    el.addValue(qname, value, startIndex);
  }

  var attrName;
  var value;
  var p = ++start;
  var s = S_TAG; //status

  while (true) {
    var c = source.charAt(p);

    switch (c) {
      case '=':
        if (s === S_ATTR) {
          //attrName
          attrName = source.slice(start, p);
          s = S_EQ;
        } else if (s === S_ATTR_SPACE) {
          s = S_EQ;
        } else {
          //fatalError: equal must after attrName or space after attrName
          throw new Error('attribute equal must after attrName'); // No known test case
        }

        break;

      case '\'':
      case '"':
        if (s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
        ) {
            //equal
            if (s === S_ATTR) {
              errorHandler.warning('attribute value must after "="');
              attrName = source.slice(start, p);
            }

            start = p + 1;
            p = source.indexOf(c, start);

            if (p > 0) {
              value = source.slice(start, p).replace(/&#?\w+;/g, entityReplacer);
              addAttribute(attrName, value, start - 1);
              s = S_ATTR_END;
            } else {
              //fatalError: no end quot match
              throw new Error('attribute value no end \'' + c + '\' match');
            }
          } else if (s == S_ATTR_NOQUOT_VALUE) {
          value = source.slice(start, p).replace(/&#?\w+;/g, entityReplacer); //console.log(attrName,value,start,p)

          addAttribute(attrName, value, start); //console.dir(el)

          errorHandler.warning('attribute "' + attrName + '" missed start quot(' + c + ')!!');
          start = p + 1;
          s = S_ATTR_END;
        } else {
          //fatalError: no equal before
          throw new Error('attribute value must after "="'); // No known test case
        }

        break;

      case '/':
        switch (s) {
          case S_TAG:
            el.setTagName(source.slice(start, p));

          case S_ATTR_END:
          case S_TAG_SPACE:
          case S_TAG_CLOSE:
            s = S_TAG_CLOSE;
            el.closed = true;

          case S_ATTR_NOQUOT_VALUE:
          case S_ATTR:
          case S_ATTR_SPACE:
            break;
          //case S_EQ:

          default:
            throw new Error("attribute invalid close char('/')");
          // No known test case
        }

        break;

      case '':
        //end document
        errorHandler.error('unexpected end of input');

        if (s == S_TAG) {
          el.setTagName(source.slice(start, p));
        }

        return p;

      case '>':
        switch (s) {
          case S_TAG:
            el.setTagName(source.slice(start, p));

          case S_ATTR_END:
          case S_TAG_SPACE:
          case S_TAG_CLOSE:
            break;
          //normal

          case S_ATTR_NOQUOT_VALUE: //Compatible state

          case S_ATTR:
            value = source.slice(start, p);

            if (value.slice(-1) === '/') {
              el.closed = true;
              value = value.slice(0, -1);
            }

          case S_ATTR_SPACE:
            if (s === S_ATTR_SPACE) {
              value = attrName;
            }

            if (s == S_ATTR_NOQUOT_VALUE) {
              errorHandler.warning('attribute "' + value + '" missed quot(")!');
              addAttribute(attrName, value.replace(/&#?\w+;/g, entityReplacer), start);
            } else {
              if (currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)) {
                errorHandler.warning('attribute "' + value + '" missed value!! "' + value + '" instead!!');
              }

              addAttribute(value, value, start);
            }

            break;

          case S_EQ:
            throw new Error('attribute value missed!!');
        } //			console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))


        return p;

      /*xml space '\x20' | #x9 | #xD | #xA; */

      case '\u0080':
        c = ' ';

      default:
        if (c <= ' ') {
          //space
          switch (s) {
            case S_TAG:
              el.setTagName(source.slice(start, p)); //tagName

              s = S_TAG_SPACE;
              break;

            case S_ATTR:
              attrName = source.slice(start, p);
              s = S_ATTR_SPACE;
              break;

            case S_ATTR_NOQUOT_VALUE:
              var value = source.slice(start, p).replace(/&#?\w+;/g, entityReplacer);
              errorHandler.warning('attribute "' + value + '" missed quot(")!!');
              addAttribute(attrName, value, start);

            case S_ATTR_END:
              s = S_TAG_SPACE;
              break;
            //case S_TAG_SPACE:
            //case S_EQ:
            //case S_ATTR_SPACE:
            //	void();break;
            //case S_TAG_CLOSE:
            //ignore warning
          }
        } else {
          //not space
          //S_TAG,	S_ATTR,	S_EQ,	S_ATTR_NOQUOT_VALUE
          //S_ATTR_SPACE,	S_ATTR_END,	S_TAG_SPACE, S_TAG_CLOSE
          switch (s) {
            //case S_TAG:void();break;
            //case S_ATTR:void();break;
            //case S_ATTR_NOQUOT_VALUE:void();break;
            case S_ATTR_SPACE:
              var tagName = el.tagName;

              if (currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)) {
                errorHandler.warning('attribute "' + attrName + '" missed value!! "' + attrName + '" instead2!!');
              }

              addAttribute(attrName, attrName, start);
              start = p;
              s = S_ATTR;
              break;

            case S_ATTR_END:
              errorHandler.warning('attribute space is required"' + attrName + '"!!');

            case S_TAG_SPACE:
              s = S_ATTR;
              start = p;
              break;

            case S_EQ:
              s = S_ATTR_NOQUOT_VALUE;
              start = p;
              break;

            case S_TAG_CLOSE:
              throw new Error("elements closed character '/' and '>' must be connected to");
          }
        }

    } //end outer switch
    //console.log('p++',p)


    p++;
  }
}
/**
 * @return true if has new namespace define
 */


function appendElement(el, domBuilder, currentNSMap) {
  var tagName = el.tagName;
  var localNSMap = null; //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;

  var i = el.length;

  while (i--) {
    var a = el[i];
    var qName = a.qName;
    var value = a.value;
    var nsp = qName.indexOf(':');

    if (nsp > 0) {
      var prefix = a.prefix = qName.slice(0, nsp);
      var localName = qName.slice(nsp + 1);
      var nsPrefix = prefix === 'xmlns' && localName;
    } else {
      localName = qName;
      prefix = null;
      nsPrefix = qName === 'xmlns' && '';
    } //can not set prefix,because prefix !== ''


    a.localName = localName; //prefix == null for no ns prefix attribute 

    if (nsPrefix !== false) {
      //hack!!
      if (localNSMap == null) {
        localNSMap = {}; //console.log(currentNSMap,0)

        _copy(currentNSMap, currentNSMap = {}); //console.log(currentNSMap,1)

      }

      currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
      a.uri = 'http://www.w3.org/2000/xmlns/';
      domBuilder.startPrefixMapping(nsPrefix, value);
    }
  }

  var i = el.length;

  while (i--) {
    a = el[i];
    var prefix = a.prefix;

    if (prefix) {
      //no prefix attribute has no namespace
      if (prefix === 'xml') {
        a.uri = 'http://www.w3.org/XML/1998/namespace';
      }

      if (prefix !== 'xmlns') {
        a.uri = currentNSMap[prefix || '']; //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
      }
    }
  }

  var nsp = tagName.indexOf(':');

  if (nsp > 0) {
    prefix = el.prefix = tagName.slice(0, nsp);
    localName = el.localName = tagName.slice(nsp + 1);
  } else {
    prefix = null; //important!!

    localName = el.localName = tagName;
  } //no prefix element has default namespace


  var ns = el.uri = currentNSMap[prefix || ''];
  domBuilder.startElement(ns, localName, tagName, el); //endPrefixMapping and startPrefixMapping have not any help for dom builder
  //localNSMap = null

  if (el.closed) {
    domBuilder.endElement(ns, localName, tagName);

    if (localNSMap) {
      for (prefix in localNSMap) {
        domBuilder.endPrefixMapping(prefix);
      }
    }
  } else {
    el.currentNSMap = currentNSMap;
    el.localNSMap = localNSMap; //parseStack.push(el);

    return true;
  }
}

function parseHtmlSpecialContent(source, elStartEnd, tagName, entityReplacer, domBuilder) {
  if (/^(?:script|textarea)$/i.test(tagName)) {
    var elEndStart = source.indexOf('</' + tagName + '>', elStartEnd);
    var text = source.substring(elStartEnd + 1, elEndStart);

    if (/[&<]/.test(text)) {
      if (/^script$/i.test(tagName)) {
        //if(!/\]\]>/.test(text)){
        //lexHandler.startCDATA();
        domBuilder.characters(text, 0, text.length); //lexHandler.endCDATA();

        return elEndStart; //}
      } //}else{//text area


      text = text.replace(/&#?\w+;/g, entityReplacer);
      domBuilder.characters(text, 0, text.length);
      return elEndStart; //}
    }
  }

  return elStartEnd + 1;
}

function fixSelfClosed(source, elStartEnd, tagName, closeMap) {
  //if(tagName in closeMap){
  var pos = closeMap[tagName];

  if (pos == null) {
    //console.log(tagName)
    pos = source.lastIndexOf('</' + tagName + '>');

    if (pos < elStartEnd) {
      //忘记闭合
      pos = source.lastIndexOf('</' + tagName);
    }

    closeMap[tagName] = pos;
  }

  return pos < elStartEnd; //} 
}

function _copy(source, target) {
  for (var n in source) {
    target[n] = source[n];
  }
}

function parseDCC(source, start, domBuilder, errorHandler) {
  //sure start with '<!'
  var next = source.charAt(start + 2);

  switch (next) {
    case '-':
      if (source.charAt(start + 3) === '-') {
        var end = source.indexOf('-->', start + 4); //append comment source.substring(4,end)//<!--

        if (end > start) {
          domBuilder.comment(source, start + 4, end - start - 4);
          return end + 3;
        } else {
          errorHandler.error("Unclosed comment");
          return -1;
        }
      } else {
        //error
        return -1;
      }

    default:
      if (source.substr(start + 3, 6) == 'CDATA[') {
        var end = source.indexOf(']]>', start + 9);
        domBuilder.startCDATA();
        domBuilder.characters(source, start + 9, end - start - 9);
        domBuilder.endCDATA();
        return end + 3;
      } //<!DOCTYPE
      //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId) 


      var matchs = split(source, start);
      var len = matchs.length;

      if (len > 1 && /!doctype/i.test(matchs[0][0])) {
        var name = matchs[1][0];
        var pubid = false;
        var sysid = false;

        if (len > 3) {
          if (/^public$/i.test(matchs[2][0])) {
            pubid = matchs[3][0];
            sysid = len > 4 && matchs[4][0];
          } else if (/^system$/i.test(matchs[2][0])) {
            sysid = matchs[3][0];
          }
        }

        var lastMatch = matchs[len - 1];
        domBuilder.startDTD(name, pubid, sysid);
        domBuilder.endDTD();
        return lastMatch.index + lastMatch[0].length;
      }

  }

  return -1;
}

function parseInstruction(source, start, domBuilder) {
  var end = source.indexOf('?>', start);

  if (end) {
    var match = source.substring(start, end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);

    if (match) {
      var len = match[0].length;
      domBuilder.processingInstruction(match[1], match[2]);
      return end + 2;
    } else {
      //error
      return -1;
    }
  }

  return -1;
}

function ElementAttributes() {
  this.attributeNames = {};
}

ElementAttributes.prototype = {
  setTagName: function (tagName) {
    if (!tagNamePattern.test(tagName)) {
      throw new Error('invalid tagName:' + tagName);
    }

    this.tagName = tagName;
  },
  addValue: function (qName, value, offset) {
    if (!tagNamePattern.test(qName)) {
      throw new Error('invalid attribute:' + qName);
    }

    this.attributeNames[qName] = this.length;
    this[this.length++] = {
      qName: qName,
      value: value,
      offset: offset
    };
  },
  length: 0,
  getLocalName: function (i) {
    return this[i].localName;
  },
  getLocator: function (i) {
    return this[i].locator;
  },
  getQName: function (i) {
    return this[i].qName;
  },
  getURI: function (i) {
    return this[i].uri;
  },
  getValue: function (i) {
    return this[i].value;
  } //	,getIndex:function(uri, localName)){
  //		if(localName){
  //			
  //		}else{
  //			var qName = uri
  //		}
  //	},
  //	getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
  //	getType:function(uri,localName){}
  //	getType:function(i){},

};

function split(source, start) {
  var match;
  var buf = [];
  var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
  reg.lastIndex = start;
  reg.exec(source); //skip <

  while (match = reg.exec(source)) {
    buf.push(match);
    if (match[1]) return buf;
  }
}

exports.XMLReader = XMLReader;
exports.ParseError = ParseError;

/***/ }),
/* 326 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/**
 * Implementation of atob() according to the HTML and Infra specs, except that
 * instead of throwing INVALID_CHARACTER_ERR we return null.
 */

function atob(data) {
  // Web IDL requires DOMStrings to just be converted using ECMAScript
  // ToString, which in our case amounts to using a template literal.
  data = `${data}`; // "Remove all ASCII whitespace from data."

  data = data.replace(/[ \t\n\f\r]/g, ""); // "If data's length divides by 4 leaving no remainder, then: if data ends
  // with one or two U+003D (=) code points, then remove them from data."

  if (data.length % 4 === 0) {
    data = data.replace(/==?$/, "");
  } // "If data's length divides by 4 leaving a remainder of 1, then return
  // failure."
  //
  // "If data contains a code point that is not one of
  //
  // U+002B (+)
  // U+002F (/)
  // ASCII alphanumeric
  //
  // then return failure."


  if (data.length % 4 === 1 || /[^+/0-9A-Za-z]/.test(data)) {
    return null;
  } // "Let output be an empty byte sequence."


  let output = ""; // "Let buffer be an empty buffer that can have bits appended to it."
  //
  // We append bits via left-shift and or.  accumulatedBits is used to track
  // when we've gotten to 24 bits.

  let buffer = 0;
  let accumulatedBits = 0; // "Let position be a position variable for data, initially pointing at the
  // start of data."
  //
  // "While position does not point past the end of data:"

  for (let i = 0; i < data.length; i++) {
    // "Find the code point pointed to by position in the second column of
    // Table 1: The Base 64 Alphabet of RFC 4648. Let n be the number given in
    // the first cell of the same row.
    //
    // "Append to buffer the six bits corresponding to n, most significant bit
    // first."
    //
    // atobLookup() implements the table from RFC 4648.
    buffer <<= 6;
    buffer |= atobLookup(data[i]);
    accumulatedBits += 6; // "If buffer has accumulated 24 bits, interpret them as three 8-bit
    // big-endian numbers. Append three bytes with values equal to those
    // numbers to output, in the same order, and then empty buffer."

    if (accumulatedBits === 24) {
      output += String.fromCharCode((buffer & 0xff0000) >> 16);
      output += String.fromCharCode((buffer & 0xff00) >> 8);
      output += String.fromCharCode(buffer & 0xff);
      buffer = accumulatedBits = 0;
    } // "Advance position by 1."

  } // "If buffer is not empty, it contains either 12 or 18 bits. If it contains
  // 12 bits, then discard the last four and interpret the remaining eight as
  // an 8-bit big-endian number. If it contains 18 bits, then discard the last
  // two and interpret the remaining 16 as two 8-bit big-endian numbers. Append
  // the one or two bytes with values equal to those one or two numbers to
  // output, in the same order."


  if (accumulatedBits === 12) {
    buffer >>= 4;
    output += String.fromCharCode(buffer);
  } else if (accumulatedBits === 18) {
    buffer >>= 2;
    output += String.fromCharCode((buffer & 0xff00) >> 8);
    output += String.fromCharCode(buffer & 0xff);
  } // "Return output."


  return output;
}
/**
 * A lookup table for atob(), which converts an ASCII character to the
 * corresponding six-bit number.
 */


const keystr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

function atobLookup(chr) {
  const index = keystr.indexOf(chr); // Throw exception if character is not in the lookup string; should not be hit in tests

  return index < 0 ? undefined : index;
}

module.exports = atob;

/***/ }),
/* 327 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/**
 * btoa() as defined by the HTML and Infra specs, which mostly just references
 * RFC 4648.
 */

function btoa(s) {
  let i; // String conversion as required by Web IDL.

  s = `${s}`; // "The btoa() method must throw an "InvalidCharacterError" DOMException if
  // data contains any character whose code point is greater than U+00FF."

  for (i = 0; i < s.length; i++) {
    if (s.charCodeAt(i) > 255) {
      return null;
    }
  }

  let out = "";

  for (i = 0; i < s.length; i += 3) {
    const groupsOfSix = [undefined, undefined, undefined, undefined];
    groupsOfSix[0] = s.charCodeAt(i) >> 2;
    groupsOfSix[1] = (s.charCodeAt(i) & 0x03) << 4;

    if (s.length > i + 1) {
      groupsOfSix[1] |= s.charCodeAt(i + 1) >> 4;
      groupsOfSix[2] = (s.charCodeAt(i + 1) & 0x0f) << 2;
    }

    if (s.length > i + 2) {
      groupsOfSix[2] |= s.charCodeAt(i + 2) >> 6;
      groupsOfSix[3] = s.charCodeAt(i + 2) & 0x3f;
    }

    for (let j = 0; j < groupsOfSix.length; j++) {
      if (typeof groupsOfSix[j] === "undefined") {
        out += "=";
      } else {
        out += btoaLookup(groupsOfSix[j]);
      }
    }
  }

  return out;
}
/**
 * Lookup table for btoa(), which converts a six-bit number into the
 * corresponding ASCII character.
 */


const keystr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

function btoaLookup(index) {
  if (index >= 0 && index < 64) {
    return keystr[index];
  } // Throw INVALID_CHARACTER_ERR exception here -- won't be hit in the tests.


  return undefined;
}

module.exports = btoa;

/***/ }),
/* 328 */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.slice` without an iteratee call guard.
 *
 * @private
 * @param {Array} array The array to slice.
 * @param {number} [start=0] The start position.
 * @param {number} [end=array.length] The end position.
 * @returns {Array} Returns the slice of `array`.
 */
function baseSlice(array, start, end) {
  var index = -1,
      length = array.length;

  if (start < 0) {
    start = -start > length ? 0 : length + start;
  }

  end = end > length ? length : end;

  if (end < 0) {
    end += length;
  }

  length = start > end ? 0 : end - start >>> 0;
  start >>>= 0;
  var result = Array(length);

  while (++index < length) {
    result[index] = array[index + start];
  }

  return result;
}

module.exports = baseSlice;

/***/ }),
/* 329 */
/***/ (function(module, exports, __webpack_require__) {

var toNumber = __webpack_require__(330);
/** Used as references for various `Number` constants. */


var INFINITY = 1 / 0,
    MAX_INTEGER = 1.7976931348623157e+308;
/**
 * Converts `value` to a finite number.
 *
 * @static
 * @memberOf _
 * @since 4.12.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted number.
 * @example
 *
 * _.toFinite(3.2);
 * // => 3.2
 *
 * _.toFinite(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toFinite(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toFinite('3.2');
 * // => 3.2
 */

function toFinite(value) {
  if (!value) {
    return value === 0 ? value : 0;
  }

  value = toNumber(value);

  if (value === INFINITY || value === -INFINITY) {
    var sign = value < 0 ? -1 : 1;
    return sign * MAX_INTEGER;
  }

  return value === value ? value : 0;
}

module.exports = toFinite;

/***/ }),
/* 330 */
/***/ (function(module, exports, __webpack_require__) {

var baseTrim = __webpack_require__(331),
    isObject = __webpack_require__(16),
    isSymbol = __webpack_require__(44);
/** Used as references for various `Number` constants. */


var NAN = 0 / 0;
/** Used to detect bad signed hexadecimal string values. */

var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */

var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */

var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */

var freeParseInt = parseInt;
/**
 * Converts `value` to a number.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to process.
 * @returns {number} Returns the number.
 * @example
 *
 * _.toNumber(3.2);
 * // => 3.2
 *
 * _.toNumber(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toNumber(Infinity);
 * // => Infinity
 *
 * _.toNumber('3.2');
 * // => 3.2
 */

function toNumber(value) {
  if (typeof value == 'number') {
    return value;
  }

  if (isSymbol(value)) {
    return NAN;
  }

  if (isObject(value)) {
    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
    value = isObject(other) ? other + '' : other;
  }

  if (typeof value != 'string') {
    return value === 0 ? value : +value;
  }

  value = baseTrim(value);
  var isBinary = reIsBinary.test(value);
  return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}

module.exports = toNumber;

/***/ }),
/* 331 */
/***/ (function(module, exports, __webpack_require__) {

var trimmedEndIndex = __webpack_require__(332);
/** Used to match leading whitespace. */


var reTrimStart = /^\s+/;
/**
 * The base implementation of `_.trim`.
 *
 * @private
 * @param {string} string The string to trim.
 * @returns {string} Returns the trimmed string.
 */

function baseTrim(string) {
  return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string;
}

module.exports = baseTrim;

/***/ }),
/* 332 */
/***/ (function(module, exports) {

/** Used to match a single whitespace character. */
var reWhitespace = /\s/;
/**
 * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
 * character of `string`.
 *
 * @private
 * @param {string} string The string to inspect.
 * @returns {number} Returns the index of the last non-whitespace character.
 */

function trimmedEndIndex(string) {
  var index = string.length;

  while (index-- && reWhitespace.test(string.charAt(index))) {}

  return index;
}

module.exports = trimmedEndIndex;

/***/ }),
/* 333 */
/***/ (function(module, exports, __webpack_require__) {

var Symbol = __webpack_require__(45);
/** Used for built-in method references. */


var objectProto = Object.prototype;
/** Used to check objects for own properties. */

var hasOwnProperty = objectProto.hasOwnProperty;
/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */

var nativeObjectToString = objectProto.toString;
/** Built-in value references. */

var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the raw `toStringTag`.
 */

function getRawTag(value) {
  var isOwn = hasOwnProperty.call(value, symToStringTag),
      tag = value[symToStringTag];

  try {
    value[symToStringTag] = undefined;
    var unmasked = true;
  } catch (e) {}

  var result = nativeObjectToString.call(value);

  if (unmasked) {
    if (isOwn) {
      value[symToStringTag] = tag;
    } else {
      delete value[symToStringTag];
    }
  }

  return result;
}

module.exports = getRawTag;

/***/ }),
/* 334 */
/***/ (function(module, exports) {

/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */

var nativeObjectToString = objectProto.toString;
/**
 * Converts `value` to a string using `Object.prototype.toString`.
 *
 * @private
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 */

function objectToString(value) {
  return nativeObjectToString.call(value);
}

module.exports = objectToString;

/***/ }),
/* 335 */
/***/ (function(module, exports, __webpack_require__) {

var arrayEach = __webpack_require__(95),
    baseEach = __webpack_require__(336),
    castFunction = __webpack_require__(348),
    isArray = __webpack_require__(12);
/**
 * Iterates over elements of `collection` and invokes `iteratee` for each element.
 * The iteratee is invoked with three arguments: (value, index|key, collection).
 * Iteratee functions may exit iteration early by explicitly returning `false`.
 *
 * **Note:** As with other "Collections" methods, objects with a "length"
 * property are iterated like arrays. To avoid this behavior use `_.forIn`
 * or `_.forOwn` for object iteration.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @alias each
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
 * @returns {Array|Object} Returns `collection`.
 * @see _.forEachRight
 * @example
 *
 * _.forEach([1, 2], function(value) {
 *   console.log(value);
 * });
 * // => Logs `1` then `2`.
 *
 * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
 *   console.log(key);
 * });
 * // => Logs 'a' then 'b' (iteration order is not guaranteed).
 */


function forEach(collection, iteratee) {
  var func = isArray(collection) ? arrayEach : baseEach;
  return func(collection, castFunction(iteratee));
}

module.exports = forEach;

/***/ }),
/* 336 */
/***/ (function(module, exports, __webpack_require__) {

var baseForOwn = __webpack_require__(337),
    createBaseEach = __webpack_require__(347);
/**
 * The base implementation of `_.forEach` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array|Object} Returns `collection`.
 */


var baseEach = createBaseEach(baseForOwn);
module.exports = baseEach;

/***/ }),
/* 337 */
/***/ (function(module, exports, __webpack_require__) {

var baseFor = __webpack_require__(338),
    keys = __webpack_require__(29);
/**
 * The base implementation of `_.forOwn` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Object} Returns `object`.
 */


function baseForOwn(object, iteratee) {
  return object && baseFor(object, iteratee, keys);
}

module.exports = baseForOwn;

/***/ }),
/* 338 */
/***/ (function(module, exports, __webpack_require__) {

var createBaseFor = __webpack_require__(339);
/**
 * The base implementation of `baseForOwn` which iterates over `object`
 * properties returned by `keysFunc` and invokes `iteratee` for each property.
 * Iteratee functions may exit iteration early by explicitly returning `false`.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @returns {Object} Returns `object`.
 */


var baseFor = createBaseFor();
module.exports = baseFor;

/***/ }),
/* 339 */
/***/ (function(module, exports) {

/**
 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
 *
 * @private
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new base function.
 */
function createBaseFor(fromRight) {
  return function (object, iteratee, keysFunc) {
    var index = -1,
        iterable = Object(object),
        props = keysFunc(object),
        length = props.length;

    while (length--) {
      var key = props[fromRight ? length : ++index];

      if (iteratee(iterable[key], key, iterable) === false) {
        break;
      }
    }

    return object;
  };
}

module.exports = createBaseFor;

/***/ }),
/* 340 */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.times` without support for iteratee shorthands
 * or max array length checks.
 *
 * @private
 * @param {number} n The number of times to invoke `iteratee`.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the array of results.
 */
function baseTimes(n, iteratee) {
  var index = -1,
      result = Array(n);

  while (++index < n) {
    result[index] = iteratee(index);
  }

  return result;
}

module.exports = baseTimes;

/***/ }),
/* 341 */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(20),
    isObjectLike = __webpack_require__(19);
/** `Object#toString` result references. */


var argsTag = '[object Arguments]';
/**
 * The base implementation of `_.isArguments`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 */

function baseIsArguments(value) {
  return isObjectLike(value) && baseGetTag(value) == argsTag;
}

module.exports = baseIsArguments;

/***/ }),
/* 342 */
/***/ (function(module, exports) {

/**
 * This method returns `false`.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {boolean} Returns `false`.
 * @example
 *
 * _.times(2, _.stubFalse);
 * // => [false, false]
 */
function stubFalse() {
  return false;
}

module.exports = stubFalse;

/***/ }),
/* 343 */
/***/ (function(module, exports, __webpack_require__) {

var baseGetTag = __webpack_require__(20),
    isLength = __webpack_require__(68),
    isObjectLike = __webpack_require__(19);
/** `Object#toString` result references. */


var argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    funcTag = '[object Function]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    objectTag = '[object Object]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
    dataViewTag = '[object DataView]',
    float32Tag = '[object Float32Array]',
    float64Tag = '[object Float64Array]',
    int8Tag = '[object Int8Array]',
    int16Tag = '[object Int16Array]',
    int32Tag = '[object Int32Array]',
    uint8Tag = '[object Uint8Array]',
    uint8ClampedTag = '[object Uint8ClampedArray]',
    uint16Tag = '[object Uint16Array]',
    uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */

var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
/**
 * The base implementation of `_.isTypedArray` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 */

function baseIsTypedArray(value) {
  return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}

module.exports = baseIsTypedArray;

/***/ }),
/* 344 */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.unary` without support for storing metadata.
 *
 * @private
 * @param {Function} func The function to cap arguments for.
 * @returns {Function} Returns the new capped function.
 */
function baseUnary(func) {
  return function (value) {
    return func(value);
  };
}

module.exports = baseUnary;

/***/ }),
/* 345 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(94);
/** Detect free variable `exports`. */


var freeExports =  true && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */

var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */

var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */

var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */

var nodeUtil = function () {
  try {
    // Use `util.types` for Node.js 10+.
    var types = freeModule && freeModule.require && freeModule.require('util').types;

    if (types) {
      return types;
    } // Legacy `process.binding('util')` for Node.js < 10.


    return freeProcess && freeProcess.binding && freeProcess.binding('util');
  } catch (e) {}
}();

module.exports = nodeUtil;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(43)(module)))

/***/ }),
/* 346 */
/***/ (function(module, exports, __webpack_require__) {

var overArg = __webpack_require__(102);
/* Built-in method references for those with the same name as other `lodash` methods. */


var nativeKeys = overArg(Object.keys, Object);
module.exports = nativeKeys;

/***/ }),
/* 347 */
/***/ (function(module, exports, __webpack_require__) {

var isArrayLike = __webpack_require__(25);
/**
 * Creates a `baseEach` or `baseEachRight` function.
 *
 * @private
 * @param {Function} eachFunc The function to iterate over a collection.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new base function.
 */


function createBaseEach(eachFunc, fromRight) {
  return function (collection, iteratee) {
    if (collection == null) {
      return collection;
    }

    if (!isArrayLike(collection)) {
      return eachFunc(collection, iteratee);
    }

    var length = collection.length,
        index = fromRight ? length : -1,
        iterable = Object(collection);

    while (fromRight ? index-- : ++index < length) {
      if (iteratee(iterable[index], index, iterable) === false) {
        break;
      }
    }

    return collection;
  };
}

module.exports = createBaseEach;

/***/ }),
/* 348 */
/***/ (function(module, exports, __webpack_require__) {

var identity = __webpack_require__(34);
/**
 * Casts `value` to `identity` if it's not a function.
 *
 * @private
 * @param {*} value The value to inspect.
 * @returns {Function} Returns cast function.
 */


function castFunction(value) {
  return typeof value == 'function' ? value : identity;
}

module.exports = castFunction;

/***/ }),
/* 349 */
/***/ (function(module, exports, __webpack_require__) {

var copyObject = __webpack_require__(350),
    createAssigner = __webpack_require__(355),
    keysIn = __webpack_require__(110);
/**
 * This method is like `_.assign` except that it iterates over own and
 * inherited source properties.
 *
 * **Note:** This method mutates `object`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @alias extend
 * @category Object
 * @param {Object} object The destination object.
 * @param {...Object} [sources] The source objects.
 * @returns {Object} Returns `object`.
 * @see _.assign
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 * }
 *
 * function Bar() {
 *   this.c = 3;
 * }
 *
 * Foo.prototype.b = 2;
 * Bar.prototype.d = 4;
 *
 * _.assignIn({ 'a': 0 }, new Foo, new Bar);
 * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
 */


var assignIn = createAssigner(function (object, source) {
  copyObject(source, keysIn(source), object);
});
module.exports = assignIn;

/***/ }),
/* 350 */
/***/ (function(module, exports, __webpack_require__) {

var assignValue = __webpack_require__(103),
    baseAssignValue = __webpack_require__(104);
/**
 * Copies properties of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy properties from.
 * @param {Array} props The property identifiers to copy.
 * @param {Object} [object={}] The object to copy properties to.
 * @param {Function} [customizer] The function to customize copied values.
 * @returns {Object} Returns `object`.
 */


function copyObject(source, props, object, customizer) {
  var isNew = !object;
  object || (object = {});
  var index = -1,
      length = props.length;

  while (++index < length) {
    var key = props[index];
    var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined;

    if (newValue === undefined) {
      newValue = source[key];
    }

    if (isNew) {
      baseAssignValue(object, key, newValue);
    } else {
      assignValue(object, key, newValue);
    }
  }

  return object;
}

module.exports = copyObject;

/***/ }),
/* 351 */
/***/ (function(module, exports, __webpack_require__) {

var isFunction = __webpack_require__(58),
    isMasked = __webpack_require__(352),
    isObject = __webpack_require__(16),
    toSource = __webpack_require__(106);
/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */


var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */

var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */

var funcProto = Function.prototype,
    objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */

var funcToString = funcProto.toString;
/** Used to check objects for own properties. */

var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */

var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
/**
 * The base implementation of `_.isNative` without bad shim checks.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function,
 *  else `false`.
 */

function baseIsNative(value) {
  if (!isObject(value) || isMasked(value)) {
    return false;
  }

  var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
  return pattern.test(toSource(value));
}

module.exports = baseIsNative;

/***/ }),
/* 352 */
/***/ (function(module, exports, __webpack_require__) {

var coreJsData = __webpack_require__(353);
/** Used to detect methods masquerading as native. */


var maskSrcKey = function () {
  var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  return uid ? 'Symbol(src)_1.' + uid : '';
}();
/**
 * Checks if `func` has its source masked.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
 */


function isMasked(func) {
  return !!maskSrcKey && maskSrcKey in func;
}

module.exports = isMasked;

/***/ }),
/* 353 */
/***/ (function(module, exports, __webpack_require__) {

var root = __webpack_require__(9);
/** Used to detect overreaching core-js shims. */


var coreJsData = root['__core-js_shared__'];
module.exports = coreJsData;

/***/ }),
/* 354 */
/***/ (function(module, exports) {

/**
 * Gets the value at `key` of `object`.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function getValue(object, key) {
  return object == null ? undefined : object[key];
}

module.exports = getValue;

/***/ }),
/* 355 */
/***/ (function(module, exports, __webpack_require__) {

var baseRest = __webpack_require__(107),
    isIterateeCall = __webpack_require__(359);
/**
 * Creates a function like `_.assign`.
 *
 * @private
 * @param {Function} assigner The function to assign values.
 * @returns {Function} Returns the new assigner function.
 */


function createAssigner(assigner) {
  return baseRest(function (object, sources) {
    var index = -1,
        length = sources.length,
        customizer = length > 1 ? sources[length - 1] : undefined,
        guard = length > 2 ? sources[2] : undefined;
    customizer = assigner.length > 3 && typeof customizer == 'function' ? (length--, customizer) : undefined;

    if (guard && isIterateeCall(sources[0], sources[1], guard)) {
      customizer = length < 3 ? undefined : customizer;
      length = 1;
    }

    object = Object(object);

    while (++index < length) {
      var source = sources[index];

      if (source) {
        assigner(object, source, index, customizer);
      }
    }

    return object;
  });
}

module.exports = createAssigner;

/***/ }),
/* 356 */
/***/ (function(module, exports, __webpack_require__) {

var apply = __webpack_require__(69);
/* Built-in method references for those with the same name as other `lodash` methods. */


var nativeMax = Math.max;
/**
 * A specialized version of `baseRest` which transforms the rest array.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @param {Function} transform The rest array transform.
 * @returns {Function} Returns the new function.
 */

function overRest(func, start, transform) {
  start = nativeMax(start === undefined ? func.length - 1 : start, 0);
  return function () {
    var args = arguments,
        index = -1,
        length = nativeMax(args.length - start, 0),
        array = Array(length);

    while (++index < length) {
      array[index] = args[start + index];
    }

    index = -1;
    var otherArgs = Array(start + 1);

    while (++index < start) {
      otherArgs[index] = args[index];
    }

    otherArgs[start] = transform(array);
    return apply(func, this, otherArgs);
  };
}

module.exports = overRest;

/***/ }),
/* 357 */
/***/ (function(module, exports, __webpack_require__) {

var constant = __webpack_require__(358),
    defineProperty = __webpack_require__(105),
    identity = __webpack_require__(34);
/**
 * The base implementation of `setToString` without support for hot loop shorting.
 *
 * @private
 * @param {Function} func The function to modify.
 * @param {Function} string The `toString` result.
 * @returns {Function} Returns `func`.
 */


var baseSetToString = !defineProperty ? identity : function (func, string) {
  return defineProperty(func, 'toString', {
    'configurable': true,
    'enumerable': false,
    'value': constant(string),
    'writable': true
  });
};
module.exports = baseSetToString;

/***/ }),
/* 358 */
/***/ (function(module, exports) {

/**
 * Creates a function that returns `value`.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Util
 * @param {*} value The value to return from the new function.
 * @returns {Function} Returns the new constant function.
 * @example
 *
 * var objects = _.times(2, _.constant({ 'a': 1 }));
 *
 * console.log(objects);
 * // => [{ 'a': 1 }, { 'a': 1 }]
 *
 * console.log(objects[0] === objects[1]);
 * // => true
 */
function constant(value) {
  return function () {
    return value;
  };
}

module.exports = constant;

/***/ }),
/* 359 */
/***/ (function(module, exports, __webpack_require__) {

var eq = __webpack_require__(46),
    isArrayLike = __webpack_require__(25),
    isIndex = __webpack_require__(33),
    isObject = __webpack_require__(16);
/**
 * Checks if the given arguments are from an iteratee call.
 *
 * @private
 * @param {*} value The potential iteratee value argument.
 * @param {*} index The potential iteratee index or key argument.
 * @param {*} object The potential iteratee object argument.
 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
 *  else `false`.
 */


function isIterateeCall(value, index, object) {
  if (!isObject(object)) {
    return false;
  }

  var type = typeof index;

  if (type == 'number' ? isArrayLike(object) && isIndex(index, object.length) : type == 'string' && index in object) {
    return eq(object[index], value);
  }

  return false;
}

module.exports = isIterateeCall;

/***/ }),
/* 360 */
/***/ (function(module, exports, __webpack_require__) {

var isObject = __webpack_require__(16),
    isPrototype = __webpack_require__(101),
    nativeKeysIn = __webpack_require__(361);
/** Used for built-in method references. */


var objectProto = Object.prototype;
/** Used to check objects for own properties. */

var hasOwnProperty = objectProto.hasOwnProperty;
/**
 * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */

function baseKeysIn(object) {
  if (!isObject(object)) {
    return nativeKeysIn(object);
  }

  var isProto = isPrototype(object),
      result = [];

  for (var key in object) {
    if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
      result.push(key);
    }
  }

  return result;
}

module.exports = baseKeysIn;

/***/ }),
/* 361 */
/***/ (function(module, exports) {

/**
 * This function is like
 * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * except that it includes inherited enumerable properties.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function nativeKeysIn(object) {
  var result = [];

  if (object != null) {
    for (var key in Object(object)) {
      result.push(key);
    }
  }

  return result;
}

module.exports = nativeKeysIn;

/***/ }),
/* 362 */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.findIndex` and `_.findLastIndex` without
 * support for iteratee shorthands.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {Function} predicate The function invoked per iteration.
 * @param {number} fromIndex The index to search from.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function baseFindIndex(array, predicate, fromIndex, fromRight) {
  var length = array.length,
      index = fromIndex + (fromRight ? 1 : -1);

  while (fromRight ? index-- : ++index < length) {
    if (predicate(array[index], index, array)) {
      return index;
    }
  }

  return -1;
}

module.exports = baseFindIndex;

/***/ }),
/* 363 */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.isNaN` without support for number objects.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
 */
function baseIsNaN(value) {
  return value !== value;
}

module.exports = baseIsNaN;

/***/ }),
/* 364 */
/***/ (function(module, exports) {

/**
 * A specialized version of `_.indexOf` which performs strict equality
 * comparisons of values, i.e. `===`.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function strictIndexOf(array, value, fromIndex) {
  var index = fromIndex - 1,
      length = array.length;

  while (++index < length) {
    if (array[index] === value) {
      return index;
    }
  }

  return -1;
}

module.exports = strictIndexOf;

/***/ }),
/* 365 */
/***/ (function(module, exports, __webpack_require__) {

var arrayMap = __webpack_require__(70);
/**
 * The base implementation of `_.values` and `_.valuesIn` which creates an
 * array of `object` property values corresponding to the property names
 * of `props`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array} props The property names to get values for.
 * @returns {Object} Returns the array of property values.
 */


function baseValues(object, props) {
  return arrayMap(props, function (key) {
    return object[key];
  });
}

module.exports = baseValues;

/***/ }),
/* 366 */
/***/ (function(module, exports, __webpack_require__) {

var baseSetData = __webpack_require__(113),
    createBind = __webpack_require__(367),
    createCurry = __webpack_require__(368),
    createHybrid = __webpack_require__(116),
    createPartial = __webpack_require__(381),
    getData = __webpack_require__(120),
    mergeData = __webpack_require__(382),
    setData = __webpack_require__(123),
    setWrapToString = __webpack_require__(124),
    toInteger = __webpack_require__(67);
/** Error message constants. */


var FUNC_ERROR_TEXT = 'Expected a function';
/** Used to compose bitmasks for function metadata. */

var WRAP_BIND_FLAG = 1,
    WRAP_BIND_KEY_FLAG = 2,
    WRAP_CURRY_FLAG = 8,
    WRAP_CURRY_RIGHT_FLAG = 16,
    WRAP_PARTIAL_FLAG = 32,
    WRAP_PARTIAL_RIGHT_FLAG = 64;
/* Built-in method references for those with the same name as other `lodash` methods. */

var nativeMax = Math.max;
/**
 * Creates a function that either curries or invokes `func` with optional
 * `this` binding and partially applied arguments.
 *
 * @private
 * @param {Function|string} func The function or method name to wrap.
 * @param {number} bitmask The bitmask flags.
 *    1 - `_.bind`
 *    2 - `_.bindKey`
 *    4 - `_.curry` or `_.curryRight` of a bound function
 *    8 - `_.curry`
 *   16 - `_.curryRight`
 *   32 - `_.partial`
 *   64 - `_.partialRight`
 *  128 - `_.rearg`
 *  256 - `_.ary`
 *  512 - `_.flip`
 * @param {*} [thisArg] The `this` binding of `func`.
 * @param {Array} [partials] The arguments to be partially applied.
 * @param {Array} [holders] The `partials` placeholder indexes.
 * @param {Array} [argPos] The argument positions of the new function.
 * @param {number} [ary] The arity cap of `func`.
 * @param {number} [arity] The arity of `func`.
 * @returns {Function} Returns the new wrapped function.
 */

function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
  var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;

  if (!isBindKey && typeof func != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }

  var length = partials ? partials.length : 0;

  if (!length) {
    bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
    partials = holders = undefined;
  }

  ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
  arity = arity === undefined ? arity : toInteger(arity);
  length -= holders ? holders.length : 0;

  if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
    var partialsRight = partials,
        holdersRight = holders;
    partials = holders = undefined;
  }

  var data = isBindKey ? undefined : getData(func);
  var newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];

  if (data) {
    mergeData(newData, data);
  }

  func = newData[0];
  bitmask = newData[1];
  thisArg = newData[2];
  partials = newData[3];
  holders = newData[4];
  arity = newData[9] = newData[9] === undefined ? isBindKey ? 0 : func.length : nativeMax(newData[9] - length, 0);

  if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
    bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
  }

  if (!bitmask || bitmask == WRAP_BIND_FLAG) {
    var result = createBind(func, bitmask, thisArg);
  } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
    result = createCurry(func, bitmask, arity);
  } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
    result = createPartial(func, bitmask, thisArg, partials);
  } else {
    result = createHybrid.apply(undefined, newData);
  }

  var setter = data ? baseSetData : setData;
  return setWrapToString(setter(result, newData), func, bitmask);
}

module.exports = createWrap;

/***/ }),
/* 367 */
/***/ (function(module, exports, __webpack_require__) {

var createCtor = __webpack_require__(47),
    root = __webpack_require__(9);
/** Used to compose bitmasks for function metadata. */


var WRAP_BIND_FLAG = 1;
/**
 * Creates a function that wraps `func` to invoke it with the optional `this`
 * binding of `thisArg`.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @param {*} [thisArg] The `this` binding of `func`.
 * @returns {Function} Returns the new wrapped function.
 */

function createBind(func, bitmask, thisArg) {
  var isBind = bitmask & WRAP_BIND_FLAG,
      Ctor = createCtor(func);

  function wrapper() {
    var fn = this && this !== root && this instanceof wrapper ? Ctor : func;
    return fn.apply(isBind ? thisArg : this, arguments);
  }

  return wrapper;
}

module.exports = createBind;

/***/ }),
/* 368 */
/***/ (function(module, exports, __webpack_require__) {

var apply = __webpack_require__(69),
    createCtor = __webpack_require__(47),
    createHybrid = __webpack_require__(116),
    createRecurry = __webpack_require__(119),
    getHolder = __webpack_require__(74),
    replaceHolders = __webpack_require__(48),
    root = __webpack_require__(9);
/**
 * Creates a function that wraps `func` to enable currying.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @param {number} arity The arity of `func`.
 * @returns {Function} Returns the new wrapped function.
 */


function createCurry(func, bitmask, arity) {
  var Ctor = createCtor(func);

  function wrapper() {
    var length = arguments.length,
        args = Array(length),
        index = length,
        placeholder = getHolder(wrapper);

    while (index--) {
      args[index] = arguments[index];
    }

    var holders = length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder ? [] : replaceHolders(args, placeholder);
    length -= holders.length;

    if (length < arity) {
      return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length);
    }

    var fn = this && this !== root && this instanceof wrapper ? Ctor : func;
    return apply(fn, this, args);
  }

  return wrapper;
}

module.exports = createCurry;

/***/ }),
/* 369 */
/***/ (function(module, exports) {

/**
 * Gets the number of `placeholder` occurrences in `array`.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} placeholder The placeholder to search for.
 * @returns {number} Returns the placeholder count.
 */
function countHolders(array, placeholder) {
  var length = array.length,
      result = 0;

  while (length--) {
    if (array[length] === placeholder) {
      ++result;
    }
  }

  return result;
}

module.exports = countHolders;

/***/ }),
/* 370 */
/***/ (function(module, exports, __webpack_require__) {

var LazyWrapper = __webpack_require__(72),
    getData = __webpack_require__(120),
    getFuncName = __webpack_require__(372),
    lodash = __webpack_require__(374);
/**
 * Checks if `func` has a lazy counterpart.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
 *  else `false`.
 */


function isLaziable(func) {
  var funcName = getFuncName(func),
      other = lodash[funcName];

  if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
    return false;
  }

  if (func === other) {
    return true;
  }

  var data = getData(other);
  return !!data && func === data[0];
}

module.exports = isLaziable;

/***/ }),
/* 371 */
/***/ (function(module, exports) {

/**
 * This method returns `undefined`.
 *
 * @static
 * @memberOf _
 * @since 2.3.0
 * @category Util
 * @example
 *
 * _.times(2, _.noop);
 * // => [undefined, undefined]
 */
function noop() {// No operation performed.
}

module.exports = noop;

/***/ }),
/* 372 */
/***/ (function(module, exports, __webpack_require__) {

var realNames = __webpack_require__(373);
/** Used for built-in method references. */


var objectProto = Object.prototype;
/** Used to check objects for own properties. */

var hasOwnProperty = objectProto.hasOwnProperty;
/**
 * Gets the name of `func`.
 *
 * @private
 * @param {Function} func The function to query.
 * @returns {string} Returns the function name.
 */

function getFuncName(func) {
  var result = func.name + '',
      array = realNames[result],
      length = hasOwnProperty.call(realNames, result) ? array.length : 0;

  while (length--) {
    var data = array[length],
        otherFunc = data.func;

    if (otherFunc == null || otherFunc == func) {
      return data.name;
    }
  }

  return result;
}

module.exports = getFuncName;

/***/ }),
/* 373 */
/***/ (function(module, exports) {

/** Used to lookup unminified function names. */
var realNames = {};
module.exports = realNames;

/***/ }),
/* 374 */
/***/ (function(module, exports, __webpack_require__) {

var LazyWrapper = __webpack_require__(72),
    LodashWrapper = __webpack_require__(121),
    baseLodash = __webpack_require__(73),
    isArray = __webpack_require__(12),
    isObjectLike = __webpack_require__(19),
    wrapperClone = __webpack_require__(375);
/** Used for built-in method references. */


var objectProto = Object.prototype;
/** Used to check objects for own properties. */

var hasOwnProperty = objectProto.hasOwnProperty;
/**
 * Creates a `lodash` object which wraps `value` to enable implicit method
 * chain sequences. Methods that operate on and return arrays, collections,
 * and functions can be chained together. Methods that retrieve a single value
 * or may return a primitive value will automatically end the chain sequence
 * and return the unwrapped value. Otherwise, the value must be unwrapped
 * with `_#value`.
 *
 * Explicit chain sequences, which must be unwrapped with `_#value`, may be
 * enabled using `_.chain`.
 *
 * The execution of chained methods is lazy, that is, it's deferred until
 * `_#value` is implicitly or explicitly called.
 *
 * Lazy evaluation allows several methods to support shortcut fusion.
 * Shortcut fusion is an optimization to merge iteratee calls; this avoids
 * the creation of intermediate arrays and can greatly reduce the number of
 * iteratee executions. Sections of a chain sequence qualify for shortcut
 * fusion if the section is applied to an array and iteratees accept only
 * one argument. The heuristic for whether a section qualifies for shortcut
 * fusion is subject to change.
 *
 * Chaining is supported in custom builds as long as the `_#value` method is
 * directly or indirectly included in the build.
 *
 * In addition to lodash methods, wrappers have `Array` and `String` methods.
 *
 * The wrapper `Array` methods are:
 * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
 *
 * The wrapper `String` methods are:
 * `replace` and `split`
 *
 * The wrapper methods that support shortcut fusion are:
 * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
 * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
 * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
 *
 * The chainable wrapper methods are:
 * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
 * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
 * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
 * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
 * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
 * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
 * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
 * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
 * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
 * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
 * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
 * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
 * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
 * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
 * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
 * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
 * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
 * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
 * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
 * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
 * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
 * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
 * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
 * `zipObject`, `zipObjectDeep`, and `zipWith`
 *
 * The wrapper methods that are **not** chainable by default are:
 * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
 * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
 * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
 * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
 * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
 * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
 * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
 * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
 * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
 * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
 * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
 * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
 * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
 * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
 * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
 * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
 * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
 * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
 * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
 * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
 * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
 * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
 * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
 * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
 * `upperFirst`, `value`, and `words`
 *
 * @name _
 * @constructor
 * @category Seq
 * @param {*} value The value to wrap in a `lodash` instance.
 * @returns {Object} Returns the new `lodash` wrapper instance.
 * @example
 *
 * function square(n) {
 *   return n * n;
 * }
 *
 * var wrapped = _([1, 2, 3]);
 *
 * // Returns an unwrapped value.
 * wrapped.reduce(_.add);
 * // => 6
 *
 * // Returns a wrapped value.
 * var squares = wrapped.map(square);
 *
 * _.isArray(squares);
 * // => false
 *
 * _.isArray(squares.value());
 * // => true
 */

function lodash(value) {
  if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
    if (value instanceof LodashWrapper) {
      return value;
    }

    if (hasOwnProperty.call(value, '__wrapped__')) {
      return wrapperClone(value);
    }
  }

  return new LodashWrapper(value);
} // Ensure wrappers are instances of `baseLodash`.


lodash.prototype = baseLodash.prototype;
lodash.prototype.constructor = lodash;
module.exports = lodash;

/***/ }),
/* 375 */
/***/ (function(module, exports, __webpack_require__) {

var LazyWrapper = __webpack_require__(72),
    LodashWrapper = __webpack_require__(121),
    copyArray = __webpack_require__(122);
/**
 * Creates a clone of `wrapper`.
 *
 * @private
 * @param {Object} wrapper The wrapper to clone.
 * @returns {Object} Returns the cloned wrapper.
 */


function wrapperClone(wrapper) {
  if (wrapper instanceof LazyWrapper) {
    return wrapper.clone();
  }

  var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
  result.__actions__ = copyArray(wrapper.__actions__);
  result.__index__ = wrapper.__index__;
  result.__values__ = wrapper.__values__;
  return result;
}

module.exports = wrapperClone;

/***/ }),
/* 376 */
/***/ (function(module, exports) {

/** Used to match wrap detail comments. */
var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
    reSplitDetails = /,? & /;
/**
 * Extracts wrapper details from the `source` body comment.
 *
 * @private
 * @param {string} source The source to inspect.
 * @returns {Array} Returns the wrapper details.
 */

function getWrapDetails(source) {
  var match = source.match(reWrapDetails);
  return match ? match[1].split(reSplitDetails) : [];
}

module.exports = getWrapDetails;

/***/ }),
/* 377 */
/***/ (function(module, exports) {

/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
/**
 * Inserts wrapper `details` in a comment at the top of the `source` body.
 *
 * @private
 * @param {string} source The source to modify.
 * @returns {Array} details The details to insert.
 * @returns {string} Returns the modified source.
 */

function insertWrapDetails(source, details) {
  var length = details.length;

  if (!length) {
    return source;
  }

  var lastIndex = length - 1;
  details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
  details = details.join(length > 2 ? ', ' : ' ');
  return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}

module.exports = insertWrapDetails;

/***/ }),
/* 378 */
/***/ (function(module, exports, __webpack_require__) {

var arrayEach = __webpack_require__(95),
    arrayIncludes = __webpack_require__(379);
/** Used to compose bitmasks for function metadata. */


var WRAP_BIND_FLAG = 1,
    WRAP_BIND_KEY_FLAG = 2,
    WRAP_CURRY_FLAG = 8,
    WRAP_CURRY_RIGHT_FLAG = 16,
    WRAP_PARTIAL_FLAG = 32,
    WRAP_PARTIAL_RIGHT_FLAG = 64,
    WRAP_ARY_FLAG = 128,
    WRAP_REARG_FLAG = 256,
    WRAP_FLIP_FLAG = 512;
/** Used to associate wrap methods with their bit flags. */

var wrapFlags = [['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG]];
/**
 * Updates wrapper `details` based on `bitmask` flags.
 *
 * @private
 * @returns {Array} details The details to modify.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @returns {Array} Returns `details`.
 */

function updateWrapDetails(details, bitmask) {
  arrayEach(wrapFlags, function (pair) {
    var value = '_.' + pair[0];

    if (bitmask & pair[1] && !arrayIncludes(details, value)) {
      details.push(value);
    }
  });
  return details.sort();
}

module.exports = updateWrapDetails;

/***/ }),
/* 379 */
/***/ (function(module, exports, __webpack_require__) {

var baseIndexOf = __webpack_require__(111);
/**
 * A specialized version of `_.includes` for arrays without support for
 * specifying an index to search from.
 *
 * @private
 * @param {Array} [array] The array to inspect.
 * @param {*} target The value to search for.
 * @returns {boolean} Returns `true` if `target` is found, else `false`.
 */


function arrayIncludes(array, value) {
  var length = array == null ? 0 : array.length;
  return !!length && baseIndexOf(array, value, 0) > -1;
}

module.exports = arrayIncludes;

/***/ }),
/* 380 */
/***/ (function(module, exports, __webpack_require__) {

var copyArray = __webpack_require__(122),
    isIndex = __webpack_require__(33);
/* Built-in method references for those with the same name as other `lodash` methods. */


var nativeMin = Math.min;
/**
 * Reorder `array` according to the specified indexes where the element at
 * the first index is assigned as the first element, the element at
 * the second index is assigned as the second element, and so on.
 *
 * @private
 * @param {Array} array The array to reorder.
 * @param {Array} indexes The arranged array indexes.
 * @returns {Array} Returns `array`.
 */

function reorder(array, indexes) {
  var arrLength = array.length,
      length = nativeMin(indexes.length, arrLength),
      oldArray = copyArray(array);

  while (length--) {
    var index = indexes[length];
    array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
  }

  return array;
}

module.exports = reorder;

/***/ }),
/* 381 */
/***/ (function(module, exports, __webpack_require__) {

var apply = __webpack_require__(69),
    createCtor = __webpack_require__(47),
    root = __webpack_require__(9);
/** Used to compose bitmasks for function metadata. */


var WRAP_BIND_FLAG = 1;
/**
 * Creates a function that wraps `func` to invoke it with the `this` binding
 * of `thisArg` and `partials` prepended to the arguments it receives.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @param {*} thisArg The `this` binding of `func`.
 * @param {Array} partials The arguments to prepend to those provided to
 *  the new function.
 * @returns {Function} Returns the new wrapped function.
 */

function createPartial(func, bitmask, thisArg, partials) {
  var isBind = bitmask & WRAP_BIND_FLAG,
      Ctor = createCtor(func);

  function wrapper() {
    var argsIndex = -1,
        argsLength = arguments.length,
        leftIndex = -1,
        leftLength = partials.length,
        args = Array(leftLength + argsLength),
        fn = this && this !== root && this instanceof wrapper ? Ctor : func;

    while (++leftIndex < leftLength) {
      args[leftIndex] = partials[leftIndex];
    }

    while (argsLength--) {
      args[leftIndex++] = arguments[++argsIndex];
    }

    return apply(fn, isBind ? thisArg : this, args);
  }

  return wrapper;
}

module.exports = createPartial;

/***/ }),
/* 382 */
/***/ (function(module, exports, __webpack_require__) {

var composeArgs = __webpack_require__(117),
    composeArgsRight = __webpack_require__(118),
    replaceHolders = __webpack_require__(48);
/** Used as the internal argument placeholder. */


var PLACEHOLDER = '__lodash_placeholder__';
/** Used to compose bitmasks for function metadata. */

var WRAP_BIND_FLAG = 1,
    WRAP_BIND_KEY_FLAG = 2,
    WRAP_CURRY_BOUND_FLAG = 4,
    WRAP_CURRY_FLAG = 8,
    WRAP_ARY_FLAG = 128,
    WRAP_REARG_FLAG = 256;
/* Built-in method references for those with the same name as other `lodash` methods. */

var nativeMin = Math.min;
/**
 * Merges the function metadata of `source` into `data`.
 *
 * Merging metadata reduces the number of wrappers used to invoke a function.
 * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
 * may be applied regardless of execution order. Methods like `_.ary` and
 * `_.rearg` modify function arguments, making the order in which they are
 * executed important, preventing the merging of metadata. However, we make
 * an exception for a safe combined case where curried functions have `_.ary`
 * and or `_.rearg` applied.
 *
 * @private
 * @param {Array} data The destination metadata.
 * @param {Array} source The source metadata.
 * @returns {Array} Returns `data`.
 */

function mergeData(data, source) {
  var bitmask = data[1],
      srcBitmask = source[1],
      newBitmask = bitmask | srcBitmask,
      isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
  var isCombo = srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_CURRY_FLAG || srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_REARG_FLAG && data[7].length <= source[8] || srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG) && source[7].length <= source[8] && bitmask == WRAP_CURRY_FLAG; // Exit early if metadata can't be merged.

  if (!(isCommon || isCombo)) {
    return data;
  } // Use source `thisArg` if available.


  if (srcBitmask & WRAP_BIND_FLAG) {
    data[2] = source[2]; // Set when currying a bound function.

    newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
  } // Compose partial arguments.


  var value = source[3];

  if (value) {
    var partials = data[3];
    data[3] = partials ? composeArgs(partials, value, source[4]) : value;
    data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
  } // Compose partial right arguments.


  value = source[5];

  if (value) {
    partials = data[5];
    data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
    data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
  } // Use source `argPos` if available.


  value = source[7];

  if (value) {
    data[7] = value;
  } // Use source `ary` if it's smaller.


  if (srcBitmask & WRAP_ARY_FLAG) {
    data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
  } // Use source `arity` if one is not provided.


  if (data[9] == null) {
    data[9] = source[9];
  } // Use source `func` and merge bitmasks.


  data[0] = source[0];
  data[1] = newBitmask;
  return data;
}

module.exports = mergeData;

/***/ }),
/* 383 */
/***/ (function(module, exports, __webpack_require__) {

var baseMatches = __webpack_require__(384),
    baseMatchesProperty = __webpack_require__(425),
    identity = __webpack_require__(34),
    isArray = __webpack_require__(12),
    property = __webpack_require__(434);
/**
 * The base implementation of `_.iteratee`.
 *
 * @private
 * @param {*} [value=_.identity] The value to convert to an iteratee.
 * @returns {Function} Returns the iteratee.
 */


function baseIteratee(value) {
  // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  if (typeof value == 'function') {
    return value;
  }

  if (value == null) {
    return identity;
  }

  if (typeof value == 'object') {
    return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value);
  }

  return property(value);
}

module.exports = baseIteratee;

/***/ }),
/* 384 */
/***/ (function(module, exports, __webpack_require__) {

var baseIsMatch = __webpack_require__(385),
    getMatchData = __webpack_require__(424),
    matchesStrictComparable = __webpack_require__(134);
/**
 * The base implementation of `_.matches` which doesn't clone `source`.
 *
 * @private
 * @param {Object} source The object of property values to match.
 * @returns {Function} Returns the new spec function.
 */


function baseMatches(source) {
  var matchData = getMatchData(source);

  if (matchData.length == 1 && matchData[0][2]) {
    return matchesStrictComparable(matchData[0][0], matchData[0][1]);
  }

  return function (object) {
    return object === source || baseIsMatch(object, source, matchData);
  };
}

module.exports = baseMatches;

/***/ }),
/* 385 */
/***/ (function(module, exports, __webpack_require__) {

var Stack = __webpack_require__(125),
    baseIsEqual = __webpack_require__(126);
/** Used to compose bitmasks for value comparisons. */


var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;
/**
 * The base implementation of `_.isMatch` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The object to inspect.
 * @param {Object} source The object of property values to match.
 * @param {Array} matchData The property names, values, and compare flags to match.
 * @param {Function} [customizer] The function to customize comparisons.
 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
 */

function baseIsMatch(object, source, matchData, customizer) {
  var index = matchData.length,
      length = index,
      noCustomizer = !customizer;

  if (object == null) {
    return !length;
  }

  object = Object(object);

  while (index--) {
    var data = matchData[index];

    if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
      return false;
    }
  }

  while (++index < length) {
    data = matchData[index];
    var key = data[0],
        objValue = object[key],
        srcValue = data[1];

    if (noCustomizer && data[2]) {
      if (objValue === undefined && !(key in object)) {
        return false;
      }
    } else {
      var stack = new Stack();

      if (customizer) {
        var result = customizer(objValue, srcValue, key, object, source, stack);
      }

      if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result)) {
        return false;
      }
    }
  }

  return true;
}

module.exports = baseIsMatch;

/***/ }),
/* 386 */
/***/ (function(module, exports) {

/**
 * Removes all key-value entries from the list cache.
 *
 * @private
 * @name clear
 * @memberOf ListCache
 */
function listCacheClear() {
  this.__data__ = [];
  this.size = 0;
}

module.exports = listCacheClear;

/***/ }),
/* 387 */
/***/ (function(module, exports, __webpack_require__) {

var assocIndexOf = __webpack_require__(50);
/** Used for built-in method references. */


var arrayProto = Array.prototype;
/** Built-in value references. */

var splice = arrayProto.splice;
/**
 * Removes `key` and its value from the list cache.
 *
 * @private
 * @name delete
 * @memberOf ListCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */

function listCacheDelete(key) {
  var data = this.__data__,
      index = assocIndexOf(data, key);

  if (index < 0) {
    return false;
  }

  var lastIndex = data.length - 1;

  if (index == lastIndex) {
    data.pop();
  } else {
    splice.call(data, index, 1);
  }

  --this.size;
  return true;
}

module.exports = listCacheDelete;

/***/ }),
/* 388 */
/***/ (function(module, exports, __webpack_require__) {

var assocIndexOf = __webpack_require__(50);
/**
 * Gets the list cache value for `key`.
 *
 * @private
 * @name get
 * @memberOf ListCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */


function listCacheGet(key) {
  var data = this.__data__,
      index = assocIndexOf(data, key);
  return index < 0 ? undefined : data[index][1];
}

module.exports = listCacheGet;

/***/ }),
/* 389 */
/***/ (function(module, exports, __webpack_require__) {

var assocIndexOf = __webpack_require__(50);
/**
 * Checks if a list cache value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf ListCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */


function listCacheHas(key) {
  return assocIndexOf(this.__data__, key) > -1;
}

module.exports = listCacheHas;

/***/ }),
/* 390 */
/***/ (function(module, exports, __webpack_require__) {

var assocIndexOf = __webpack_require__(50);
/**
 * Sets the list cache `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf ListCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the list cache instance.
 */


function listCacheSet(key, value) {
  var data = this.__data__,
      index = assocIndexOf(data, key);

  if (index < 0) {
    ++this.size;
    data.push([key, value]);
  } else {
    data[index][1] = value;
  }

  return this;
}

module.exports = listCacheSet;

/***/ }),
/* 391 */
/***/ (function(module, exports, __webpack_require__) {

var ListCache = __webpack_require__(49);
/**
 * Removes all key-value entries from the stack.
 *
 * @private
 * @name clear
 * @memberOf Stack
 */


function stackClear() {
  this.__data__ = new ListCache();
  this.size = 0;
}

module.exports = stackClear;

/***/ }),
/* 392 */
/***/ (function(module, exports) {

/**
 * Removes `key` and its value from the stack.
 *
 * @private
 * @name delete
 * @memberOf Stack
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function stackDelete(key) {
  var data = this.__data__,
      result = data['delete'](key);
  this.size = data.size;
  return result;
}

module.exports = stackDelete;

/***/ }),
/* 393 */
/***/ (function(module, exports) {

/**
 * Gets the stack value for `key`.
 *
 * @private
 * @name get
 * @memberOf Stack
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function stackGet(key) {
  return this.__data__.get(key);
}

module.exports = stackGet;

/***/ }),
/* 394 */
/***/ (function(module, exports) {

/**
 * Checks if a stack value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Stack
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function stackHas(key) {
  return this.__data__.has(key);
}

module.exports = stackHas;

/***/ }),
/* 395 */
/***/ (function(module, exports, __webpack_require__) {

var ListCache = __webpack_require__(49),
    Map = __webpack_require__(75),
    MapCache = __webpack_require__(76);
/** Used as the size to enable large array optimizations. */


var LARGE_ARRAY_SIZE = 200;
/**
 * Sets the stack `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Stack
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the stack cache instance.
 */

function stackSet(key, value) {
  var data = this.__data__;

  if (data instanceof ListCache) {
    var pairs = data.__data__;

    if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
      pairs.push([key, value]);
      this.size = ++data.size;
      return this;
    }

    data = this.__data__ = new MapCache(pairs);
  }

  data.set(key, value);
  this.size = data.size;
  return this;
}

module.exports = stackSet;

/***/ }),
/* 396 */
/***/ (function(module, exports, __webpack_require__) {

var Hash = __webpack_require__(397),
    ListCache = __webpack_require__(49),
    Map = __webpack_require__(75);
/**
 * Removes all key-value entries from the map.
 *
 * @private
 * @name clear
 * @memberOf MapCache
 */


function mapCacheClear() {
  this.size = 0;
  this.__data__ = {
    'hash': new Hash(),
    'map': new (Map || ListCache)(),
    'string': new Hash()
  };
}

module.exports = mapCacheClear;

/***/ }),
/* 397 */
/***/ (function(module, exports, __webpack_require__) {

var hashClear = __webpack_require__(398),
    hashDelete = __webpack_require__(399),
    hashGet = __webpack_require__(400),
    hashHas = __webpack_require__(401),
    hashSet = __webpack_require__(402);
/**
 * Creates a hash object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */


function Hash(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;
  this.clear();

  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
} // Add methods to `Hash`.


Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
module.exports = Hash;

/***/ }),
/* 398 */
/***/ (function(module, exports, __webpack_require__) {

var nativeCreate = __webpack_require__(51);
/**
 * Removes all key-value entries from the hash.
 *
 * @private
 * @name clear
 * @memberOf Hash
 */


function hashClear() {
  this.__data__ = nativeCreate ? nativeCreate(null) : {};
  this.size = 0;
}

module.exports = hashClear;

/***/ }),
/* 399 */
/***/ (function(module, exports) {

/**
 * Removes `key` and its value from the hash.
 *
 * @private
 * @name delete
 * @memberOf Hash
 * @param {Object} hash The hash to modify.
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function hashDelete(key) {
  var result = this.has(key) && delete this.__data__[key];
  this.size -= result ? 1 : 0;
  return result;
}

module.exports = hashDelete;

/***/ }),
/* 400 */
/***/ (function(module, exports, __webpack_require__) {

var nativeCreate = __webpack_require__(51);
/** Used to stand-in for `undefined` hash values. */


var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */

var objectProto = Object.prototype;
/** Used to check objects for own properties. */

var hasOwnProperty = objectProto.hasOwnProperty;
/**
 * Gets the hash value for `key`.
 *
 * @private
 * @name get
 * @memberOf Hash
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */

function hashGet(key) {
  var data = this.__data__;

  if (nativeCreate) {
    var result = data[key];
    return result === HASH_UNDEFINED ? undefined : result;
  }

  return hasOwnProperty.call(data, key) ? data[key] : undefined;
}

module.exports = hashGet;

/***/ }),
/* 401 */
/***/ (function(module, exports, __webpack_require__) {

var nativeCreate = __webpack_require__(51);
/** Used for built-in method references. */


var objectProto = Object.prototype;
/** Used to check objects for own properties. */

var hasOwnProperty = objectProto.hasOwnProperty;
/**
 * Checks if a hash value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Hash
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */

function hashHas(key) {
  var data = this.__data__;
  return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
}

module.exports = hashHas;

/***/ }),
/* 402 */
/***/ (function(module, exports, __webpack_require__) {

var nativeCreate = __webpack_require__(51);
/** Used to stand-in for `undefined` hash values. */


var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
 * Sets the hash `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Hash
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the hash instance.
 */

function hashSet(key, value) {
  var data = this.__data__;
  this.size += this.has(key) ? 0 : 1;
  data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value;
  return this;
}

module.exports = hashSet;

/***/ }),
/* 403 */
/***/ (function(module, exports, __webpack_require__) {

var getMapData = __webpack_require__(52);
/**
 * Removes `key` and its value from the map.
 *
 * @private
 * @name delete
 * @memberOf MapCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */


function mapCacheDelete(key) {
  var result = getMapData(this, key)['delete'](key);
  this.size -= result ? 1 : 0;
  return result;
}

module.exports = mapCacheDelete;

/***/ }),
/* 404 */
/***/ (function(module, exports) {

/**
 * Checks if `value` is suitable for use as unique object key.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
 */
function isKeyable(value) {
  var type = typeof value;
  return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
}

module.exports = isKeyable;

/***/ }),
/* 405 */
/***/ (function(module, exports, __webpack_require__) {

var getMapData = __webpack_require__(52);
/**
 * Gets the map value for `key`.
 *
 * @private
 * @name get
 * @memberOf MapCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */


function mapCacheGet(key) {
  return getMapData(this, key).get(key);
}

module.exports = mapCacheGet;

/***/ }),
/* 406 */
/***/ (function(module, exports, __webpack_require__) {

var getMapData = __webpack_require__(52);
/**
 * Checks if a map value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf MapCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */


function mapCacheHas(key) {
  return getMapData(this, key).has(key);
}

module.exports = mapCacheHas;

/***/ }),
/* 407 */
/***/ (function(module, exports, __webpack_require__) {

var getMapData = __webpack_require__(52);
/**
 * Sets the map `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf MapCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the map cache instance.
 */


function mapCacheSet(key, value) {
  var data = getMapData(this, key),
      size = data.size;
  data.set(key, value);
  this.size += data.size == size ? 0 : 1;
  return this;
}

module.exports = mapCacheSet;

/***/ }),
/* 408 */
/***/ (function(module, exports, __webpack_require__) {

var Stack = __webpack_require__(125),
    equalArrays = __webpack_require__(127),
    equalByTag = __webpack_require__(414),
    equalObjects = __webpack_require__(418),
    getTag = __webpack_require__(132),
    isArray = __webpack_require__(12),
    isBuffer = __webpack_require__(98),
    isTypedArray = __webpack_require__(99);
/** Used to compose bitmasks for value comparisons. */


var COMPARE_PARTIAL_FLAG = 1;
/** `Object#toString` result references. */

var argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    objectTag = '[object Object]';
/** Used for built-in method references. */

var objectProto = Object.prototype;
/** Used to check objects for own properties. */

var hasOwnProperty = objectProto.hasOwnProperty;
/**
 * A specialized version of `baseIsEqual` for arrays and objects which performs
 * deep comparisons and tracks traversed objects enabling objects with circular
 * references to be compared.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */

function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  var objIsArr = isArray(object),
      othIsArr = isArray(other),
      objTag = objIsArr ? arrayTag : getTag(object),
      othTag = othIsArr ? arrayTag : getTag(other);
  objTag = objTag == argsTag ? objectTag : objTag;
  othTag = othTag == argsTag ? objectTag : othTag;
  var objIsObj = objTag == objectTag,
      othIsObj = othTag == objectTag,
      isSameTag = objTag == othTag;

  if (isSameTag && isBuffer(object)) {
    if (!isBuffer(other)) {
      return false;
    }

    objIsArr = true;
    objIsObj = false;
  }

  if (isSameTag && !objIsObj) {
    stack || (stack = new Stack());
    return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  }

  if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
    var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
        othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');

    if (objIsWrapped || othIsWrapped) {
      var objUnwrapped = objIsWrapped ? object.value() : object,
          othUnwrapped = othIsWrapped ? other.value() : other;
      stack || (stack = new Stack());
      return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
    }
  }

  if (!isSameTag) {
    return false;
  }

  stack || (stack = new Stack());
  return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}

module.exports = baseIsEqualDeep;

/***/ }),
/* 409 */
/***/ (function(module, exports, __webpack_require__) {

var MapCache = __webpack_require__(76),
    setCacheAdd = __webpack_require__(410),
    setCacheHas = __webpack_require__(411);
/**
 *
 * Creates an array cache object to store unique values.
 *
 * @private
 * @constructor
 * @param {Array} [values] The values to cache.
 */


function SetCache(values) {
  var index = -1,
      length = values == null ? 0 : values.length;
  this.__data__ = new MapCache();

  while (++index < length) {
    this.add(values[index]);
  }
} // Add methods to `SetCache`.


SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
module.exports = SetCache;

/***/ }),
/* 410 */
/***/ (function(module, exports) {

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
 * Adds `value` to the array cache.
 *
 * @private
 * @name add
 * @memberOf SetCache
 * @alias push
 * @param {*} value The value to cache.
 * @returns {Object} Returns the cache instance.
 */

function setCacheAdd(value) {
  this.__data__.set(value, HASH_UNDEFINED);

  return this;
}

module.exports = setCacheAdd;

/***/ }),
/* 411 */
/***/ (function(module, exports) {

/**
 * Checks if `value` is in the array cache.
 *
 * @private
 * @name has
 * @memberOf SetCache
 * @param {*} value The value to search for.
 * @returns {number} Returns `true` if `value` is found, else `false`.
 */
function setCacheHas(value) {
  return this.__data__.has(value);
}

module.exports = setCacheHas;

/***/ }),
/* 412 */
/***/ (function(module, exports) {

/**
 * A specialized version of `_.some` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if any element passes the predicate check,
 *  else `false`.
 */
function arraySome(array, predicate) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    if (predicate(array[index], index, array)) {
      return true;
    }
  }

  return false;
}

module.exports = arraySome;

/***/ }),
/* 413 */
/***/ (function(module, exports) {

/**
 * Checks if a `cache` value for `key` exists.
 *
 * @private
 * @param {Object} cache The cache to query.
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function cacheHas(cache, key) {
  return cache.has(key);
}

module.exports = cacheHas;

/***/ }),
/* 414 */
/***/ (function(module, exports, __webpack_require__) {

var Symbol = __webpack_require__(45),
    Uint8Array = __webpack_require__(415),
    eq = __webpack_require__(46),
    equalArrays = __webpack_require__(127),
    mapToArray = __webpack_require__(416),
    setToArray = __webpack_require__(417);
/** Used to compose bitmasks for value comparisons. */


var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;
/** `Object#toString` result references. */

var boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
    dataViewTag = '[object DataView]';
/** Used to convert symbols to primitives and strings. */

var symbolProto = Symbol ? Symbol.prototype : undefined,
    symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
 * A specialized version of `baseIsEqualDeep` for comparing objects of
 * the same `toStringTag`.
 *
 * **Note:** This function only supports comparing values with tags of
 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {string} tag The `toStringTag` of the objects to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */

function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  switch (tag) {
    case dataViewTag:
      if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
        return false;
      }

      object = object.buffer;
      other = other.buffer;

    case arrayBufferTag:
      if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
        return false;
      }

      return true;

    case boolTag:
    case dateTag:
    case numberTag:
      // Coerce booleans to `1` or `0` and dates to milliseconds.
      // Invalid dates are coerced to `NaN`.
      return eq(+object, +other);

    case errorTag:
      return object.name == other.name && object.message == other.message;

    case regexpTag:
    case stringTag:
      // Coerce regexes to strings and treat strings, primitives and objects,
      // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
      // for more details.
      return object == other + '';

    case mapTag:
      var convert = mapToArray;

    case setTag:
      var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
      convert || (convert = setToArray);

      if (object.size != other.size && !isPartial) {
        return false;
      } // Assume cyclic values are equal.


      var stacked = stack.get(object);

      if (stacked) {
        return stacked == other;
      }

      bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits).

      stack.set(object, other);
      var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
      stack['delete'](object);
      return result;

    case symbolTag:
      if (symbolValueOf) {
        return symbolValueOf.call(object) == symbolValueOf.call(other);
      }

  }

  return false;
}

module.exports = equalByTag;

/***/ }),
/* 415 */
/***/ (function(module, exports, __webpack_require__) {

var root = __webpack_require__(9);
/** Built-in value references. */


var Uint8Array = root.Uint8Array;
module.exports = Uint8Array;

/***/ }),
/* 416 */
/***/ (function(module, exports) {

/**
 * Converts `map` to its key-value pairs.
 *
 * @private
 * @param {Object} map The map to convert.
 * @returns {Array} Returns the key-value pairs.
 */
function mapToArray(map) {
  var index = -1,
      result = Array(map.size);
  map.forEach(function (value, key) {
    result[++index] = [key, value];
  });
  return result;
}

module.exports = mapToArray;

/***/ }),
/* 417 */
/***/ (function(module, exports) {

/**
 * Converts `set` to an array of its values.
 *
 * @private
 * @param {Object} set The set to convert.
 * @returns {Array} Returns the values.
 */
function setToArray(set) {
  var index = -1,
      result = Array(set.size);
  set.forEach(function (value) {
    result[++index] = value;
  });
  return result;
}

module.exports = setToArray;

/***/ }),
/* 418 */
/***/ (function(module, exports, __webpack_require__) {

var getAllKeys = __webpack_require__(419);
/** Used to compose bitmasks for value comparisons. */


var COMPARE_PARTIAL_FLAG = 1;
/** Used for built-in method references. */

var objectProto = Object.prototype;
/** Used to check objects for own properties. */

var hasOwnProperty = objectProto.hasOwnProperty;
/**
 * A specialized version of `baseIsEqualDeep` for objects with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */

function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
      objProps = getAllKeys(object),
      objLength = objProps.length,
      othProps = getAllKeys(other),
      othLength = othProps.length;

  if (objLength != othLength && !isPartial) {
    return false;
  }

  var index = objLength;

  while (index--) {
    var key = objProps[index];

    if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
      return false;
    }
  } // Check that cyclic values are equal.


  var objStacked = stack.get(object);
  var othStacked = stack.get(other);

  if (objStacked && othStacked) {
    return objStacked == other && othStacked == object;
  }

  var result = true;
  stack.set(object, other);
  stack.set(other, object);
  var skipCtor = isPartial;

  while (++index < objLength) {
    key = objProps[index];
    var objValue = object[key],
        othValue = other[key];

    if (customizer) {
      var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
    } // Recursively compare objects (susceptible to call stack limits).


    if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
      result = false;
      break;
    }

    skipCtor || (skipCtor = key == 'constructor');
  }

  if (result && !skipCtor) {
    var objCtor = object.constructor,
        othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal.

    if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
      result = false;
    }
  }

  stack['delete'](object);
  stack['delete'](other);
  return result;
}

module.exports = equalObjects;

/***/ }),
/* 419 */
/***/ (function(module, exports, __webpack_require__) {

var baseGetAllKeys = __webpack_require__(128),
    getSymbols = __webpack_require__(130),
    keys = __webpack_require__(29);
/**
 * Creates an array of own enumerable property names and symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */


function getAllKeys(object) {
  return baseGetAllKeys(object, keys, getSymbols);
}

module.exports = getAllKeys;

/***/ }),
/* 420 */
/***/ (function(module, exports) {

/**
 * A specialized version of `_.filter` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 */
function arrayFilter(array, predicate) {
  var index = -1,
      length = array == null ? 0 : array.length,
      resIndex = 0,
      result = [];

  while (++index < length) {
    var value = array[index];

    if (predicate(value, index, array)) {
      result[resIndex++] = value;
    }
  }

  return result;
}

module.exports = arrayFilter;

/***/ }),
/* 421 */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(21),
    root = __webpack_require__(9);
/* Built-in method references that are verified to be native. */


var DataView = getNative(root, 'DataView');
module.exports = DataView;

/***/ }),
/* 422 */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(21),
    root = __webpack_require__(9);
/* Built-in method references that are verified to be native. */


var Promise = getNative(root, 'Promise');
module.exports = Promise;

/***/ }),
/* 423 */
/***/ (function(module, exports, __webpack_require__) {

var getNative = __webpack_require__(21),
    root = __webpack_require__(9);
/* Built-in method references that are verified to be native. */


var Set = getNative(root, 'Set');
module.exports = Set;

/***/ }),
/* 424 */
/***/ (function(module, exports, __webpack_require__) {

var isStrictComparable = __webpack_require__(133),
    keys = __webpack_require__(29);
/**
 * Gets the property names, values, and compare flags of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the match data of `object`.
 */


function getMatchData(object) {
  var result = keys(object),
      length = result.length;

  while (length--) {
    var key = result[length],
        value = object[key];
    result[length] = [key, value, isStrictComparable(value)];
  }

  return result;
}

module.exports = getMatchData;

/***/ }),
/* 425 */
/***/ (function(module, exports, __webpack_require__) {

var baseIsEqual = __webpack_require__(126),
    get = __webpack_require__(426),
    hasIn = __webpack_require__(431),
    isKey = __webpack_require__(78),
    isStrictComparable = __webpack_require__(133),
    matchesStrictComparable = __webpack_require__(134),
    toKey = __webpack_require__(35);
/** Used to compose bitmasks for value comparisons. */


var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;
/**
 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
 *
 * @private
 * @param {string} path The path of the property to get.
 * @param {*} srcValue The value to match.
 * @returns {Function} Returns the new spec function.
 */

function baseMatchesProperty(path, srcValue) {
  if (isKey(path) && isStrictComparable(srcValue)) {
    return matchesStrictComparable(toKey(path), srcValue);
  }

  return function (object) {
    var objValue = get(object, path);
    return objValue === undefined && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
  };
}

module.exports = baseMatchesProperty;

/***/ }),
/* 426 */
/***/ (function(module, exports, __webpack_require__) {

var baseGet = __webpack_require__(77);
/**
 * Gets the value at `path` of `object`. If the resolved value is
 * `undefined`, the `defaultValue` is returned in its place.
 *
 * @static
 * @memberOf _
 * @since 3.7.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
 * @returns {*} Returns the resolved value.
 * @example
 *
 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
 *
 * _.get(object, 'a[0].b.c');
 * // => 3
 *
 * _.get(object, ['a', '0', 'b', 'c']);
 * // => 3
 *
 * _.get(object, 'a.b.c', 'default');
 * // => 'default'
 */


function get(object, path, defaultValue) {
  var result = object == null ? undefined : baseGet(object, path);
  return result === undefined ? defaultValue : result;
}

module.exports = get;

/***/ }),
/* 427 */
/***/ (function(module, exports, __webpack_require__) {

var memoizeCapped = __webpack_require__(428);
/** Used to match property names within property paths. */


var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */

var reEscapeChar = /\\(\\)?/g;
/**
 * Converts `string` to a property path array.
 *
 * @private
 * @param {string} string The string to convert.
 * @returns {Array} Returns the property path array.
 */

var stringToPath = memoizeCapped(function (string) {
  var result = [];

  if (string.charCodeAt(0) === 46
  /* . */
  ) {
      result.push('');
    }

  string.replace(rePropName, function (match, number, quote, subString) {
    result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
  });
  return result;
});
module.exports = stringToPath;

/***/ }),
/* 428 */
/***/ (function(module, exports, __webpack_require__) {

var memoize = __webpack_require__(429);
/** Used as the maximum memoize cache size. */


var MAX_MEMOIZE_SIZE = 500;
/**
 * A specialized version of `_.memoize` which clears the memoized function's
 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
 *
 * @private
 * @param {Function} func The function to have its output memoized.
 * @returns {Function} Returns the new memoized function.
 */

function memoizeCapped(func) {
  var result = memoize(func, function (key) {
    if (cache.size === MAX_MEMOIZE_SIZE) {
      cache.clear();
    }

    return key;
  });
  var cache = result.cache;
  return result;
}

module.exports = memoizeCapped;

/***/ }),
/* 429 */
/***/ (function(module, exports, __webpack_require__) {

var MapCache = __webpack_require__(76);
/** Error message constants. */


var FUNC_ERROR_TEXT = 'Expected a function';
/**
 * Creates a function that memoizes the result of `func`. If `resolver` is
 * provided, it determines the cache key for storing the result based on the
 * arguments provided to the memoized function. By default, the first argument
 * provided to the memoized function is used as the map cache key. The `func`
 * is invoked with the `this` binding of the memoized function.
 *
 * **Note:** The cache is exposed as the `cache` property on the memoized
 * function. Its creation may be customized by replacing the `_.memoize.Cache`
 * constructor with one whose instances implement the
 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to have its output memoized.
 * @param {Function} [resolver] The function to resolve the cache key.
 * @returns {Function} Returns the new memoized function.
 * @example
 *
 * var object = { 'a': 1, 'b': 2 };
 * var other = { 'c': 3, 'd': 4 };
 *
 * var values = _.memoize(_.values);
 * values(object);
 * // => [1, 2]
 *
 * values(other);
 * // => [3, 4]
 *
 * object.a = 2;
 * values(object);
 * // => [1, 2]
 *
 * // Modify the result cache.
 * values.cache.set(object, ['a', 'b']);
 * values(object);
 * // => ['a', 'b']
 *
 * // Replace `_.memoize.Cache`.
 * _.memoize.Cache = WeakMap;
 */

function memoize(func, resolver) {
  if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }

  var memoized = function () {
    var args = arguments,
        key = resolver ? resolver.apply(this, args) : args[0],
        cache = memoized.cache;

    if (cache.has(key)) {
      return cache.get(key);
    }

    var result = func.apply(this, args);
    memoized.cache = cache.set(key, result) || cache;
    return result;
  };

  memoized.cache = new (memoize.Cache || MapCache)();
  return memoized;
} // Expose `MapCache`.


memoize.Cache = MapCache;
module.exports = memoize;

/***/ }),
/* 430 */
/***/ (function(module, exports, __webpack_require__) {

var Symbol = __webpack_require__(45),
    arrayMap = __webpack_require__(70),
    isArray = __webpack_require__(12),
    isSymbol = __webpack_require__(44);
/** Used as references for various `Number` constants. */


var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */

var symbolProto = Symbol ? Symbol.prototype : undefined,
    symbolToString = symbolProto ? symbolProto.toString : undefined;
/**
 * The base implementation of `_.toString` which doesn't convert nullish
 * values to empty strings.
 *
 * @private
 * @param {*} value The value to process.
 * @returns {string} Returns the string.
 */

function baseToString(value) {
  // Exit early for strings to avoid a performance hit in some environments.
  if (typeof value == 'string') {
    return value;
  }

  if (isArray(value)) {
    // Recursively convert values (susceptible to call stack limits).
    return arrayMap(value, baseToString) + '';
  }

  if (isSymbol(value)) {
    return symbolToString ? symbolToString.call(value) : '';
  }

  var result = value + '';
  return result == '0' && 1 / value == -INFINITY ? '-0' : result;
}

module.exports = baseToString;

/***/ }),
/* 431 */
/***/ (function(module, exports, __webpack_require__) {

var baseHasIn = __webpack_require__(432),
    hasPath = __webpack_require__(433);
/**
 * Checks if `path` is a direct or inherited property of `object`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 * @example
 *
 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
 *
 * _.hasIn(object, 'a');
 * // => true
 *
 * _.hasIn(object, 'a.b');
 * // => true
 *
 * _.hasIn(object, ['a', 'b']);
 * // => true
 *
 * _.hasIn(object, 'b');
 * // => false
 */


function hasIn(object, path) {
  return object != null && hasPath(object, path, baseHasIn);
}

module.exports = hasIn;

/***/ }),
/* 432 */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.hasIn` without support for deep paths.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {Array|string} key The key to check.
 * @returns {boolean} Returns `true` if `key` exists, else `false`.
 */
function baseHasIn(object, key) {
  return object != null && key in Object(object);
}

module.exports = baseHasIn;

/***/ }),
/* 433 */
/***/ (function(module, exports, __webpack_require__) {

var castPath = __webpack_require__(53),
    isArguments = __webpack_require__(97),
    isArray = __webpack_require__(12),
    isIndex = __webpack_require__(33),
    isLength = __webpack_require__(68),
    toKey = __webpack_require__(35);
/**
 * Checks if `path` exists on `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @param {Function} hasFunc The function to check properties.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 */


function hasPath(object, path, hasFunc) {
  path = castPath(path, object);
  var index = -1,
      length = path.length,
      result = false;

  while (++index < length) {
    var key = toKey(path[index]);

    if (!(result = object != null && hasFunc(object, key))) {
      break;
    }

    object = object[key];
  }

  if (result || ++index != length) {
    return result;
  }

  length = object == null ? 0 : object.length;
  return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object));
}

module.exports = hasPath;

/***/ }),
/* 434 */
/***/ (function(module, exports, __webpack_require__) {

var baseProperty = __webpack_require__(136),
    basePropertyDeep = __webpack_require__(435),
    isKey = __webpack_require__(78),
    toKey = __webpack_require__(35);
/**
 * Creates a function that returns the value at `path` of a given object.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Util
 * @param {Array|string} path The path of the property to get.
 * @returns {Function} Returns the new accessor function.
 * @example
 *
 * var objects = [
 *   { 'a': { 'b': 2 } },
 *   { 'a': { 'b': 1 } }
 * ];
 *
 * _.map(objects, _.property('a.b'));
 * // => [2, 1]
 *
 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
 * // => [1, 2]
 */


function property(path) {
  return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}

module.exports = property;

/***/ }),
/* 435 */
/***/ (function(module, exports, __webpack_require__) {

var baseGet = __webpack_require__(77);
/**
 * A specialized version of `baseProperty` which supports deep paths.
 *
 * @private
 * @param {Array|string} path The path of the property to get.
 * @returns {Function} Returns the new accessor function.
 */


function basePropertyDeep(path) {
  return function (object) {
    return baseGet(object, path);
  };
}

module.exports = basePropertyDeep;

/***/ }),
/* 436 */
/***/ (function(module, exports, __webpack_require__) {

var baseGet = __webpack_require__(77),
    baseSet = __webpack_require__(437),
    castPath = __webpack_require__(53);
/**
 * The base implementation of  `_.pickBy` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The source object.
 * @param {string[]} paths The property paths to pick.
 * @param {Function} predicate The function invoked per property.
 * @returns {Object} Returns the new object.
 */


function basePickBy(object, paths, predicate) {
  var index = -1,
      length = paths.length,
      result = {};

  while (++index < length) {
    var path = paths[index],
        value = baseGet(object, path);

    if (predicate(value, path)) {
      baseSet(result, castPath(path, object), value);
    }
  }

  return result;
}

module.exports = basePickBy;

/***/ }),
/* 437 */
/***/ (function(module, exports, __webpack_require__) {

var assignValue = __webpack_require__(103),
    castPath = __webpack_require__(53),
    isIndex = __webpack_require__(33),
    isObject = __webpack_require__(16),
    toKey = __webpack_require__(35);
/**
 * The base implementation of `_.set`.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {Array|string} path The path of the property to set.
 * @param {*} value The value to set.
 * @param {Function} [customizer] The function to customize path creation.
 * @returns {Object} Returns `object`.
 */


function baseSet(object, path, value, customizer) {
  if (!isObject(object)) {
    return object;
  }

  path = castPath(path, object);
  var index = -1,
      length = path.length,
      lastIndex = length - 1,
      nested = object;

  while (nested != null && ++index < length) {
    var key = toKey(path[index]),
        newValue = value;

    if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
      return object;
    }

    if (index != lastIndex) {
      var objValue = nested[key];
      newValue = customizer ? customizer(objValue, key, nested) : undefined;

      if (newValue === undefined) {
        newValue = isObject(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {};
      }
    }

    assignValue(nested, key, newValue);
    nested = nested[key];
  }

  return object;
}

module.exports = baseSet;

/***/ }),
/* 438 */
/***/ (function(module, exports, __webpack_require__) {

var baseGetAllKeys = __webpack_require__(128),
    getSymbolsIn = __webpack_require__(439),
    keysIn = __webpack_require__(110);
/**
 * Creates an array of own and inherited enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */


function getAllKeysIn(object) {
  return baseGetAllKeys(object, keysIn, getSymbolsIn);
}

module.exports = getAllKeysIn;

/***/ }),
/* 439 */
/***/ (function(module, exports, __webpack_require__) {

var arrayPush = __webpack_require__(129),
    getPrototype = __webpack_require__(440),
    getSymbols = __webpack_require__(130),
    stubArray = __webpack_require__(131);
/* Built-in method references for those with the same name as other `lodash` methods. */


var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
 * Creates an array of the own and inherited enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */

var getSymbolsIn = !nativeGetSymbols ? stubArray : function (object) {
  var result = [];

  while (object) {
    arrayPush(result, getSymbols(object));
    object = getPrototype(object);
  }

  return result;
};
module.exports = getSymbolsIn;

/***/ }),
/* 440 */
/***/ (function(module, exports, __webpack_require__) {

var overArg = __webpack_require__(102);
/** Built-in value references. */


var getPrototype = overArg(Object.getPrototypeOf, Object);
module.exports = getPrototype;

/***/ }),
/* 441 */
/***/ (function(module, exports, __webpack_require__) {

var asciiSize = __webpack_require__(442),
    hasUnicode = __webpack_require__(443),
    unicodeSize = __webpack_require__(444);
/**
 * Gets the number of symbols in `string`.
 *
 * @private
 * @param {string} string The string to inspect.
 * @returns {number} Returns the string size.
 */


function stringSize(string) {
  return hasUnicode(string) ? unicodeSize(string) : asciiSize(string);
}

module.exports = stringSize;

/***/ }),
/* 442 */
/***/ (function(module, exports, __webpack_require__) {

var baseProperty = __webpack_require__(136);
/**
 * Gets the size of an ASCII `string`.
 *
 * @private
 * @param {string} string The string inspect.
 * @returns {number} Returns the string size.
 */


var asciiSize = baseProperty('length');
module.exports = asciiSize;

/***/ }),
/* 443 */
/***/ (function(module, exports) {

/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
    rsComboMarksRange = '\\u0300-\\u036f',
    reComboHalfMarksRange = '\\ufe20-\\ufe2f',
    rsComboSymbolsRange = '\\u20d0-\\u20ff',
    rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
    rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */

var rsZWJ = '\\u200d';
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */

var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
/**
 * Checks if `string` contains Unicode symbols.
 *
 * @private
 * @param {string} string The string to inspect.
 * @returns {boolean} Returns `true` if a symbol is found, else `false`.
 */

function hasUnicode(string) {
  return reHasUnicode.test(string);
}

module.exports = hasUnicode;

/***/ }),
/* 444 */
/***/ (function(module, exports) {

/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
    rsComboMarksRange = '\\u0300-\\u036f',
    reComboHalfMarksRange = '\\ufe20-\\ufe2f',
    rsComboSymbolsRange = '\\u20d0-\\u20ff',
    rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
    rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */

var rsAstral = '[' + rsAstralRange + ']',
    rsCombo = '[' + rsComboRange + ']',
    rsFitz = '\\ud83c[\\udffb-\\udfff]',
    rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
    rsNonAstral = '[^' + rsAstralRange + ']',
    rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
    rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
    rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */

var reOptMod = rsModifier + '?',
    rsOptVar = '[' + rsVarRange + ']?',
    rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
    rsSeq = rsOptVar + reOptMod + rsOptJoin,
    rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */

var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/**
 * Gets the size of a Unicode `string`.
 *
 * @private
 * @param {string} string The string inspect.
 * @returns {number} Returns the string size.
 */

function unicodeSize(string) {
  var result = reUnicode.lastIndex = 0;

  while (reUnicode.test(string)) {
    ++result;
  }

  return result;
}

module.exports = unicodeSize;

/***/ }),
/* 445 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _defineProperty = __webpack_require__(446);

var _defineProperty2 = _interopRequireDefault(_defineProperty);

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {
    default: obj
  };
}

exports.default = function (obj, key, value) {
  if (key in obj) {
    (0, _defineProperty2.default)(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
};

/***/ }),
/* 446 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = {
  "default": __webpack_require__(447),
  __esModule: true
};

/***/ }),
/* 447 */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(448);

var $Object = __webpack_require__(15).Object;

module.exports = function defineProperty(it, key, desc) {
  return $Object.defineProperty(it, key, desc);
};

/***/ }),
/* 448 */
/***/ (function(module, exports, __webpack_require__) {

var $export = __webpack_require__(26); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)


$export($export.S + $export.F * !__webpack_require__(28), 'Object', {
  defineProperty: __webpack_require__(36).f
});

/***/ }),
/* 449 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = !__webpack_require__(28) && !__webpack_require__(79)(function () {
  return Object.defineProperty(__webpack_require__(80)('div'), 'a', {
    get: function () {
      return 7;
    }
  }).a != 7;
});

/***/ }),
/* 450 */
/***/ (function(module, exports, __webpack_require__) {

// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(37); // instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string


module.exports = function (it, S) {
  if (!isObject(it)) return it;
  var fn, val;
  if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
  if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
  if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
  throw TypeError("Can't convert object to primitive value");
};

/***/ }),
/* 451 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = {
  "default": __webpack_require__(452),
  __esModule: true
};

/***/ }),
/* 452 */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(453);

module.exports = __webpack_require__(15).Object.keys;

/***/ }),
/* 453 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(139);

var $keys = __webpack_require__(140);

__webpack_require__(458)('keys', function () {
  return function keys(it) {
    return $keys(toObject(it));
  };
});

/***/ }),
/* 454 */
/***/ (function(module, exports, __webpack_require__) {

var has = __webpack_require__(56);

var toIObject = __webpack_require__(82);

var arrayIndexOf = __webpack_require__(456)(false);

var IE_PROTO = __webpack_require__(84)('IE_PROTO');

module.exports = function (object, names) {
  var O = toIObject(object);
  var i = 0;
  var result = [];
  var key;

  for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); // Don't enum bug & hidden keys


  while (names.length > i) if (has(O, key = names[i++])) {
    ~arrayIndexOf(result, key) || result.push(key);
  }

  return result;
};

/***/ }),
/* 455 */
/***/ (function(module, exports, __webpack_require__) {

// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(57); // eslint-disable-next-line no-prototype-builtins


module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
  return cof(it) == 'String' ? it.split('') : Object(it);
};

/***/ }),
/* 456 */
/***/ (function(module, exports, __webpack_require__) {

// false -> Array#indexOf
// true  -> Array#includes
var toIObject = __webpack_require__(82);

var toLength = __webpack_require__(141);

var toAbsoluteIndex = __webpack_require__(457);

module.exports = function (IS_INCLUDES) {
  return function ($this, el, fromIndex) {
    var O = toIObject($this);
    var length = toLength(O.length);
    var index = toAbsoluteIndex(fromIndex, length);
    var value; // Array#includes uses SameValueZero equality algorithm
    // eslint-disable-next-line no-self-compare

    if (IS_INCLUDES && el != el) while (length > index) {
      value = O[index++]; // eslint-disable-next-line no-self-compare

      if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not
    } else for (; length > index; index++) if (IS_INCLUDES || index in O) {
      if (O[index] === el) return IS_INCLUDES || index || 0;
    }
    return !IS_INCLUDES && -1;
  };
};

/***/ }),
/* 457 */
/***/ (function(module, exports, __webpack_require__) {

var toInteger = __webpack_require__(83);

var max = Math.max;
var min = Math.min;

module.exports = function (index, length) {
  index = toInteger(index);
  return index < 0 ? max(index + length, 0) : min(index, length);
};

/***/ }),
/* 458 */
/***/ (function(module, exports, __webpack_require__) {

// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(26);

var core = __webpack_require__(15);

var fails = __webpack_require__(79);

module.exports = function (KEY, exec) {
  var fn = (core.Object || {})[KEY] || Object[KEY];
  var exp = {};
  exp[KEY] = exec(fn);
  $export($export.S + $export.F * fails(function () {
    fn(1);
  }), 'Object', exp);
};

/***/ }),
/* 459 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(460);

/***/ }),
/* 460 */
/***/ (function(module, exports, __webpack_require__) {

/**
 * Copyright (c) 2014-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
// This method of obtaining a reference to the global object needs to be
// kept identical to the way it is obtained in runtime.js
var g = function () {
  return this;
}() || Function("return this")(); // Use `getOwnPropertyNames` because not all browsers support calling
// `hasOwnProperty` on the global `self` object in a worker. See #183.


var hadRuntime = g.regeneratorRuntime && Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0; // Save the old regeneratorRuntime in case it needs to be restored later.

var oldRuntime = hadRuntime && g.regeneratorRuntime; // Force reevalutation of runtime.js.

g.regeneratorRuntime = undefined;
module.exports = __webpack_require__(461);

if (hadRuntime) {
  // Restore the original runtime.
  g.regeneratorRuntime = oldRuntime;
} else {
  // Remove the global property added by runtime.js.
  try {
    delete g.regeneratorRuntime;
  } catch (e) {
    g.regeneratorRuntime = undefined;
  }
}

/***/ }),
/* 461 */
/***/ (function(module, exports) {

/**
 * Copyright (c) 2014-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
!function (global) {
  "use strict";

  var Op = Object.prototype;
  var hasOwn = Op.hasOwnProperty;
  var undefined; // More compressible than void 0.

  var $Symbol = typeof Symbol === "function" ? Symbol : {};
  var iteratorSymbol = $Symbol.iterator || "@@iterator";
  var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  var inModule = typeof module === "object";
  var runtime = global.regeneratorRuntime;

  if (runtime) {
    if (inModule) {
      // If regeneratorRuntime is defined globally and we're in a module,
      // make the exports object identical to regeneratorRuntime.
      module.exports = runtime;
    } // Don't bother evaluating the rest of this file if the runtime was
    // already defined globally.


    return;
  } // Define the runtime globally (as expected by generated code) as either
  // module.exports (if we're in a module) or a new, empty object.


  runtime = global.regeneratorRuntime = inModule ? module.exports : {};

  function wrap(innerFn, outerFn, self, tryLocsList) {
    // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
    var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
    var generator = Object.create(protoGenerator.prototype);
    var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next,
    // .throw, and .return methods.

    generator._invoke = makeInvokeMethod(innerFn, self, context);
    return generator;
  }

  runtime.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion
  // record like context.tryEntries[i].completion. This interface could
  // have been (and was previously) designed to take a closure to be
  // invoked without arguments, but in all the cases we care about we
  // already have an existing method we want to call, so there's no need
  // to create a new function object. We can even get away with assuming
  // the method takes exactly one argument, since that happens to be true
  // in every case, so we don't have to touch the arguments object. The
  // only additional allocation required is the completion record, which
  // has a stable shape and so hopefully should be cheap to allocate.

  function tryCatch(fn, obj, arg) {
    try {
      return {
        type: "normal",
        arg: fn.call(obj, arg)
      };
    } catch (err) {
      return {
        type: "throw",
        arg: err
      };
    }
  }

  var GenStateSuspendedStart = "suspendedStart";
  var GenStateSuspendedYield = "suspendedYield";
  var GenStateExecuting = "executing";
  var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as
  // breaking out of the dispatch switch statement.

  var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and
  // .constructor.prototype properties for functions that return Generator
  // objects. For full spec compliance, you may wish to configure your
  // minifier not to mangle the names of these two functions.

  function Generator() {}

  function GeneratorFunction() {}

  function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that
  // don't natively support it.


  var IteratorPrototype = {};

  IteratorPrototype[iteratorSymbol] = function () {
    return this;
  };

  var getProto = Object.getPrototypeOf;
  var NativeIteratorPrototype = getProto && getProto(getProto(values([])));

  if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
    // This environment has a native %IteratorPrototype%; use it instead
    // of the polyfill.
    IteratorPrototype = NativeIteratorPrototype;
  }

  var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
  GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  GeneratorFunctionPrototype.constructor = GeneratorFunction;
  GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the
  // Iterator interface in terms of a single ._invoke method.

  function defineIteratorMethods(prototype) {
    ["next", "throw", "return"].forEach(function (method) {
      prototype[method] = function (arg) {
        return this._invoke(method, arg);
      };
    });
  }

  runtime.isGeneratorFunction = function (genFun) {
    var ctor = typeof genFun === "function" && genFun.constructor;
    return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can
    // do is to check its .name property.
    (ctor.displayName || ctor.name) === "GeneratorFunction" : false;
  };

  runtime.mark = function (genFun) {
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
    } else {
      genFun.__proto__ = GeneratorFunctionPrototype;

      if (!(toStringTagSymbol in genFun)) {
        genFun[toStringTagSymbol] = "GeneratorFunction";
      }
    }

    genFun.prototype = Object.create(Gp);
    return genFun;
  }; // Within the body of any async function, `await x` is transformed to
  // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  // `hasOwn.call(value, "__await")` to determine if the yielded value is
  // meant to be awaited.


  runtime.awrap = function (arg) {
    return {
      __await: arg
    };
  };

  function AsyncIterator(generator) {
    function invoke(method, arg, resolve, reject) {
      var record = tryCatch(generator[method], generator, arg);

      if (record.type === "throw") {
        reject(record.arg);
      } else {
        var result = record.arg;
        var value = result.value;

        if (value && typeof value === "object" && hasOwn.call(value, "__await")) {
          return Promise.resolve(value.__await).then(function (value) {
            invoke("next", value, resolve, reject);
          }, function (err) {
            invoke("throw", err, resolve, reject);
          });
        }

        return Promise.resolve(value).then(function (unwrapped) {
          // When a yielded Promise is resolved, its final value becomes
          // the .value of the Promise<{value,done}> result for the
          // current iteration. If the Promise is rejected, however, the
          // result for this iteration will be rejected with the same
          // reason. Note that rejections of yielded Promises are not
          // thrown back into the generator function, as is the case
          // when an awaited Promise is rejected. This difference in
          // behavior between yield and await is important, because it
          // allows the consumer to decide what to do with the yielded
          // rejection (swallow it and continue, manually .throw it back
          // into the generator, abandon iteration, whatever). With
          // await, by contrast, there is no opportunity to examine the
          // rejection reason outside the generator function, so the
          // only option is to throw it from the await expression, and
          // let the generator function handle the exception.
          result.value = unwrapped;
          resolve(result);
        }, reject);
      }
    }

    var previousPromise;

    function enqueue(method, arg) {
      function callInvokeWithMethodAndArg() {
        return new Promise(function (resolve, reject) {
          invoke(method, arg, resolve, reject);
        });
      }

      return previousPromise = // If enqueue has been called before, then we want to wait until
      // all previous Promises have been resolved before calling invoke,
      // so that results are always delivered in the correct order. If
      // enqueue has not been called before, then it is important to
      // call invoke immediately, without waiting on a callback to fire,
      // so that the async generator function has the opportunity to do
      // any necessary setup in a predictable way. This predictability
      // is why the Promise constructor synchronously invokes its
      // executor callback, and why async functions synchronously
      // execute code before the first await. Since we implement simple
      // async functions in terms of async generators, it is especially
      // important to get this right, even though it requires care.
      previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later
      // invocations of the iterator.
      callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
    } // Define the unified helper method that is used to implement .next,
    // .throw, and .return (see defineIteratorMethods).


    this._invoke = enqueue;
  }

  defineIteratorMethods(AsyncIterator.prototype);

  AsyncIterator.prototype[asyncIteratorSymbol] = function () {
    return this;
  };

  runtime.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of
  // AsyncIterator objects; they just return a Promise for the value of
  // the final result produced by the iterator.

  runtime.async = function (innerFn, outerFn, self, tryLocsList) {
    var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList));
    return runtime.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator.
    : iter.next().then(function (result) {
      return result.done ? result.value : iter.next();
    });
  };

  function makeInvokeMethod(innerFn, self, context) {
    var state = GenStateSuspendedStart;
    return function invoke(method, arg) {
      if (state === GenStateExecuting) {
        throw new Error("Generator is already running");
      }

      if (state === GenStateCompleted) {
        if (method === "throw") {
          throw arg;
        } // Be forgiving, per 25.3.3.3.3 of the spec:
        // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume


        return doneResult();
      }

      context.method = method;
      context.arg = arg;

      while (true) {
        var delegate = context.delegate;

        if (delegate) {
          var delegateResult = maybeInvokeDelegate(delegate, context);

          if (delegateResult) {
            if (delegateResult === ContinueSentinel) continue;
            return delegateResult;
          }
        }

        if (context.method === "next") {
          // Setting context._sent for legacy support of Babel's
          // function.sent implementation.
          context.sent = context._sent = context.arg;
        } else if (context.method === "throw") {
          if (state === GenStateSuspendedStart) {
            state = GenStateCompleted;
            throw context.arg;
          }

          context.dispatchException(context.arg);
        } else if (context.method === "return") {
          context.abrupt("return", context.arg);
        }

        state = GenStateExecuting;
        var record = tryCatch(innerFn, self, context);

        if (record.type === "normal") {
          // If an exception is thrown from innerFn, we leave state ===
          // GenStateExecuting and loop back for another invocation.
          state = context.done ? GenStateCompleted : GenStateSuspendedYield;

          if (record.arg === ContinueSentinel) {
            continue;
          }

          return {
            value: record.arg,
            done: context.done
          };
        } else if (record.type === "throw") {
          state = GenStateCompleted; // Dispatch the exception by looping back around to the
          // context.dispatchException(context.arg) call above.

          context.method = "throw";
          context.arg = record.arg;
        }
      }
    };
  } // Call delegate.iterator[context.method](context.arg) and handle the
  // result, either by returning a { value, done } result from the
  // delegate iterator, or by modifying context.method and context.arg,
  // setting context.delegate to null, and returning the ContinueSentinel.


  function maybeInvokeDelegate(delegate, context) {
    var method = delegate.iterator[context.method];

    if (method === undefined) {
      // A .throw or .return when the delegate iterator has no .throw
      // method always terminates the yield* loop.
      context.delegate = null;

      if (context.method === "throw") {
        if (delegate.iterator.return) {
          // If the delegate iterator has a return method, give it a
          // chance to clean up.
          context.method = "return";
          context.arg = undefined;
          maybeInvokeDelegate(delegate, context);

          if (context.method === "throw") {
            // If maybeInvokeDelegate(context) changed context.method from
            // "return" to "throw", let that override the TypeError below.
            return ContinueSentinel;
          }
        }

        context.method = "throw";
        context.arg = new TypeError("The iterator does not provide a 'throw' method");
      }

      return ContinueSentinel;
    }

    var record = tryCatch(method, delegate.iterator, context.arg);

    if (record.type === "throw") {
      context.method = "throw";
      context.arg = record.arg;
      context.delegate = null;
      return ContinueSentinel;
    }

    var info = record.arg;

    if (!info) {
      context.method = "throw";
      context.arg = new TypeError("iterator result is not an object");
      context.delegate = null;
      return ContinueSentinel;
    }

    if (info.done) {
      // Assign the result of the finished delegate to the temporary
      // variable specified by delegate.resultName (see delegateYield).
      context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield).

      context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the
      // exception, let the outer generator proceed normally. If
      // context.method was "next", forget context.arg since it has been
      // "consumed" by the delegate iterator. If context.method was
      // "return", allow the original .return call to continue in the
      // outer generator.

      if (context.method !== "return") {
        context.method = "next";
        context.arg = undefined;
      }
    } else {
      // Re-yield the result returned by the delegate method.
      return info;
    } // The delegate iterator is finished, so forget it and continue with
    // the outer generator.


    context.delegate = null;
    return ContinueSentinel;
  } // Define Generator.prototype.{next,throw,return} in terms of the
  // unified ._invoke helper method.


  defineIteratorMethods(Gp);
  Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the
  // @@iterator function is called on it. Some browsers' implementations of the
  // iterator prototype chain incorrectly implement this, causing the Generator
  // object to not be returned from this call. This ensures that doesn't happen.
  // See https://github.com/facebook/regenerator/issues/274 for more details.

  Gp[iteratorSymbol] = function () {
    return this;
  };

  Gp.toString = function () {
    return "[object Generator]";
  };

  function pushTryEntry(locs) {
    var entry = {
      tryLoc: locs[0]
    };

    if (1 in locs) {
      entry.catchLoc = locs[1];
    }

    if (2 in locs) {
      entry.finallyLoc = locs[2];
      entry.afterLoc = locs[3];
    }

    this.tryEntries.push(entry);
  }

  function resetTryEntry(entry) {
    var record = entry.completion || {};
    record.type = "normal";
    delete record.arg;
    entry.completion = record;
  }

  function Context(tryLocsList) {
    // The root entry object (effectively a try statement without a catch
    // or a finally block) gives us a place to store values thrown from
    // locations where there is no enclosing try statement.
    this.tryEntries = [{
      tryLoc: "root"
    }];
    tryLocsList.forEach(pushTryEntry, this);
    this.reset(true);
  }

  runtime.keys = function (object) {
    var keys = [];

    for (var key in object) {
      keys.push(key);
    }

    keys.reverse(); // Rather than returning an object with a next method, we keep
    // things simple and return the next function itself.

    return function next() {
      while (keys.length) {
        var key = keys.pop();

        if (key in object) {
          next.value = key;
          next.done = false;
          return next;
        }
      } // To avoid creating an additional object, we just hang the .value
      // and .done properties off the next function object itself. This
      // also ensures that the minifier will not anonymize the function.


      next.done = true;
      return next;
    };
  };

  function values(iterable) {
    if (iterable) {
      var iteratorMethod = iterable[iteratorSymbol];

      if (iteratorMethod) {
        return iteratorMethod.call(iterable);
      }

      if (typeof iterable.next === "function") {
        return iterable;
      }

      if (!isNaN(iterable.length)) {
        var i = -1,
            next = function next() {
          while (++i < iterable.length) {
            if (hasOwn.call(iterable, i)) {
              next.value = iterable[i];
              next.done = false;
              return next;
            }
          }

          next.value = undefined;
          next.done = true;
          return next;
        };

        return next.next = next;
      }
    } // Return an iterator with no values.


    return {
      next: doneResult
    };
  }

  runtime.values = values;

  function doneResult() {
    return {
      value: undefined,
      done: true
    };
  }

  Context.prototype = {
    constructor: Context,
    reset: function (skipTempReset) {
      this.prev = 0;
      this.next = 0; // Resetting context._sent for legacy support of Babel's
      // function.sent implementation.

      this.sent = this._sent = undefined;
      this.done = false;
      this.delegate = null;
      this.method = "next";
      this.arg = undefined;
      this.tryEntries.forEach(resetTryEntry);

      if (!skipTempReset) {
        for (var name in this) {
          // Not sure about the optimal order of these conditions:
          if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) {
            this[name] = undefined;
          }
        }
      }
    },
    stop: function () {
      this.done = true;
      var rootEntry = this.tryEntries[0];
      var rootRecord = rootEntry.completion;

      if (rootRecord.type === "throw") {
        throw rootRecord.arg;
      }

      return this.rval;
    },
    dispatchException: function (exception) {
      if (this.done) {
        throw exception;
      }

      var context = this;

      function handle(loc, caught) {
        record.type = "throw";
        record.arg = exception;
        context.next = loc;

        if (caught) {
          // If the dispatched exception was caught by a catch block,
          // then let that catch block handle the exception normally.
          context.method = "next";
          context.arg = undefined;
        }

        return !!caught;
      }

      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        var record = entry.completion;

        if (entry.tryLoc === "root") {
          // Exception thrown outside of any try block that could handle
          // it, so set the completion value of the entire function to
          // throw the exception.
          return handle("end");
        }

        if (entry.tryLoc <= this.prev) {
          var hasCatch = hasOwn.call(entry, "catchLoc");
          var hasFinally = hasOwn.call(entry, "finallyLoc");

          if (hasCatch && hasFinally) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            } else if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }
          } else if (hasCatch) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            }
          } else if (hasFinally) {
            if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }
          } else {
            throw new Error("try statement without catch or finally");
          }
        }
      }
    },
    abrupt: function (type, arg) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];

        if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
          var finallyEntry = entry;
          break;
        }
      }

      if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) {
        // Ignore the finally entry if control is not jumping to a
        // location outside the try/catch block.
        finallyEntry = null;
      }

      var record = finallyEntry ? finallyEntry.completion : {};
      record.type = type;
      record.arg = arg;

      if (finallyEntry) {
        this.method = "next";
        this.next = finallyEntry.finallyLoc;
        return ContinueSentinel;
      }

      return this.complete(record);
    },
    complete: function (record, afterLoc) {
      if (record.type === "throw") {
        throw record.arg;
      }

      if (record.type === "break" || record.type === "continue") {
        this.next = record.arg;
      } else if (record.type === "return") {
        this.rval = this.arg = record.arg;
        this.method = "return";
        this.next = "end";
      } else if (record.type === "normal" && afterLoc) {
        this.next = afterLoc;
      }

      return ContinueSentinel;
    },
    finish: function (finallyLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];

        if (entry.finallyLoc === finallyLoc) {
          this.complete(entry.completion, entry.afterLoc);
          resetTryEntry(entry);
          return ContinueSentinel;
        }
      }
    },
    "catch": function (tryLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];

        if (entry.tryLoc === tryLoc) {
          var record = entry.completion;

          if (record.type === "throw") {
            var thrown = record.arg;
            resetTryEntry(entry);
          }

          return thrown;
        }
      } // The context.catch method must only be called with a location
      // argument that corresponds to a known catch block.


      throw new Error("illegal catch attempt");
    },
    delegateYield: function (iterable, resultName, nextLoc) {
      this.delegate = {
        iterator: values(iterable),
        resultName: resultName,
        nextLoc: nextLoc
      };

      if (this.method === "next") {
        // Deliberately forget the last sent value so that we don't
        // accidentally pass it on to the delegate.
        this.arg = undefined;
      }

      return ContinueSentinel;
    }
  };
}( // In sloppy mode, unbound `this` refers to the global object, fallback to
// Function constructor if we're in global strict mode. That is sadly a form
// of indirect eval which violates Content Security Policy.
function () {
  return this;
}() || Function("return this")());

/***/ }),
/* 462 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

var _promise = __webpack_require__(86);

var _promise2 = _interopRequireDefault(_promise);

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {
    default: obj
  };
}

exports.default = function (fn) {
  return function () {
    var gen = fn.apply(this, arguments);
    return new _promise2.default(function (resolve, reject) {
      function step(key, arg) {
        try {
          var info = gen[key](arg);
          var value = info.value;
        } catch (error) {
          reject(error);
          return;
        }

        if (info.done) {
          resolve(value);
        } else {
          return _promise2.default.resolve(value).then(function (value) {
            step("next", value);
          }, function (err) {
            step("throw", err);
          });
        }
      }

      return step("next");
    });
  };
};

/***/ }),
/* 463 */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(464);

__webpack_require__(465);

__webpack_require__(472);

__webpack_require__(476);

__webpack_require__(488);

__webpack_require__(489);

module.exports = __webpack_require__(15).Promise;

/***/ }),
/* 464 */
/***/ (function(module, exports) {



/***/ }),
/* 465 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var $at = __webpack_require__(466)(true); // 21.1.3.27 String.prototype[@@iterator]()


__webpack_require__(145)(String, 'String', function (iterated) {
  this._t = String(iterated); // target

  this._i = 0; // next index
  // 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function () {
  var O = this._t;
  var index = this._i;
  var point;
  if (index >= O.length) return {
    value: undefined,
    done: true
  };
  point = $at(O, index);
  this._i += point.length;
  return {
    value: point,
    done: false
  };
});

/***/ }),
/* 466 */
/***/ (function(module, exports, __webpack_require__) {

var toInteger = __webpack_require__(83);

var defined = __webpack_require__(81); // true  -> String#at
// false -> String#codePointAt


module.exports = function (TO_STRING) {
  return function (that, pos) {
    var s = String(defined(that));
    var i = toInteger(pos);
    var l = s.length;
    var a, b;
    if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
    a = s.charCodeAt(i);
    return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
  };
};

/***/ }),
/* 467 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(27);

/***/ }),
/* 468 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var create = __webpack_require__(469);

var descriptor = __webpack_require__(138);

var setToStringTag = __webpack_require__(87);

var IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]()

__webpack_require__(27)(IteratorPrototype, __webpack_require__(13)('iterator'), function () {
  return this;
});

module.exports = function (Constructor, NAME, next) {
  Constructor.prototype = create(IteratorPrototype, {
    next: descriptor(1, next)
  });
  setToStringTag(Constructor, NAME + ' Iterator');
};

/***/ }),
/* 469 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(22);

var dPs = __webpack_require__(470);

var enumBugKeys = __webpack_require__(144);

var IE_PROTO = __webpack_require__(84)('IE_PROTO');

var Empty = function () {
  /* empty */
};

var PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype

var createDict = function () {
  // Thrash, waste and sodomy: IE GC bug
  var iframe = __webpack_require__(80)('iframe');

  var i = enumBugKeys.length;
  var lt = '<';
  var gt = '>';
  var iframeDocument;
  iframe.style.display = 'none';

  __webpack_require__(146).appendChild(iframe);

  iframe.src = 'javascript:'; // eslint-disable-line no-script-url
  // createDict = iframe.contentWindow.Object;
  // html.removeChild(iframe);

  iframeDocument = iframe.contentWindow.document;
  iframeDocument.open();
  iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
  iframeDocument.close();
  createDict = iframeDocument.F;

  while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];

  return createDict();
};

module.exports = Object.create || function create(O, Properties) {
  var result;

  if (O !== null) {
    Empty[PROTOTYPE] = anObject(O);
    result = new Empty();
    Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill

    result[IE_PROTO] = O;
  } else result = createDict();

  return Properties === undefined ? result : dPs(result, Properties);
};

/***/ }),
/* 470 */
/***/ (function(module, exports, __webpack_require__) {

var dP = __webpack_require__(36);

var anObject = __webpack_require__(22);

var getKeys = __webpack_require__(140);

module.exports = __webpack_require__(28) ? Object.defineProperties : function defineProperties(O, Properties) {
  anObject(O);
  var keys = getKeys(Properties);
  var length = keys.length;
  var i = 0;
  var P;

  while (length > i) dP.f(O, P = keys[i++], Properties[P]);

  return O;
};

/***/ }),
/* 471 */
/***/ (function(module, exports, __webpack_require__) {

// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__(56);

var toObject = __webpack_require__(139);

var IE_PROTO = __webpack_require__(84)('IE_PROTO');

var ObjectProto = Object.prototype;

module.exports = Object.getPrototypeOf || function (O) {
  O = toObject(O);
  if (has(O, IE_PROTO)) return O[IE_PROTO];

  if (typeof O.constructor == 'function' && O instanceof O.constructor) {
    return O.constructor.prototype;
  }

  return O instanceof Object ? ObjectProto : null;
};

/***/ }),
/* 472 */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(473);

var global = __webpack_require__(10);

var hide = __webpack_require__(27);

var Iterators = __webpack_require__(38);

var TO_STRING_TAG = __webpack_require__(13)('toStringTag');

var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' + 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' + 'TextTrackList,TouchList').split(',');

for (var i = 0; i < DOMIterables.length; i++) {
  var NAME = DOMIterables[i];
  var Collection = global[NAME];
  var proto = Collection && Collection.prototype;
  if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
  Iterators[NAME] = Iterators.Array;
}

/***/ }),
/* 473 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var addToUnscopables = __webpack_require__(474);

var step = __webpack_require__(475);

var Iterators = __webpack_require__(38);

var toIObject = __webpack_require__(82); // 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()


module.exports = __webpack_require__(145)(Array, 'Array', function (iterated, kind) {
  this._t = toIObject(iterated); // target

  this._i = 0; // next index

  this._k = kind; // kind
  // 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function () {
  var O = this._t;
  var kind = this._k;
  var index = this._i++;

  if (!O || index >= O.length) {
    this._t = undefined;
    return step(1);
  }

  if (kind == 'keys') return step(0, index);
  if (kind == 'values') return step(0, O[index]);
  return step(0, [index, O[index]]);
}, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)

Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');

/***/ }),
/* 474 */
/***/ (function(module, exports) {

module.exports = function () {
  /* empty */
};

/***/ }),
/* 475 */
/***/ (function(module, exports) {

module.exports = function (done, value) {
  return {
    value: value,
    done: !!done
  };
};

/***/ }),
/* 476 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var LIBRARY = __webpack_require__(85);

var global = __webpack_require__(10);

var ctx = __webpack_require__(54);

var classof = __webpack_require__(147);

var $export = __webpack_require__(26);

var isObject = __webpack_require__(37);

var aFunction = __webpack_require__(55);

var anInstance = __webpack_require__(477);

var forOf = __webpack_require__(478);

var speciesConstructor = __webpack_require__(148);

var task = __webpack_require__(149).set;

var microtask = __webpack_require__(483)();

var newPromiseCapabilityModule = __webpack_require__(88);

var perform = __webpack_require__(150);

var userAgent = __webpack_require__(484);

var promiseResolve = __webpack_require__(151);

var PROMISE = 'Promise';
var TypeError = global.TypeError;
var process = global.process;
var versions = process && process.versions;
var v8 = versions && versions.v8 || '';
var $Promise = global[PROMISE];
var isNode = classof(process) == 'process';

var empty = function () {
  /* empty */
};

var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;
var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f;
var USE_NATIVE = !!function () {
  try {
    // correct subclassing with @@species support
    var promise = $Promise.resolve(1);

    var FakePromise = (promise.constructor = {})[__webpack_require__(13)('species')] = function (exec) {
      exec(empty, empty);
    }; // unhandled rejections tracking support, NodeJS Promise without it fails @@species test


    return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
    // https://bugs.chromium.org/p/chromium/issues/detail?id=830565
    // we can't detect it synchronously, so just check versions
    && v8.indexOf('6.6') !== 0 && userAgent.indexOf('Chrome/66') === -1;
  } catch (e) {
    /* empty */
  }
}(); // helpers

var isThenable = function (it) {
  var then;
  return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};

var notify = function (promise, isReject) {
  if (promise._n) return;
  promise._n = true;
  var chain = promise._c;
  microtask(function () {
    var value = promise._v;
    var ok = promise._s == 1;
    var i = 0;

    var run = function (reaction) {
      var handler = ok ? reaction.ok : reaction.fail;
      var resolve = reaction.resolve;
      var reject = reaction.reject;
      var domain = reaction.domain;
      var result, then, exited;

      try {
        if (handler) {
          if (!ok) {
            if (promise._h == 2) onHandleUnhandled(promise);
            promise._h = 1;
          }

          if (handler === true) result = value;else {
            if (domain) domain.enter();
            result = handler(value); // may throw

            if (domain) {
              domain.exit();
              exited = true;
            }
          }

          if (result === reaction.promise) {
            reject(TypeError('Promise-chain cycle'));
          } else if (then = isThenable(result)) {
            then.call(result, resolve, reject);
          } else resolve(result);
        } else reject(value);
      } catch (e) {
        if (domain && !exited) domain.exit();
        reject(e);
      }
    };

    while (chain.length > i) run(chain[i++]); // variable length - can't use forEach


    promise._c = [];
    promise._n = false;
    if (isReject && !promise._h) onUnhandled(promise);
  });
};

var onUnhandled = function (promise) {
  task.call(global, function () {
    var value = promise._v;
    var unhandled = isUnhandled(promise);
    var result, handler, console;

    if (unhandled) {
      result = perform(function () {
        if (isNode) {
          process.emit('unhandledRejection', value, promise);
        } else if (handler = global.onunhandledrejection) {
          handler({
            promise: promise,
            reason: value
          });
        } else if ((console = global.console) && console.error) {
          console.error('Unhandled promise rejection', value);
        }
      }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should

      promise._h = isNode || isUnhandled(promise) ? 2 : 1;
    }

    promise._a = undefined;
    if (unhandled && result.e) throw result.v;
  });
};

var isUnhandled = function (promise) {
  return promise._h !== 1 && (promise._a || promise._c).length === 0;
};

var onHandleUnhandled = function (promise) {
  task.call(global, function () {
    var handler;

    if (isNode) {
      process.emit('rejectionHandled', promise);
    } else if (handler = global.onrejectionhandled) {
      handler({
        promise: promise,
        reason: promise._v
      });
    }
  });
};

var $reject = function (value) {
  var promise = this;
  if (promise._d) return;
  promise._d = true;
  promise = promise._w || promise; // unwrap

  promise._v = value;
  promise._s = 2;
  if (!promise._a) promise._a = promise._c.slice();
  notify(promise, true);
};

var $resolve = function (value) {
  var promise = this;
  var then;
  if (promise._d) return;
  promise._d = true;
  promise = promise._w || promise; // unwrap

  try {
    if (promise === value) throw TypeError("Promise can't be resolved itself");

    if (then = isThenable(value)) {
      microtask(function () {
        var wrapper = {
          _w: promise,
          _d: false
        }; // wrap

        try {
          then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
        } catch (e) {
          $reject.call(wrapper, e);
        }
      });
    } else {
      promise._v = value;
      promise._s = 1;
      notify(promise, false);
    }
  } catch (e) {
    $reject.call({
      _w: promise,
      _d: false
    }, e); // wrap
  }
}; // constructor polyfill


if (!USE_NATIVE) {
  // 25.4.3.1 Promise(executor)
  $Promise = function Promise(executor) {
    anInstance(this, $Promise, PROMISE, '_h');
    aFunction(executor);
    Internal.call(this);

    try {
      executor(ctx($resolve, this, 1), ctx($reject, this, 1));
    } catch (err) {
      $reject.call(this, err);
    }
  }; // eslint-disable-next-line no-unused-vars


  Internal = function Promise(executor) {
    this._c = []; // <- awaiting reactions

    this._a = undefined; // <- checked in isUnhandled reactions

    this._s = 0; // <- state

    this._d = false; // <- done

    this._v = undefined; // <- value

    this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled

    this._n = false; // <- notify
  };

  Internal.prototype = __webpack_require__(485)($Promise.prototype, {
    // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
    then: function then(onFulfilled, onRejected) {
      var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
      reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
      reaction.fail = typeof onRejected == 'function' && onRejected;
      reaction.domain = isNode ? process.domain : undefined;

      this._c.push(reaction);

      if (this._a) this._a.push(reaction);
      if (this._s) notify(this, false);
      return reaction.promise;
    },
    // 25.4.5.1 Promise.prototype.catch(onRejected)
    'catch': function (onRejected) {
      return this.then(undefined, onRejected);
    }
  });

  OwnPromiseCapability = function () {
    var promise = new Internal();
    this.promise = promise;
    this.resolve = ctx($resolve, promise, 1);
    this.reject = ctx($reject, promise, 1);
  };

  newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
    return C === $Promise || C === Wrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C);
  };
}

$export($export.G + $export.W + $export.F * !USE_NATIVE, {
  Promise: $Promise
});

__webpack_require__(87)($Promise, PROMISE);

__webpack_require__(486)(PROMISE);

Wrapper = __webpack_require__(15)[PROMISE]; // statics

$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
  // 25.4.4.5 Promise.reject(r)
  reject: function reject(r) {
    var capability = newPromiseCapability(this);
    var $$reject = capability.reject;
    $$reject(r);
    return capability.promise;
  }
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
  // 25.4.4.6 Promise.resolve(x)
  resolve: function resolve(x) {
    return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x);
  }
});
$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(487)(function (iter) {
  $Promise.all(iter)['catch'](empty);
})), PROMISE, {
  // 25.4.4.1 Promise.all(iterable)
  all: function all(iterable) {
    var C = this;
    var capability = newPromiseCapability(C);
    var resolve = capability.resolve;
    var reject = capability.reject;
    var result = perform(function () {
      var values = [];
      var index = 0;
      var remaining = 1;
      forOf(iterable, false, function (promise) {
        var $index = index++;
        var alreadyCalled = false;
        values.push(undefined);
        remaining++;
        C.resolve(promise).then(function (value) {
          if (alreadyCalled) return;
          alreadyCalled = true;
          values[$index] = value;
          --remaining || resolve(values);
        }, reject);
      });
      --remaining || resolve(values);
    });
    if (result.e) reject(result.v);
    return capability.promise;
  },
  // 25.4.4.4 Promise.race(iterable)
  race: function race(iterable) {
    var C = this;
    var capability = newPromiseCapability(C);
    var reject = capability.reject;
    var result = perform(function () {
      forOf(iterable, false, function (promise) {
        C.resolve(promise).then(capability.resolve, reject);
      });
    });
    if (result.e) reject(result.v);
    return capability.promise;
  }
});

/***/ }),
/* 477 */
/***/ (function(module, exports) {

module.exports = function (it, Constructor, name, forbiddenField) {
  if (!(it instanceof Constructor) || forbiddenField !== undefined && forbiddenField in it) {
    throw TypeError(name + ': incorrect invocation!');
  }

  return it;
};

/***/ }),
/* 478 */
/***/ (function(module, exports, __webpack_require__) {

var ctx = __webpack_require__(54);

var call = __webpack_require__(479);

var isArrayIter = __webpack_require__(480);

var anObject = __webpack_require__(22);

var toLength = __webpack_require__(141);

var getIterFn = __webpack_require__(481);

var BREAK = {};
var RETURN = {};

var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {
  var iterFn = ITERATOR ? function () {
    return iterable;
  } : getIterFn(iterable);
  var f = ctx(fn, that, entries ? 2 : 1);
  var index = 0;
  var length, step, iterator, result;
  if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); // fast case for arrays with default iterator

  if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) {
    result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
    if (result === BREAK || result === RETURN) return result;
  } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {
    result = call(iterator, f, step.value, entries);
    if (result === BREAK || result === RETURN) return result;
  }
};

exports.BREAK = BREAK;
exports.RETURN = RETURN;

/***/ }),
/* 479 */
/***/ (function(module, exports, __webpack_require__) {

// call something on iterator step with safe closing on error
var anObject = __webpack_require__(22);

module.exports = function (iterator, fn, value, entries) {
  try {
    return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion)
  } catch (e) {
    var ret = iterator['return'];
    if (ret !== undefined) anObject(ret.call(iterator));
    throw e;
  }
};

/***/ }),
/* 480 */
/***/ (function(module, exports, __webpack_require__) {

// check on default Array iterator
var Iterators = __webpack_require__(38);

var ITERATOR = __webpack_require__(13)('iterator');

var ArrayProto = Array.prototype;

module.exports = function (it) {
  return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};

/***/ }),
/* 481 */
/***/ (function(module, exports, __webpack_require__) {

var classof = __webpack_require__(147);

var ITERATOR = __webpack_require__(13)('iterator');

var Iterators = __webpack_require__(38);

module.exports = __webpack_require__(15).getIteratorMethod = function (it) {
  if (it != undefined) return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)];
};

/***/ }),
/* 482 */
/***/ (function(module, exports) {

// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function (fn, args, that) {
  var un = that === undefined;

  switch (args.length) {
    case 0:
      return un ? fn() : fn.call(that);

    case 1:
      return un ? fn(args[0]) : fn.call(that, args[0]);

    case 2:
      return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]);

    case 3:
      return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]);

    case 4:
      return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]);
  }

  return fn.apply(that, args);
};

/***/ }),
/* 483 */
/***/ (function(module, exports, __webpack_require__) {

var global = __webpack_require__(10);

var macrotask = __webpack_require__(149).set;

var Observer = global.MutationObserver || global.WebKitMutationObserver;
var process = global.process;
var Promise = global.Promise;
var isNode = __webpack_require__(57)(process) == 'process';

module.exports = function () {
  var head, last, notify;

  var flush = function () {
    var parent, fn;
    if (isNode && (parent = process.domain)) parent.exit();

    while (head) {
      fn = head.fn;
      head = head.next;

      try {
        fn();
      } catch (e) {
        if (head) notify();else last = undefined;
        throw e;
      }
    }

    last = undefined;
    if (parent) parent.enter();
  }; // Node.js


  if (isNode) {
    notify = function () {
      process.nextTick(flush);
    }; // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339

  } else if (Observer && !(global.navigator && global.navigator.standalone)) {
    var toggle = true;
    var node = document.createTextNode('');
    new Observer(flush).observe(node, {
      characterData: true
    }); // eslint-disable-line no-new

    notify = function () {
      node.data = toggle = !toggle;
    }; // environments with maybe non-completely correct, but existent Promise

  } else if (Promise && Promise.resolve) {
    // Promise.resolve without an argument throws an error in LG WebOS 2
    var promise = Promise.resolve(undefined);

    notify = function () {
      promise.then(flush);
    }; // for other environments - macrotask based on:
    // - setImmediate
    // - MessageChannel
    // - window.postMessag
    // - onreadystatechange
    // - setTimeout

  } else {
    notify = function () {
      // strange IE + webpack dev server bug - use .call(global)
      macrotask.call(global, flush);
    };
  }

  return function (fn) {
    var task = {
      fn: fn,
      next: undefined
    };
    if (last) last.next = task;

    if (!head) {
      head = task;
      notify();
    }

    last = task;
  };
};

/***/ }),
/* 484 */
/***/ (function(module, exports, __webpack_require__) {

var global = __webpack_require__(10);

var navigator = global.navigator;
module.exports = navigator && navigator.userAgent || '';

/***/ }),
/* 485 */
/***/ (function(module, exports, __webpack_require__) {

var hide = __webpack_require__(27);

module.exports = function (target, src, safe) {
  for (var key in src) {
    if (safe && target[key]) target[key] = src[key];else hide(target, key, src[key]);
  }

  return target;
};

/***/ }),
/* 486 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var global = __webpack_require__(10);

var core = __webpack_require__(15);

var dP = __webpack_require__(36);

var DESCRIPTORS = __webpack_require__(28);

var SPECIES = __webpack_require__(13)('species');

module.exports = function (KEY) {
  var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY];
  if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {
    configurable: true,
    get: function () {
      return this;
    }
  });
};

/***/ }),
/* 487 */
/***/ (function(module, exports, __webpack_require__) {

var ITERATOR = __webpack_require__(13)('iterator');

var SAFE_CLOSING = false;

try {
  var riter = [7][ITERATOR]();

  riter['return'] = function () {
    SAFE_CLOSING = true;
  }; // eslint-disable-next-line no-throw-literal


  Array.from(riter, function () {
    throw 2;
  });
} catch (e) {
  /* empty */
}

module.exports = function (exec, skipClosing) {
  if (!skipClosing && !SAFE_CLOSING) return false;
  var safe = false;

  try {
    var arr = [7];
    var iter = arr[ITERATOR]();

    iter.next = function () {
      return {
        done: safe = true
      };
    };

    arr[ITERATOR] = function () {
      return iter;
    };

    exec(arr);
  } catch (e) {
    /* empty */
  }

  return safe;
};

/***/ }),
/* 488 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// https://github.com/tc39/proposal-promise-finally


var $export = __webpack_require__(26);

var core = __webpack_require__(15);

var global = __webpack_require__(10);

var speciesConstructor = __webpack_require__(148);

var promiseResolve = __webpack_require__(151);

$export($export.P + $export.R, 'Promise', {
  'finally': function (onFinally) {
    var C = speciesConstructor(this, core.Promise || global.Promise);
    var isFunction = typeof onFinally == 'function';
    return this.then(isFunction ? function (x) {
      return promiseResolve(C, onFinally()).then(function () {
        return x;
      });
    } : onFinally, isFunction ? function (e) {
      return promiseResolve(C, onFinally()).then(function () {
        throw e;
      });
    } : onFinally);
  }
});

/***/ }),
/* 489 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
 // https://github.com/tc39/proposal-promise-try

var $export = __webpack_require__(26);

var newPromiseCapability = __webpack_require__(88);

var perform = __webpack_require__(150);

$export($export.S, 'Promise', {
  'try': function (callbackfn) {
    var promiseCapability = newPromiseCapability.f(this);
    var result = perform(callbackfn);
    (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v);
    return promiseCapability.promise;
  }
});

/***/ }),
/* 490 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});

var _promise = __webpack_require__(86);

var _promise2 = _interopRequireDefault(_promise);

exports.getStorage = getStorage;
exports.usePromise = usePromise;

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {
    default: obj
  };
}
/**
 * Need to invoke a function at runtime instead of import-time to make tests
 * pass with mocked browser and chrome objects
 */


function getStorage() {
  return window.browser && browser.storage || window.chrome && chrome.storage;
}
/**
 * Need to invoke a function at runtime instead of import-time to make tests
 * pass with mocked browser and chrome objects
 */


function usesPromises() {
  var storage = getStorage();

  try {
    return storage && storage.local.get && storage.local.get() && typeof storage.local.get().then === 'function';
  } catch (e) {
    return false;
  }
}
/**
 * Converts a callback-based API to a promise based API.
 * For now we assume that there is only one arg in addition to the callback
 */


function usePromise(fn, arg) {
  if (usesPromises()) {
    return fn(arg);
  }

  return new _promise2.default(function (resolve) {
    fn(arg, function () {
      resolve.apply(undefined, arguments);
    });
  });
}

/***/ }),
/* 491 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _websocket_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(65);
/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(0);
/*
    This program is distributed under the terms of the MIT license.
    Please see the LICENSE file for details.

    Copyright 2020, JC Brand
*/


const lmap = {};
lmap['debug'] = _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].LogLevel.DEBUG;
lmap['info'] = _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].LogLevel.INFO;
lmap['warn'] = _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].LogLevel.WARN;
lmap['error'] = _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].LogLevel.ERROR;
lmap['fatal'] = _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].LogLevel.FATAL;
/** Class: Strophe.WorkerWebsocket
 *  _Private_ helper class that handles a websocket connection inside a shared worker.
 */

_core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].WorkerWebsocket = class WorkerWebsocket extends _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Websocket {
  /** PrivateConstructor: Strophe.WorkerWebsocket
   *  Create and initialize a Strophe.WorkerWebsocket object.
   *
   *  Parameters:
   *    (Strophe.Connection) connection - The Strophe.Connection
   *
   *  Returns:
   *    A new Strophe.WorkerWebsocket object.
   */
  constructor(connection) {
    super(connection);
    this._conn = connection;
    this.worker = new SharedWorker(this._conn.options.worker, 'Strophe XMPP Connection');

    this.worker.onerror = e => {
      var _console;

      (_console = console) === null || _console === void 0 ? void 0 : _console.error(e);
      _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].log(_core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].LogLevel.ERROR, `Shared Worker Error: ${e}`);
    };
  }

  get socket() {
    return {
      'send': str => this.worker.port.postMessage(['send', str])
    };
  }

  _connect() {
    this._messageHandler = m => this._onInitialMessage(m);

    this.worker.port.start();

    this.worker.port.onmessage = ev => this._onWorkerMessage(ev);

    this.worker.port.postMessage(['_connect', this._conn.service, this._conn.jid]);
  }

  _attach(callback) {
    this._messageHandler = m => this._onMessage(m);

    this._conn.connect_callback = callback;
    this.worker.port.start();

    this.worker.port.onmessage = ev => this._onWorkerMessage(ev);

    this.worker.port.postMessage(['_attach', this._conn.service]);
  }

  _attachCallback(status, jid) {
    if (status === _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.ATTACHED) {
      this._conn.jid = jid;
      this._conn.authenticated = true;
      this._conn.connected = true;
      this._conn.restored = true;

      this._conn._changeConnectStatus(_core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.ATTACHED);
    } else if (status === _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.ATTACHFAIL) {
      this._conn.authenticated = false;
      this._conn.connected = false;
      this._conn.restored = false;

      this._conn._changeConnectStatus(_core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.ATTACHFAIL);
    }
  }

  _disconnect(readyState, pres) {
    pres && this._conn.send(pres);
    const close = Object(_core_js__WEBPACK_IMPORTED_MODULE_1__[/* $build */ "a"])("close", {
      "xmlns": _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].NS.FRAMING
    });

    this._conn.xmlOutput(close.tree());

    const closeString = _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].serialize(close);

    this._conn.rawOutput(closeString);

    this.worker.port.postMessage(['send', closeString]);

    this._conn._doDisconnect();
  }

  _onClose(e) {
    if (this._conn.connected && !this._conn.disconnecting) {
      _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("Websocket closed unexpectedly");

      this._conn._doDisconnect();
    } else if (e && e.code === 1006 && !this._conn.connected) {
      // in case the onError callback was not called (Safari 10 does not
      // call onerror when the initial connection fails) we need to
      // dispatch a CONNFAIL status update to be consistent with the
      // behavior on other browsers.
      _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].error("Websocket closed unexcectedly");

      this._conn._changeConnectStatus(_core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].Status.CONNFAIL, "The WebSocket connection could not be established or was disconnected.");

      this._conn._doDisconnect();
    } else {
      _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].debug("Websocket closed");
    }
  }

  _closeSocket() {
    this.worker.port.postMessage(['_closeSocket']);
  }
  /** PrivateFunction: _replaceMessageHandler
   *
   * Called by _onInitialMessage in order to replace itself with the general message handler.
   * This method is overridden by Strophe.WorkerWebsocket, which manages a
   * websocket connection via a service worker and doesn't have direct access
   * to the socket.
   */


  _replaceMessageHandler() {
    this._messageHandler = m => this._onMessage(m);
  }
  /** PrivateFunction: _onWorkerMessage
   * _Private_ function that handles messages received from the service worker
   */


  _onWorkerMessage(ev) {
    const {
      data
    } = ev;
    const method_name = data[0];

    if (method_name === '_onMessage') {
      this._messageHandler(data[1]);
    } else if (method_name in this) {
      try {
        this[method_name].apply(this, ev.data.slice(1));
      } catch (e) {
        _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].log(_core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].LogLevel.ERROR, e);
      }
    } else if (method_name === 'log') {
      const level = data[1];
      const msg = data[2];
      _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].log(lmap[level], msg);
    } else {
      _core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].log(_core_js__WEBPACK_IMPORTED_MODULE_1__[/* Strophe */ "f"].LogLevel.ERROR, `Found unhandled service worker message: ${data}`);
    }
  }

};

/***/ }),
/* 492 */
/***/ (function(module, exports, __webpack_require__) {

var map = {
	"./af/LC_MESSAGES/converse.po": [
		502,
		139
	],
	"./ar/LC_MESSAGES/converse.po": [
		503,
		140
	],
	"./bg/LC_MESSAGES/converse.po": [
		504,
		141
	],
	"./ca/LC_MESSAGES/converse.po": [
		505,
		142
	],
	"./cs/LC_MESSAGES/converse.po": [
		506,
		143
	],
	"./da/LC_MESSAGES/converse.po": [
		507,
		144
	],
	"./de/LC_MESSAGES/converse.po": [
		508,
		147
	],
	"./eo/LC_MESSAGES/converse.po": [
		509,
		148
	],
	"./es/LC_MESSAGES/converse.po": [
		510,
		149
	],
	"./eu/LC_MESSAGES/converse.po": [
		511,
		150
	],
	"./fi/LC_MESSAGES/converse.po": [
		512,
		151
	],
	"./fr/LC_MESSAGES/converse.po": [
		513,
		152
	],
	"./gl/LC_MESSAGES/converse.po": [
		514,
		153
	],
	"./he/LC_MESSAGES/converse.po": [
		515,
		154
	],
	"./hi/LC_MESSAGES/converse.po": [
		516,
		155
	],
	"./hu/LC_MESSAGES/converse.po": [
		517,
		156
	],
	"./id/LC_MESSAGES/converse.po": [
		518,
		157
	],
	"./it/LC_MESSAGES/converse.po": [
		519,
		158
	],
	"./ja/LC_MESSAGES/converse.po": [
		520,
		159
	],
	"./lt/LC_MESSAGES/converse.po": [
		521,
		160
	],
	"./mr/LC_MESSAGES/converse.po": [
		522,
		161
	],
	"./nb/LC_MESSAGES/converse.po": [
		523,
		162
	],
	"./nl/LC_MESSAGES/converse.po": [
		524,
		163
	],
	"./nl_BE/LC_MESSAGES/converse.po": [
		525,
		164
	],
	"./oc/LC_MESSAGES/converse.po": [
		526,
		165
	],
	"./pl/LC_MESSAGES/converse.po": [
		527,
		166
	],
	"./pt/LC_MESSAGES/converse.po": [
		528,
		167
	],
	"./pt_BR/LC_MESSAGES/converse.po": [
		529,
		168
	],
	"./ro/LC_MESSAGES/converse.po": [
		530,
		169
	],
	"./ru/LC_MESSAGES/converse.po": [
		531,
		170
	],
	"./sv/LC_MESSAGES/converse.po": [
		532,
		171
	],
	"./th/LC_MESSAGES/converse.po": [
		533,
		172
	],
	"./tr/LC_MESSAGES/converse.po": [
		534,
		173
	],
	"./uk/LC_MESSAGES/converse.po": [
		535,
		174
	],
	"./vi/LC_MESSAGES/converse.po": [
		536,
		175
	],
	"./zh_CN/LC_MESSAGES/converse.po": [
		537,
		176
	],
	"./zh_TW/LC_MESSAGES/converse.po": [
		538,
		177
	]
};
function webpackAsyncContext(req) {
	if(!__webpack_require__.o(map, req)) {
		return Promise.resolve().then(function() {
			var e = new Error("Cannot find module '" + req + "'");
			e.code = 'MODULE_NOT_FOUND';
			throw e;
		});
	}

	var ids = map[req], id = ids[0];
	return __webpack_require__.e(ids[1]).then(function() {
		return __webpack_require__.t(id, 3);
	});
}
webpackAsyncContext.keys = function webpackAsyncContextKeys() {
	return Object.keys(map);
};
webpackAsyncContext.id = 492;
module.exports = webpackAsyncContext;

/***/ }),
/* 493 */
/***/ (function(module, exports, __webpack_require__) {

var map = {
	"./af": [
		184,
		0
	],
	"./af.js": [
		184,
		0
	],
	"./ar": [
		191,
		1
	],
	"./ar-dz": [
		185,
		2
	],
	"./ar-dz.js": [
		185,
		2
	],
	"./ar-kw": [
		186,
		3
	],
	"./ar-kw.js": [
		186,
		3
	],
	"./ar-ly": [
		187,
		4
	],
	"./ar-ly.js": [
		187,
		4
	],
	"./ar-ma": [
		188,
		5
	],
	"./ar-ma.js": [
		188,
		5
	],
	"./ar-sa": [
		189,
		6
	],
	"./ar-sa.js": [
		189,
		6
	],
	"./ar-tn": [
		190,
		7
	],
	"./ar-tn.js": [
		190,
		7
	],
	"./ar.js": [
		191,
		1
	],
	"./az": [
		192,
		8
	],
	"./az.js": [
		192,
		8
	],
	"./be": [
		193,
		9
	],
	"./be.js": [
		193,
		9
	],
	"./bg": [
		194,
		10
	],
	"./bg.js": [
		194,
		10
	],
	"./bi": [
		195,
		11
	],
	"./bi.js": [
		195,
		11
	],
	"./bm": [
		196,
		12
	],
	"./bm.js": [
		196,
		12
	],
	"./bn": [
		197,
		13
	],
	"./bn.js": [
		197,
		13
	],
	"./bo": [
		198,
		14
	],
	"./bo.js": [
		198,
		14
	],
	"./br": [
		199,
		15
	],
	"./br.js": [
		199,
		15
	],
	"./bs": [
		200,
		16
	],
	"./bs.js": [
		200,
		16
	],
	"./ca": [
		201,
		17
	],
	"./ca.js": [
		201,
		17
	],
	"./cs": [
		202,
		18
	],
	"./cs.js": [
		202,
		18
	],
	"./cv": [
		203,
		19
	],
	"./cv.js": [
		203,
		19
	],
	"./cy": [
		204,
		20
	],
	"./cy.js": [
		204,
		20
	],
	"./da": [
		205,
		21
	],
	"./da.js": [
		205,
		21
	],
	"./de": [
		208,
		22
	],
	"./de-at": [
		206,
		23
	],
	"./de-at.js": [
		206,
		23
	],
	"./de-ch": [
		207,
		24
	],
	"./de-ch.js": [
		207,
		24
	],
	"./de.js": [
		208,
		22
	],
	"./dv": [
		209,
		25
	],
	"./dv.js": [
		209,
		25
	],
	"./el": [
		210,
		26
	],
	"./el.js": [
		210,
		26
	],
	"./en": [
		220,
		27
	],
	"./en-SG": [
		211,
		28
	],
	"./en-SG.js": [
		211,
		28
	],
	"./en-au": [
		212,
		29
	],
	"./en-au.js": [
		212,
		29
	],
	"./en-ca": [
		213,
		30
	],
	"./en-ca.js": [
		213,
		30
	],
	"./en-gb": [
		214,
		31
	],
	"./en-gb.js": [
		214,
		31
	],
	"./en-ie": [
		215,
		32
	],
	"./en-ie.js": [
		215,
		32
	],
	"./en-il": [
		216,
		33
	],
	"./en-il.js": [
		216,
		33
	],
	"./en-in": [
		217,
		34
	],
	"./en-in.js": [
		217,
		34
	],
	"./en-nz": [
		218,
		35
	],
	"./en-nz.js": [
		218,
		35
	],
	"./en-tt": [
		219,
		36
	],
	"./en-tt.js": [
		219,
		36
	],
	"./en.js": [
		220,
		27
	],
	"./eo": [
		221,
		37
	],
	"./eo.js": [
		221,
		37
	],
	"./es": [
		225,
		38
	],
	"./es-do": [
		222,
		39
	],
	"./es-do.js": [
		222,
		39
	],
	"./es-pr": [
		223,
		40
	],
	"./es-pr.js": [
		223,
		40
	],
	"./es-us": [
		224,
		41
	],
	"./es-us.js": [
		224,
		41
	],
	"./es.js": [
		225,
		38
	],
	"./et": [
		226,
		42
	],
	"./et.js": [
		226,
		42
	],
	"./eu": [
		227,
		43
	],
	"./eu.js": [
		227,
		43
	],
	"./fa": [
		228,
		44
	],
	"./fa.js": [
		228,
		44
	],
	"./fi": [
		229,
		45
	],
	"./fi.js": [
		229,
		45
	],
	"./fo": [
		230,
		46
	],
	"./fo.js": [
		230,
		46
	],
	"./fr": [
		233,
		47
	],
	"./fr-ca": [
		231,
		48
	],
	"./fr-ca.js": [
		231,
		48
	],
	"./fr-ch": [
		232,
		49
	],
	"./fr-ch.js": [
		232,
		49
	],
	"./fr.js": [
		233,
		47
	],
	"./fy": [
		234,
		50
	],
	"./fy.js": [
		234,
		50
	],
	"./ga": [
		235,
		51
	],
	"./ga.js": [
		235,
		51
	],
	"./gd": [
		236,
		52
	],
	"./gd.js": [
		236,
		52
	],
	"./gl": [
		237,
		53
	],
	"./gl.js": [
		237,
		53
	],
	"./gom-latn": [
		238,
		54
	],
	"./gom-latn.js": [
		238,
		54
	],
	"./gu": [
		239,
		55
	],
	"./gu.js": [
		239,
		55
	],
	"./he": [
		240,
		56
	],
	"./he.js": [
		240,
		56
	],
	"./hi": [
		241,
		57
	],
	"./hi.js": [
		241,
		57
	],
	"./hr": [
		242,
		58
	],
	"./hr.js": [
		242,
		58
	],
	"./ht": [
		243,
		59
	],
	"./ht.js": [
		243,
		59
	],
	"./hu": [
		244,
		60
	],
	"./hu.js": [
		244,
		60
	],
	"./hy-am": [
		245,
		61
	],
	"./hy-am.js": [
		245,
		61
	],
	"./id": [
		246,
		62
	],
	"./id.js": [
		246,
		62
	],
	"./index.d.ts": [
		539,
		145
	],
	"./is": [
		247,
		63
	],
	"./is.js": [
		247,
		63
	],
	"./it": [
		249,
		64
	],
	"./it-ch": [
		248,
		65
	],
	"./it-ch.js": [
		248,
		65
	],
	"./it.js": [
		249,
		64
	],
	"./ja": [
		250,
		66
	],
	"./ja.js": [
		250,
		66
	],
	"./jv": [
		251,
		67
	],
	"./jv.js": [
		251,
		67
	],
	"./ka": [
		252,
		68
	],
	"./ka.js": [
		252,
		68
	],
	"./kk": [
		253,
		69
	],
	"./kk.js": [
		253,
		69
	],
	"./km": [
		254,
		70
	],
	"./km.js": [
		254,
		70
	],
	"./kn": [
		255,
		71
	],
	"./kn.js": [
		255,
		71
	],
	"./ko": [
		256,
		72
	],
	"./ko.js": [
		256,
		72
	],
	"./ku": [
		257,
		73
	],
	"./ku.js": [
		257,
		73
	],
	"./ky": [
		258,
		74
	],
	"./ky.js": [
		258,
		74
	],
	"./lb": [
		259,
		75
	],
	"./lb.js": [
		259,
		75
	],
	"./lo": [
		260,
		76
	],
	"./lo.js": [
		260,
		76
	],
	"./lt": [
		261,
		77
	],
	"./lt.js": [
		261,
		77
	],
	"./lv": [
		262,
		78
	],
	"./lv.js": [
		262,
		78
	],
	"./me": [
		263,
		79
	],
	"./me.js": [
		263,
		79
	],
	"./mi": [
		264,
		80
	],
	"./mi.js": [
		264,
		80
	],
	"./mk": [
		265,
		81
	],
	"./mk.js": [
		265,
		81
	],
	"./ml": [
		266,
		82
	],
	"./ml.js": [
		266,
		82
	],
	"./mn": [
		267,
		83
	],
	"./mn.js": [
		267,
		83
	],
	"./mr": [
		268,
		84
	],
	"./mr.js": [
		268,
		84
	],
	"./ms": [
		270,
		85
	],
	"./ms-my": [
		269,
		86
	],
	"./ms-my.js": [
		269,
		86
	],
	"./ms.js": [
		270,
		85
	],
	"./mt": [
		271,
		87
	],
	"./mt.js": [
		271,
		87
	],
	"./my": [
		272,
		88
	],
	"./my.js": [
		272,
		88
	],
	"./nb": [
		273,
		89
	],
	"./nb.js": [
		273,
		89
	],
	"./ne": [
		274,
		90
	],
	"./ne.js": [
		274,
		90
	],
	"./nl": [
		276,
		91
	],
	"./nl-be": [
		275,
		92
	],
	"./nl-be.js": [
		275,
		92
	],
	"./nl.js": [
		276,
		91
	],
	"./nn": [
		277,
		93
	],
	"./nn.js": [
		277,
		93
	],
	"./oc-lnc": [
		278,
		94
	],
	"./oc-lnc.js": [
		278,
		94
	],
	"./pa-in": [
		279,
		95
	],
	"./pa-in.js": [
		279,
		95
	],
	"./pl": [
		280,
		96
	],
	"./pl.js": [
		280,
		96
	],
	"./pt": [
		282,
		97
	],
	"./pt-br": [
		281,
		98
	],
	"./pt-br.js": [
		281,
		98
	],
	"./pt.js": [
		282,
		97
	],
	"./ro": [
		283,
		99
	],
	"./ro.js": [
		283,
		99
	],
	"./ru": [
		284,
		100
	],
	"./ru.js": [
		284,
		100
	],
	"./rw": [
		285,
		101
	],
	"./rw.js": [
		285,
		101
	],
	"./sd": [
		286,
		102
	],
	"./sd.js": [
		286,
		102
	],
	"./se": [
		287,
		103
	],
	"./se.js": [
		287,
		103
	],
	"./si": [
		288,
		104
	],
	"./si.js": [
		288,
		104
	],
	"./sk": [
		289,
		105
	],
	"./sk.js": [
		289,
		105
	],
	"./sl": [
		290,
		106
	],
	"./sl.js": [
		290,
		106
	],
	"./sq": [
		291,
		107
	],
	"./sq.js": [
		291,
		107
	],
	"./sr": [
		293,
		108
	],
	"./sr-cyrl": [
		292,
		109
	],
	"./sr-cyrl.js": [
		292,
		109
	],
	"./sr.js": [
		293,
		108
	],
	"./ss": [
		294,
		110
	],
	"./ss.js": [
		294,
		110
	],
	"./sv": [
		295,
		111
	],
	"./sv.js": [
		295,
		111
	],
	"./sw": [
		296,
		112
	],
	"./sw.js": [
		296,
		112
	],
	"./ta": [
		297,
		113
	],
	"./ta.js": [
		297,
		113
	],
	"./te": [
		298,
		114
	],
	"./te.js": [
		298,
		114
	],
	"./tet": [
		299,
		115
	],
	"./tet.js": [
		299,
		115
	],
	"./tg": [
		300,
		116
	],
	"./tg.js": [
		300,
		116
	],
	"./th": [
		301,
		117
	],
	"./th.js": [
		301,
		117
	],
	"./tk": [
		302,
		118
	],
	"./tk.js": [
		302,
		118
	],
	"./tl-ph": [
		303,
		119
	],
	"./tl-ph.js": [
		303,
		119
	],
	"./tlh": [
		304,
		120
	],
	"./tlh.js": [
		304,
		120
	],
	"./tr": [
		305,
		121
	],
	"./tr.js": [
		305,
		121
	],
	"./types.d.ts": [
		540,
		146
	],
	"./tzl": [
		306,
		122
	],
	"./tzl.js": [
		306,
		122
	],
	"./tzm": [
		308,
		123
	],
	"./tzm-latn": [
		307,
		124
	],
	"./tzm-latn.js": [
		307,
		124
	],
	"./tzm.js": [
		308,
		123
	],
	"./ug-cn": [
		309,
		125
	],
	"./ug-cn.js": [
		309,
		125
	],
	"./uk": [
		310,
		126
	],
	"./uk.js": [
		310,
		126
	],
	"./ur": [
		311,
		127
	],
	"./ur.js": [
		311,
		127
	],
	"./uz": [
		313,
		128
	],
	"./uz-latn": [
		312,
		129
	],
	"./uz-latn.js": [
		312,
		129
	],
	"./uz.js": [
		313,
		128
	],
	"./vi": [
		314,
		130
	],
	"./vi.js": [
		314,
		130
	],
	"./x-pseudo": [
		315,
		131
	],
	"./x-pseudo.js": [
		315,
		131
	],
	"./yo": [
		316,
		132
	],
	"./yo.js": [
		316,
		132
	],
	"./zh": [
		320,
		133
	],
	"./zh-cn": [
		317,
		134
	],
	"./zh-cn.js": [
		317,
		134
	],
	"./zh-hk": [
		318,
		135
	],
	"./zh-hk.js": [
		318,
		135
	],
	"./zh-tw": [
		319,
		136
	],
	"./zh-tw.js": [
		319,
		136
	],
	"./zh.js": [
		320,
		133
	]
};
function webpackAsyncContext(req) {
	if(!__webpack_require__.o(map, req)) {
		return Promise.resolve().then(function() {
			var e = new Error("Cannot find module '" + req + "'");
			e.code = 'MODULE_NOT_FOUND';
			throw e;
		});
	}

	var ids = map[req], id = ids[0];
	return __webpack_require__.e(ids[1]).then(function() {
		return __webpack_require__.t(id, 7);
	});
}
webpackAsyncContext.keys = function webpackAsyncContextKeys() {
	return Object.keys(map);
};
webpackAsyncContext.id = 493;
module.exports = webpackAsyncContext;

/***/ }),
/* 494 */
/***/ (function(module, exports, __webpack_require__) {

var basePropertyOf = __webpack_require__(495);
/** Used to map characters to HTML entities. */


var htmlEscapes = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;'
};
/**
 * Used by `_.escape` to convert characters to HTML entities.
 *
 * @private
 * @param {string} chr The matched character to escape.
 * @returns {string} Returns the escaped character.
 */

var escapeHtmlChar = basePropertyOf(htmlEscapes);
module.exports = escapeHtmlChar;

/***/ }),
/* 495 */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.propertyOf` without support for deep paths.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Function} Returns the new accessor function.
 */
function basePropertyOf(object) {
  return function (key) {
    return object == null ? undefined : object[key];
  };
}

module.exports = basePropertyOf;

/***/ }),
/* 496 */
/***/ (function(module, exports, __webpack_require__) {


var content = __webpack_require__(497);

if(typeof content === 'string') content = [[module.i, content, '']];

var transform;
var insertInto;



var options = {"hmr":true}

options.transform = transform
options.insertInto = undefined;

var update = __webpack_require__(499)(content, options);

if(content.locals) module.exports = content.locals;

if(false) {}

/***/ }),
/* 497 */
/***/ (function(module, exports, __webpack_require__) {

// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__(498);
exports = ___CSS_LOADER_API_IMPORT___(true);
// Module
exports.push([module.i, "", "",{"version":3,"sources":[],"names":[],"mappings":"","file":"converse.scss"}]);
// Exports
module.exports = exports;


/***/ }),
/* 498 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*
  MIT License http://www.opensource.org/licenses/mit-license.php
  Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
// eslint-disable-next-line func-names

module.exports = function (useSourceMap) {
  var list = []; // return the list of modules as css string

  list.toString = function toString() {
    return this.map(function (item) {
      var content = cssWithMappingToString(item, useSourceMap);

      if (item[2]) {
        return "@media ".concat(item[2], " {").concat(content, "}");
      }

      return content;
    }).join('');
  }; // import a list of modules into the list
  // eslint-disable-next-line func-names


  list.i = function (modules, mediaQuery, dedupe) {
    if (typeof modules === 'string') {
      // eslint-disable-next-line no-param-reassign
      modules = [[null, modules, '']];
    }

    var alreadyImportedModules = {};

    if (dedupe) {
      for (var i = 0; i < this.length; i++) {
        // eslint-disable-next-line prefer-destructuring
        var id = this[i][0];

        if (id != null) {
          alreadyImportedModules[id] = true;
        }
      }
    }

    for (var _i = 0; _i < modules.length; _i++) {
      var item = [].concat(modules[_i]);

      if (dedupe && alreadyImportedModules[item[0]]) {
        // eslint-disable-next-line no-continue
        continue;
      }

      if (mediaQuery) {
        if (!item[2]) {
          item[2] = mediaQuery;
        } else {
          item[2] = "".concat(mediaQuery, " and ").concat(item[2]);
        }
      }

      list.push(item);
    }
  };

  return list;
};

function cssWithMappingToString(item, useSourceMap) {
  var content = item[1] || ''; // eslint-disable-next-line prefer-destructuring

  var cssMapping = item[3];

  if (!cssMapping) {
    return content;
  }

  if (useSourceMap && typeof btoa === 'function') {
    var sourceMapping = toComment(cssMapping);
    var sourceURLs = cssMapping.sources.map(function (source) {
      return "/*# sourceURL=".concat(cssMapping.sourceRoot || '').concat(source, " */");
    });
    return [content].concat(sourceURLs).concat([sourceMapping]).join('\n');
  }

  return [content].join('\n');
} // Adapted from convert-source-map (MIT)


function toComment(sourceMap) {
  // eslint-disable-next-line no-undef
  var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
  var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
  return "/*# ".concat(data, " */");
}

/***/ }),
/* 499 */
/***/ (function(module, exports, __webpack_require__) {

/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

var stylesInDom = {};

var	memoize = function (fn) {
	var memo;

	return function () {
		if (typeof memo === "undefined") memo = fn.apply(this, arguments);
		return memo;
	};
};

var isOldIE = memoize(function () {
	// Test for IE <= 9 as proposed by Browserhacks
	// @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805
	// Tests for existence of standard globals is to allow style-loader
	// to operate correctly into non-standard environments
	// @see https://github.com/webpack-contrib/style-loader/issues/177
	return window && document && document.all && !window.atob;
});

var getTarget = function (target, parent) {
  if (parent){
    return parent.querySelector(target);
  }
  return document.querySelector(target);
};

var getElement = (function (fn) {
	var memo = {};

	return function(target, parent) {
                // If passing function in options, then use it for resolve "head" element.
                // Useful for Shadow Root style i.e
                // {
                //   insertInto: function () { return document.querySelector("#foo").shadowRoot }
                // }
                if (typeof target === 'function') {
                        return target();
                }
                if (typeof memo[target] === "undefined") {
			var styleTarget = getTarget.call(this, target, parent);
			// Special case to return head of iframe instead of iframe itself
			if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
				try {
					// This will throw an exception if access to iframe is blocked
					// due to cross-origin restrictions
					styleTarget = styleTarget.contentDocument.head;
				} catch(e) {
					styleTarget = null;
				}
			}
			memo[target] = styleTarget;
		}
		return memo[target]
	};
})();

var singleton = null;
var	singletonCounter = 0;
var	stylesInsertedAtTop = [];

var	fixUrls = __webpack_require__(500);

module.exports = function(list, options) {
	if (typeof DEBUG !== "undefined" && DEBUG) {
		if (typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
	}

	options = options || {};

	options.attrs = typeof options.attrs === "object" ? options.attrs : {};

	// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
	// tags it will allow on a page
	if (!options.singleton && typeof options.singleton !== "boolean") options.singleton = isOldIE();

	// By default, add <style> tags to the <head> element
        if (!options.insertInto) options.insertInto = "head";

	// By default, add <style> tags to the bottom of the target
	if (!options.insertAt) options.insertAt = "bottom";

	var styles = listToStyles(list, options);

	addStylesToDom(styles, options);

	return function update (newList) {
		var mayRemove = [];

		for (var i = 0; i < styles.length; i++) {
			var item = styles[i];
			var domStyle = stylesInDom[item.id];

			domStyle.refs--;
			mayRemove.push(domStyle);
		}

		if(newList) {
			var newStyles = listToStyles(newList, options);
			addStylesToDom(newStyles, options);
		}

		for (var i = 0; i < mayRemove.length; i++) {
			var domStyle = mayRemove[i];

			if(domStyle.refs === 0) {
				for (var j = 0; j < domStyle.parts.length; j++) domStyle.parts[j]();

				delete stylesInDom[domStyle.id];
			}
		}
	};
};

function addStylesToDom (styles, options) {
	for (var i = 0; i < styles.length; i++) {
		var item = styles[i];
		var domStyle = stylesInDom[item.id];

		if(domStyle) {
			domStyle.refs++;

			for(var j = 0; j < domStyle.parts.length; j++) {
				domStyle.parts[j](item.parts[j]);
			}

			for(; j < item.parts.length; j++) {
				domStyle.parts.push(addStyle(item.parts[j], options));
			}
		} else {
			var parts = [];

			for(var j = 0; j < item.parts.length; j++) {
				parts.push(addStyle(item.parts[j], options));
			}

			stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts};
		}
	}
}

function listToStyles (list, options) {
	var styles = [];
	var newStyles = {};

	for (var i = 0; i < list.length; i++) {
		var item = list[i];
		var id = options.base ? item[0] + options.base : item[0];
		var css = item[1];
		var media = item[2];
		var sourceMap = item[3];
		var part = {css: css, media: media, sourceMap: sourceMap};

		if(!newStyles[id]) styles.push(newStyles[id] = {id: id, parts: [part]});
		else newStyles[id].parts.push(part);
	}

	return styles;
}

function insertStyleElement (options, style) {
	var target = getElement(options.insertInto)

	if (!target) {
		throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.");
	}

	var lastStyleElementInsertedAtTop = stylesInsertedAtTop[stylesInsertedAtTop.length - 1];

	if (options.insertAt === "top") {
		if (!lastStyleElementInsertedAtTop) {
			target.insertBefore(style, target.firstChild);
		} else if (lastStyleElementInsertedAtTop.nextSibling) {
			target.insertBefore(style, lastStyleElementInsertedAtTop.nextSibling);
		} else {
			target.appendChild(style);
		}
		stylesInsertedAtTop.push(style);
	} else if (options.insertAt === "bottom") {
		target.appendChild(style);
	} else if (typeof options.insertAt === "object" && options.insertAt.before) {
		var nextSibling = getElement(options.insertAt.before, target);
		target.insertBefore(style, nextSibling);
	} else {
		throw new Error("[Style Loader]\n\n Invalid value for parameter 'insertAt' ('options.insertAt') found.\n Must be 'top', 'bottom', or Object.\n (https://github.com/webpack-contrib/style-loader#insertat)\n");
	}
}

function removeStyleElement (style) {
	if (style.parentNode === null) return false;
	style.parentNode.removeChild(style);

	var idx = stylesInsertedAtTop.indexOf(style);
	if(idx >= 0) {
		stylesInsertedAtTop.splice(idx, 1);
	}
}

function createStyleElement (options) {
	var style = document.createElement("style");

	if(options.attrs.type === undefined) {
		options.attrs.type = "text/css";
	}

	if(options.attrs.nonce === undefined) {
		var nonce = getNonce();
		if (nonce) {
			options.attrs.nonce = nonce;
		}
	}

	addAttrs(style, options.attrs);
	insertStyleElement(options, style);

	return style;
}

function createLinkElement (options) {
	var link = document.createElement("link");

	if(options.attrs.type === undefined) {
		options.attrs.type = "text/css";
	}
	options.attrs.rel = "stylesheet";

	addAttrs(link, options.attrs);
	insertStyleElement(options, link);

	return link;
}

function addAttrs (el, attrs) {
	Object.keys(attrs).forEach(function (key) {
		el.setAttribute(key, attrs[key]);
	});
}

function getNonce() {
	if (false) {}

	return __webpack_require__.nc;
}

function addStyle (obj, options) {
	var style, update, remove, result;

	// If a transform function was defined, run it on the css
	if (options.transform && obj.css) {
	    result = typeof options.transform === 'function'
		 ? options.transform(obj.css) 
		 : options.transform.default(obj.css);

	    if (result) {
	    	// If transform returns a value, use that instead of the original css.
	    	// This allows running runtime transformations on the css.
	    	obj.css = result;
	    } else {
	    	// If the transform function returns a falsy value, don't add this css.
	    	// This allows conditional loading of css
	    	return function() {
	    		// noop
	    	};
	    }
	}

	if (options.singleton) {
		var styleIndex = singletonCounter++;

		style = singleton || (singleton = createStyleElement(options));

		update = applyToSingletonTag.bind(null, style, styleIndex, false);
		remove = applyToSingletonTag.bind(null, style, styleIndex, true);

	} else if (
		obj.sourceMap &&
		typeof URL === "function" &&
		typeof URL.createObjectURL === "function" &&
		typeof URL.revokeObjectURL === "function" &&
		typeof Blob === "function" &&
		typeof btoa === "function"
	) {
		style = createLinkElement(options);
		update = updateLink.bind(null, style, options);
		remove = function () {
			removeStyleElement(style);

			if(style.href) URL.revokeObjectURL(style.href);
		};
	} else {
		style = createStyleElement(options);
		update = applyToTag.bind(null, style);
		remove = function () {
			removeStyleElement(style);
		};
	}

	update(obj);

	return function updateStyle (newObj) {
		if (newObj) {
			if (
				newObj.css === obj.css &&
				newObj.media === obj.media &&
				newObj.sourceMap === obj.sourceMap
			) {
				return;
			}

			update(obj = newObj);
		} else {
			remove();
		}
	};
}

var replaceText = (function () {
	var textStore = [];

	return function (index, replacement) {
		textStore[index] = replacement;

		return textStore.filter(Boolean).join('\n');
	};
})();

function applyToSingletonTag (style, index, remove, obj) {
	var css = remove ? "" : obj.css;

	if (style.styleSheet) {
		style.styleSheet.cssText = replaceText(index, css);
	} else {
		var cssNode = document.createTextNode(css);
		var childNodes = style.childNodes;

		if (childNodes[index]) style.removeChild(childNodes[index]);

		if (childNodes.length) {
			style.insertBefore(cssNode, childNodes[index]);
		} else {
			style.appendChild(cssNode);
		}
	}
}

function applyToTag (style, obj) {
	var css = obj.css;
	var media = obj.media;

	if(media) {
		style.setAttribute("media", media)
	}

	if(style.styleSheet) {
		style.styleSheet.cssText = css;
	} else {
		while(style.firstChild) {
			style.removeChild(style.firstChild);
		}

		style.appendChild(document.createTextNode(css));
	}
}

function updateLink (link, options, obj) {
	var css = obj.css;
	var sourceMap = obj.sourceMap;

	/*
		If convertToAbsoluteUrls isn't defined, but sourcemaps are enabled
		and there is no publicPath defined then lets turn convertToAbsoluteUrls
		on by default.  Otherwise default to the convertToAbsoluteUrls option
		directly
	*/
	var autoFixUrls = options.convertToAbsoluteUrls === undefined && sourceMap;

	if (options.convertToAbsoluteUrls || autoFixUrls) {
		css = fixUrls(css);
	}

	if (sourceMap) {
		// http://stackoverflow.com/a/26603875
		css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
	}

	var blob = new Blob([css], { type: "text/css" });

	var oldSrc = link.href;

	link.href = URL.createObjectURL(blob);

	if(oldSrc) URL.revokeObjectURL(oldSrc);
}


/***/ }),
/* 500 */
/***/ (function(module, exports) {

/**
 * When source maps are enabled, `style-loader` uses a link element with a data-uri to
 * embed the css on the page. This breaks all relative urls because now they are relative to a
 * bundle instead of the current page.
 *
 * One solution is to only use full urls, but that may be impossible.
 *
 * Instead, this function "fixes" the relative urls to be absolute according to the current page location.
 *
 * A rudimentary test suite is located at `test/fixUrls.js` and can be run via the `npm test` command.
 *
 */
module.exports = function (css) {
  // get current location
  var location = typeof window !== "undefined" && window.location;

  if (!location) {
    throw new Error("fixUrls requires window.location");
  } // blank or null?


  if (!css || typeof css !== "string") {
    return css;
  }

  var baseUrl = location.protocol + "//" + location.host;
  var currentDir = baseUrl + location.pathname.replace(/\/[^\/]*$/, "/"); // convert each url(...)

  /*
  This regular expression is just a way to recursively match brackets within
  a string.
  	 /url\s*\(  = Match on the word "url" with any whitespace after it and then a parens
     (  = Start a capturing group
       (?:  = Start a non-capturing group
           [^)(]  = Match anything that isn't a parentheses
           |  = OR
           \(  = Match a start parentheses
               (?:  = Start another non-capturing groups
                   [^)(]+  = Match anything that isn't a parentheses
                   |  = OR
                   \(  = Match a start parentheses
                       [^)(]*  = Match anything that isn't a parentheses
                   \)  = Match a end parentheses
               )  = End Group
               *\) = Match anything and then a close parens
           )  = Close non-capturing group
           *  = Match anything
        )  = Close capturing group
   \)  = Match a close parens
  	 /gi  = Get all matches, not the first.  Be case insensitive.
   */

  var fixedCss = css.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi, function (fullMatch, origUrl) {
    // strip quotes (if they exist)
    var unquotedOrigUrl = origUrl.trim().replace(/^"(.*)"$/, function (o, $1) {
      return $1;
    }).replace(/^'(.*)'$/, function (o, $1) {
      return $1;
    }); // already a full url? no change

    if (/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/|\s*$)/i.test(unquotedOrigUrl)) {
      return fullMatch;
    } // convert the url to a full url


    var newUrl;

    if (unquotedOrigUrl.indexOf("//") === 0) {
      //TODO: should we add protocol?
      newUrl = unquotedOrigUrl;
    } else if (unquotedOrigUrl.indexOf("/") === 0) {
      // path should be relative to the base url
      newUrl = baseUrl + unquotedOrigUrl; // already starts with '/'
    } else {
      // path should be relative to current directory
      newUrl = currentDir + unquotedOrigUrl.replace(/^\.\//, ""); // Strip leading './'
    } // send back the fixed url(...)


    return "url(" + JSON.stringify(newUrl) + ")";
  }); // send back the fixed css

  return fixedCss;
};

/***/ }),
/* 501 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXTERNAL MODULE: ./src/lodash.noconflict.js
var lodash_noconflict = __webpack_require__(63);
var lodash_noconflict_default = /*#__PURE__*/__webpack_require__.n(lodash_noconflict);

// EXTERNAL MODULE: ./src/headless/polyfill.js
var polyfill = __webpack_require__(322);

// EXTERNAL MODULE: ./node_modules/strophe.js/src/websocket.js
var websocket = __webpack_require__(65);

// EXTERNAL MODULE: ./node_modules/localforage/dist/localforage.js
var localforage = __webpack_require__(23);

// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheClear.js
/**
 * Removes all key-value entries from the list cache.
 *
 * @private
 * @name clear
 * @memberOf ListCache
 */
function listCacheClear() {
  this.__data__ = [];
  this.size = 0;
}

/* harmony default export */ var _listCacheClear = (listCacheClear);
// CONCATENATED MODULE: ./node_modules/lodash-es/eq.js
/**
 * Performs a
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * comparison between two values to determine if they are equivalent.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.eq(object, object);
 * // => true
 *
 * _.eq(object, other);
 * // => false
 *
 * _.eq('a', 'a');
 * // => true
 *
 * _.eq('a', Object('a'));
 * // => false
 *
 * _.eq(NaN, NaN);
 * // => true
 */
function eq(value, other) {
  return value === other || value !== value && other !== other;
}

/* harmony default export */ var lodash_es_eq = (eq);
// CONCATENATED MODULE: ./node_modules/lodash-es/_assocIndexOf.js

/**
 * Gets the index at which the `key` is found in `array` of key-value pairs.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} key The key to search for.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */

function assocIndexOf(array, key) {
  var length = array.length;

  while (length--) {
    if (lodash_es_eq(array[length][0], key)) {
      return length;
    }
  }

  return -1;
}

/* harmony default export */ var _assocIndexOf = (assocIndexOf);
// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheDelete.js

/** Used for built-in method references. */

var arrayProto = Array.prototype;
/** Built-in value references. */

var splice = arrayProto.splice;
/**
 * Removes `key` and its value from the list cache.
 *
 * @private
 * @name delete
 * @memberOf ListCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */

function listCacheDelete(key) {
  var data = this.__data__,
      index = _assocIndexOf(data, key);

  if (index < 0) {
    return false;
  }

  var lastIndex = data.length - 1;

  if (index == lastIndex) {
    data.pop();
  } else {
    splice.call(data, index, 1);
  }

  --this.size;
  return true;
}

/* harmony default export */ var _listCacheDelete = (listCacheDelete);
// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheGet.js

/**
 * Gets the list cache value for `key`.
 *
 * @private
 * @name get
 * @memberOf ListCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */

function listCacheGet(key) {
  var data = this.__data__,
      index = _assocIndexOf(data, key);
  return index < 0 ? undefined : data[index][1];
}

/* harmony default export */ var _listCacheGet = (listCacheGet);
// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheHas.js

/**
 * Checks if a list cache value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf ListCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */

function listCacheHas(key) {
  return _assocIndexOf(this.__data__, key) > -1;
}

/* harmony default export */ var _listCacheHas = (listCacheHas);
// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheSet.js

/**
 * Sets the list cache `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf ListCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the list cache instance.
 */

function listCacheSet(key, value) {
  var data = this.__data__,
      index = _assocIndexOf(data, key);

  if (index < 0) {
    ++this.size;
    data.push([key, value]);
  } else {
    data[index][1] = value;
  }

  return this;
}

/* harmony default export */ var _listCacheSet = (listCacheSet);
// CONCATENATED MODULE: ./node_modules/lodash-es/_ListCache.js





/**
 * Creates an list cache object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */

function ListCache(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;
  this.clear();

  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
} // Add methods to `ListCache`.


ListCache.prototype.clear = _listCacheClear;
ListCache.prototype['delete'] = _listCacheDelete;
ListCache.prototype.get = _listCacheGet;
ListCache.prototype.has = _listCacheHas;
ListCache.prototype.set = _listCacheSet;
/* harmony default export */ var _ListCache = (ListCache);
// CONCATENATED MODULE: ./node_modules/lodash-es/_stackClear.js

/**
 * Removes all key-value entries from the stack.
 *
 * @private
 * @name clear
 * @memberOf Stack
 */

function stackClear() {
  this.__data__ = new _ListCache();
  this.size = 0;
}

/* harmony default export */ var _stackClear = (stackClear);
// CONCATENATED MODULE: ./node_modules/lodash-es/_stackDelete.js
/**
 * Removes `key` and its value from the stack.
 *
 * @private
 * @name delete
 * @memberOf Stack
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function stackDelete(key) {
  var data = this.__data__,
      result = data['delete'](key);
  this.size = data.size;
  return result;
}

/* harmony default export */ var _stackDelete = (stackDelete);
// CONCATENATED MODULE: ./node_modules/lodash-es/_stackGet.js
/**
 * Gets the stack value for `key`.
 *
 * @private
 * @name get
 * @memberOf Stack
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function stackGet(key) {
  return this.__data__.get(key);
}

/* harmony default export */ var _stackGet = (stackGet);
// CONCATENATED MODULE: ./node_modules/lodash-es/_stackHas.js
/**
 * Checks if a stack value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Stack
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function stackHas(key) {
  return this.__data__.has(key);
}

/* harmony default export */ var _stackHas = (stackHas);
// EXTERNAL MODULE: ./node_modules/lodash-es/_root.js
var _root = __webpack_require__(4);

// CONCATENATED MODULE: ./node_modules/lodash-es/_Symbol.js

/** Built-in value references. */

var _Symbol_Symbol = _root["a" /* default */].Symbol;
/* harmony default export */ var _Symbol = (_Symbol_Symbol);
// CONCATENATED MODULE: ./node_modules/lodash-es/_getRawTag.js

/** Used for built-in method references. */

var objectProto = Object.prototype;
/** Used to check objects for own properties. */

var _getRawTag_hasOwnProperty = objectProto.hasOwnProperty;
/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */

var nativeObjectToString = objectProto.toString;
/** Built-in value references. */

var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
/**
 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the raw `toStringTag`.
 */

function getRawTag(value) {
  var isOwn = _getRawTag_hasOwnProperty.call(value, symToStringTag),
      tag = value[symToStringTag];

  try {
    value[symToStringTag] = undefined;
    var unmasked = true;
  } catch (e) {}

  var result = nativeObjectToString.call(value);

  if (unmasked) {
    if (isOwn) {
      value[symToStringTag] = tag;
    } else {
      delete value[symToStringTag];
    }
  }

  return result;
}

/* harmony default export */ var _getRawTag = (getRawTag);
// CONCATENATED MODULE: ./node_modules/lodash-es/_objectToString.js
/** Used for built-in method references. */
var _objectToString_objectProto = Object.prototype;
/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */

var _objectToString_nativeObjectToString = _objectToString_objectProto.toString;
/**
 * Converts `value` to a string using `Object.prototype.toString`.
 *
 * @private
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 */

function objectToString(value) {
  return _objectToString_nativeObjectToString.call(value);
}

/* harmony default export */ var _objectToString = (objectToString);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseGetTag.js



/** `Object#toString` result references. */

var nullTag = '[object Null]',
    undefinedTag = '[object Undefined]';
/** Built-in value references. */

var _baseGetTag_symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
/**
 * The base implementation of `getTag` without fallbacks for buggy environments.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */

function baseGetTag(value) {
  if (value == null) {
    return value === undefined ? undefinedTag : nullTag;
  }

  return _baseGetTag_symToStringTag && _baseGetTag_symToStringTag in Object(value) ? _getRawTag(value) : _objectToString(value);
}

/* harmony default export */ var _baseGetTag = (baseGetTag);
// CONCATENATED MODULE: ./node_modules/lodash-es/isObject.js
/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function isObject(value) {
  var type = typeof value;
  return value != null && (type == 'object' || type == 'function');
}

/* harmony default export */ var lodash_es_isObject = (isObject);
// CONCATENATED MODULE: ./node_modules/lodash-es/isFunction.js


/** `Object#toString` result references. */

var asyncTag = '[object AsyncFunction]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]',
    proxyTag = '[object Proxy]';
/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */

function isFunction(value) {
  if (!lodash_es_isObject(value)) {
    return false;
  } // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 9 which returns 'object' for typed arrays and other constructors.


  var tag = _baseGetTag(value);
  return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}

/* harmony default export */ var lodash_es_isFunction = (isFunction);
// CONCATENATED MODULE: ./node_modules/lodash-es/_coreJsData.js

/** Used to detect overreaching core-js shims. */

var coreJsData = _root["a" /* default */]['__core-js_shared__'];
/* harmony default export */ var _coreJsData = (coreJsData);
// CONCATENATED MODULE: ./node_modules/lodash-es/_isMasked.js

/** Used to detect methods masquerading as native. */

var maskSrcKey = function () {
  var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
  return uid ? 'Symbol(src)_1.' + uid : '';
}();
/**
 * Checks if `func` has its source masked.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
 */


function isMasked(func) {
  return !!maskSrcKey && maskSrcKey in func;
}

/* harmony default export */ var _isMasked = (isMasked);
// CONCATENATED MODULE: ./node_modules/lodash-es/_toSource.js
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */

var funcToString = funcProto.toString;
/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to convert.
 * @returns {string} Returns the source code.
 */

function toSource(func) {
  if (func != null) {
    try {
      return funcToString.call(func);
    } catch (e) {}

    try {
      return func + '';
    } catch (e) {}
  }

  return '';
}

/* harmony default export */ var _toSource = (toSource);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsNative.js




/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */

var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */

var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */

var _baseIsNative_funcProto = Function.prototype,
    _baseIsNative_objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */

var _baseIsNative_funcToString = _baseIsNative_funcProto.toString;
/** Used to check objects for own properties. */

var _baseIsNative_hasOwnProperty = _baseIsNative_objectProto.hasOwnProperty;
/** Used to detect if a method is native. */

var reIsNative = RegExp('^' + _baseIsNative_funcToString.call(_baseIsNative_hasOwnProperty).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
/**
 * The base implementation of `_.isNative` without bad shim checks.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function,
 *  else `false`.
 */

function baseIsNative(value) {
  if (!lodash_es_isObject(value) || _isMasked(value)) {
    return false;
  }

  var pattern = lodash_es_isFunction(value) ? reIsNative : reIsHostCtor;
  return pattern.test(_toSource(value));
}

/* harmony default export */ var _baseIsNative = (baseIsNative);
// CONCATENATED MODULE: ./node_modules/lodash-es/_getValue.js
/**
 * Gets the value at `key` of `object`.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function getValue(object, key) {
  return object == null ? undefined : object[key];
}

/* harmony default export */ var _getValue = (getValue);
// CONCATENATED MODULE: ./node_modules/lodash-es/_getNative.js


/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */

function getNative(object, key) {
  var value = _getValue(object, key);
  return _baseIsNative(value) ? value : undefined;
}

/* harmony default export */ var _getNative = (getNative);
// CONCATENATED MODULE: ./node_modules/lodash-es/_Map.js


/* Built-in method references that are verified to be native. */

var _Map_Map = _getNative(_root["a" /* default */], 'Map');
/* harmony default export */ var _Map = (_Map_Map);
// CONCATENATED MODULE: ./node_modules/lodash-es/_nativeCreate.js

/* Built-in method references that are verified to be native. */

var nativeCreate = _getNative(Object, 'create');
/* harmony default export */ var _nativeCreate = (nativeCreate);
// CONCATENATED MODULE: ./node_modules/lodash-es/_hashClear.js

/**
 * Removes all key-value entries from the hash.
 *
 * @private
 * @name clear
 * @memberOf Hash
 */

function hashClear() {
  this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
  this.size = 0;
}

/* harmony default export */ var _hashClear = (hashClear);
// CONCATENATED MODULE: ./node_modules/lodash-es/_hashDelete.js
/**
 * Removes `key` and its value from the hash.
 *
 * @private
 * @name delete
 * @memberOf Hash
 * @param {Object} hash The hash to modify.
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function hashDelete(key) {
  var result = this.has(key) && delete this.__data__[key];
  this.size -= result ? 1 : 0;
  return result;
}

/* harmony default export */ var _hashDelete = (hashDelete);
// CONCATENATED MODULE: ./node_modules/lodash-es/_hashGet.js

/** Used to stand-in for `undefined` hash values. */

var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */

var _hashGet_objectProto = Object.prototype;
/** Used to check objects for own properties. */

var _hashGet_hasOwnProperty = _hashGet_objectProto.hasOwnProperty;
/**
 * Gets the hash value for `key`.
 *
 * @private
 * @name get
 * @memberOf Hash
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */

function hashGet(key) {
  var data = this.__data__;

  if (_nativeCreate) {
    var result = data[key];
    return result === HASH_UNDEFINED ? undefined : result;
  }

  return _hashGet_hasOwnProperty.call(data, key) ? data[key] : undefined;
}

/* harmony default export */ var _hashGet = (hashGet);
// CONCATENATED MODULE: ./node_modules/lodash-es/_hashHas.js

/** Used for built-in method references. */

var _hashHas_objectProto = Object.prototype;
/** Used to check objects for own properties. */

var _hashHas_hasOwnProperty = _hashHas_objectProto.hasOwnProperty;
/**
 * Checks if a hash value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Hash
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */

function hashHas(key) {
  var data = this.__data__;
  return _nativeCreate ? data[key] !== undefined : _hashHas_hasOwnProperty.call(data, key);
}

/* harmony default export */ var _hashHas = (hashHas);
// CONCATENATED MODULE: ./node_modules/lodash-es/_hashSet.js

/** Used to stand-in for `undefined` hash values. */

var _hashSet_HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
 * Sets the hash `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Hash
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the hash instance.
 */

function hashSet(key, value) {
  var data = this.__data__;
  this.size += this.has(key) ? 0 : 1;
  data[key] = _nativeCreate && value === undefined ? _hashSet_HASH_UNDEFINED : value;
  return this;
}

/* harmony default export */ var _hashSet = (hashSet);
// CONCATENATED MODULE: ./node_modules/lodash-es/_Hash.js





/**
 * Creates a hash object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */

function Hash(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;
  this.clear();

  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
} // Add methods to `Hash`.


Hash.prototype.clear = _hashClear;
Hash.prototype['delete'] = _hashDelete;
Hash.prototype.get = _hashGet;
Hash.prototype.has = _hashHas;
Hash.prototype.set = _hashSet;
/* harmony default export */ var _Hash = (Hash);
// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheClear.js



/**
 * Removes all key-value entries from the map.
 *
 * @private
 * @name clear
 * @memberOf MapCache
 */

function mapCacheClear() {
  this.size = 0;
  this.__data__ = {
    'hash': new _Hash(),
    'map': new (_Map || _ListCache)(),
    'string': new _Hash()
  };
}

/* harmony default export */ var _mapCacheClear = (mapCacheClear);
// CONCATENATED MODULE: ./node_modules/lodash-es/_isKeyable.js
/**
 * Checks if `value` is suitable for use as unique object key.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
 */
function isKeyable(value) {
  var type = typeof value;
  return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
}

/* harmony default export */ var _isKeyable = (isKeyable);
// CONCATENATED MODULE: ./node_modules/lodash-es/_getMapData.js

/**
 * Gets the data for `map`.
 *
 * @private
 * @param {Object} map The map to query.
 * @param {string} key The reference key.
 * @returns {*} Returns the map data.
 */

function getMapData(map, key) {
  var data = map.__data__;
  return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
}

/* harmony default export */ var _getMapData = (getMapData);
// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheDelete.js

/**
 * Removes `key` and its value from the map.
 *
 * @private
 * @name delete
 * @memberOf MapCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */

function mapCacheDelete(key) {
  var result = _getMapData(this, key)['delete'](key);
  this.size -= result ? 1 : 0;
  return result;
}

/* harmony default export */ var _mapCacheDelete = (mapCacheDelete);
// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheGet.js

/**
 * Gets the map value for `key`.
 *
 * @private
 * @name get
 * @memberOf MapCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */

function mapCacheGet(key) {
  return _getMapData(this, key).get(key);
}

/* harmony default export */ var _mapCacheGet = (mapCacheGet);
// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheHas.js

/**
 * Checks if a map value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf MapCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */

function mapCacheHas(key) {
  return _getMapData(this, key).has(key);
}

/* harmony default export */ var _mapCacheHas = (mapCacheHas);
// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheSet.js

/**
 * Sets the map `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf MapCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the map cache instance.
 */

function mapCacheSet(key, value) {
  var data = _getMapData(this, key),
      size = data.size;
  data.set(key, value);
  this.size += data.size == size ? 0 : 1;
  return this;
}

/* harmony default export */ var _mapCacheSet = (mapCacheSet);
// CONCATENATED MODULE: ./node_modules/lodash-es/_MapCache.js





/**
 * Creates a map cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */

function MapCache(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;
  this.clear();

  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
} // Add methods to `MapCache`.


MapCache.prototype.clear = _mapCacheClear;
MapCache.prototype['delete'] = _mapCacheDelete;
MapCache.prototype.get = _mapCacheGet;
MapCache.prototype.has = _mapCacheHas;
MapCache.prototype.set = _mapCacheSet;
/* harmony default export */ var _MapCache = (MapCache);
// CONCATENATED MODULE: ./node_modules/lodash-es/_stackSet.js



/** Used as the size to enable large array optimizations. */

var LARGE_ARRAY_SIZE = 200;
/**
 * Sets the stack `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Stack
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the stack cache instance.
 */

function stackSet(key, value) {
  var data = this.__data__;

  if (data instanceof _ListCache) {
    var pairs = data.__data__;

    if (!_Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
      pairs.push([key, value]);
      this.size = ++data.size;
      return this;
    }

    data = this.__data__ = new _MapCache(pairs);
  }

  data.set(key, value);
  this.size = data.size;
  return this;
}

/* harmony default export */ var _stackSet = (stackSet);
// CONCATENATED MODULE: ./node_modules/lodash-es/_Stack.js






/**
 * Creates a stack cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */

function Stack(entries) {
  var data = this.__data__ = new _ListCache(entries);
  this.size = data.size;
} // Add methods to `Stack`.


Stack.prototype.clear = _stackClear;
Stack.prototype['delete'] = _stackDelete;
Stack.prototype.get = _stackGet;
Stack.prototype.has = _stackHas;
Stack.prototype.set = _stackSet;
/* harmony default export */ var _Stack = (Stack);
// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayEach.js
/**
 * A specialized version of `_.forEach` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns `array`.
 */
function arrayEach(array, iteratee) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    if (iteratee(array[index], index, array) === false) {
      break;
    }
  }

  return array;
}

/* harmony default export */ var _arrayEach = (arrayEach);
// CONCATENATED MODULE: ./node_modules/lodash-es/_defineProperty.js


var defineProperty = function () {
  try {
    var func = _getNative(Object, 'defineProperty');
    func({}, '', {});
    return func;
  } catch (e) {}
}();

/* harmony default export */ var _defineProperty = (defineProperty);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseAssignValue.js

/**
 * The base implementation of `assignValue` and `assignMergeValue` without
 * value checks.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */

function baseAssignValue(object, key, value) {
  if (key == '__proto__' && _defineProperty) {
    _defineProperty(object, key, {
      'configurable': true,
      'enumerable': true,
      'value': value,
      'writable': true
    });
  } else {
    object[key] = value;
  }
}

/* harmony default export */ var _baseAssignValue = (baseAssignValue);
// CONCATENATED MODULE: ./node_modules/lodash-es/_assignValue.js


/** Used for built-in method references. */

var _assignValue_objectProto = Object.prototype;
/** Used to check objects for own properties. */

var _assignValue_hasOwnProperty = _assignValue_objectProto.hasOwnProperty;
/**
 * Assigns `value` to `key` of `object` if the existing value is not equivalent
 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */

function assignValue(object, key, value) {
  var objValue = object[key];

  if (!(_assignValue_hasOwnProperty.call(object, key) && lodash_es_eq(objValue, value)) || value === undefined && !(key in object)) {
    _baseAssignValue(object, key, value);
  }
}

/* harmony default export */ var _assignValue = (assignValue);
// CONCATENATED MODULE: ./node_modules/lodash-es/_copyObject.js


/**
 * Copies properties of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy properties from.
 * @param {Array} props The property identifiers to copy.
 * @param {Object} [object={}] The object to copy properties to.
 * @param {Function} [customizer] The function to customize copied values.
 * @returns {Object} Returns `object`.
 */

function copyObject(source, props, object, customizer) {
  var isNew = !object;
  object || (object = {});
  var index = -1,
      length = props.length;

  while (++index < length) {
    var key = props[index];
    var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined;

    if (newValue === undefined) {
      newValue = source[key];
    }

    if (isNew) {
      _baseAssignValue(object, key, newValue);
    } else {
      _assignValue(object, key, newValue);
    }
  }

  return object;
}

/* harmony default export */ var _copyObject = (copyObject);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseTimes.js
/**
 * The base implementation of `_.times` without support for iteratee shorthands
 * or max array length checks.
 *
 * @private
 * @param {number} n The number of times to invoke `iteratee`.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the array of results.
 */
function baseTimes(n, iteratee) {
  var index = -1,
      result = Array(n);

  while (++index < n) {
    result[index] = iteratee(index);
  }

  return result;
}

/* harmony default export */ var _baseTimes = (baseTimes);
// CONCATENATED MODULE: ./node_modules/lodash-es/isObjectLike.js
/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return value != null && typeof value == 'object';
}

/* harmony default export */ var lodash_es_isObjectLike = (isObjectLike);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsArguments.js


/** `Object#toString` result references. */

var argsTag = '[object Arguments]';
/**
 * The base implementation of `_.isArguments`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 */

function baseIsArguments(value) {
  return lodash_es_isObjectLike(value) && _baseGetTag(value) == argsTag;
}

/* harmony default export */ var _baseIsArguments = (baseIsArguments);
// CONCATENATED MODULE: ./node_modules/lodash-es/isArguments.js


/** Used for built-in method references. */

var isArguments_objectProto = Object.prototype;
/** Used to check objects for own properties. */

var isArguments_hasOwnProperty = isArguments_objectProto.hasOwnProperty;
/** Built-in value references. */

var propertyIsEnumerable = isArguments_objectProto.propertyIsEnumerable;
/**
 * Checks if `value` is likely an `arguments` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 *  else `false`.
 * @example
 *
 * _.isArguments(function() { return arguments; }());
 * // => true
 *
 * _.isArguments([1, 2, 3]);
 * // => false
 */

var isArguments = _baseIsArguments(function () {
  return arguments;
}()) ? _baseIsArguments : function (value) {
  return lodash_es_isObjectLike(value) && isArguments_hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
};
/* harmony default export */ var lodash_es_isArguments = (isArguments);
// CONCATENATED MODULE: ./node_modules/lodash-es/isArray.js
/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
 * @example
 *
 * _.isArray([1, 2, 3]);
 * // => true
 *
 * _.isArray(document.body.children);
 * // => false
 *
 * _.isArray('abc');
 * // => false
 *
 * _.isArray(_.noop);
 * // => false
 */
var isArray = Array.isArray;
/* harmony default export */ var lodash_es_isArray = (isArray);
// EXTERNAL MODULE: ./node_modules/lodash-es/isBuffer.js
var isBuffer = __webpack_require__(17);

// CONCATENATED MODULE: ./node_modules/lodash-es/_isIndex.js
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used to detect unsigned integer values. */

var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
 * Checks if `value` is a valid array-like index.
 *
 * @private
 * @param {*} value The value to check.
 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
 */

function isIndex(value, length) {
  var type = typeof value;
  length = length == null ? MAX_SAFE_INTEGER : length;
  return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
}

/* harmony default export */ var _isIndex = (isIndex);
// CONCATENATED MODULE: ./node_modules/lodash-es/isLength.js
/** Used as references for various `Number` constants. */
var isLength_MAX_SAFE_INTEGER = 9007199254740991;
/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */

function isLength(value) {
  return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= isLength_MAX_SAFE_INTEGER;
}

/* harmony default export */ var lodash_es_isLength = (isLength);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsTypedArray.js



/** `Object#toString` result references. */

var _baseIsTypedArray_argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    _baseIsTypedArray_funcTag = '[object Function]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    objectTag = '[object Object]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
    dataViewTag = '[object DataView]',
    float32Tag = '[object Float32Array]',
    float64Tag = '[object Float64Array]',
    int8Tag = '[object Int8Array]',
    int16Tag = '[object Int16Array]',
    int32Tag = '[object Int32Array]',
    uint8Tag = '[object Uint8Array]',
    uint8ClampedTag = '[object Uint8ClampedArray]',
    uint16Tag = '[object Uint16Array]',
    uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */

var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
typedArrayTags[_baseIsTypedArray_argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[_baseIsTypedArray_funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
/**
 * The base implementation of `_.isTypedArray` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 */

function baseIsTypedArray(value) {
  return lodash_es_isObjectLike(value) && lodash_es_isLength(value.length) && !!typedArrayTags[_baseGetTag(value)];
}

/* harmony default export */ var _baseIsTypedArray = (baseIsTypedArray);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseUnary.js
/**
 * The base implementation of `_.unary` without support for storing metadata.
 *
 * @private
 * @param {Function} func The function to cap arguments for.
 * @returns {Function} Returns the new capped function.
 */
function baseUnary(func) {
  return function (value) {
    return func(value);
  };
}

/* harmony default export */ var _baseUnary = (baseUnary);
// EXTERNAL MODULE: ./node_modules/lodash-es/_nodeUtil.js
var _nodeUtil = __webpack_require__(11);

// CONCATENATED MODULE: ./node_modules/lodash-es/isTypedArray.js



/* Node.js helper references. */

var nodeIsTypedArray = _nodeUtil["a" /* default */] && _nodeUtil["a" /* default */].isTypedArray;
/**
 * Checks if `value` is classified as a typed array.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 * @example
 *
 * _.isTypedArray(new Uint8Array);
 * // => true
 *
 * _.isTypedArray([]);
 * // => false
 */

var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
/* harmony default export */ var lodash_es_isTypedArray = (isTypedArray);
// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayLikeKeys.js






/** Used for built-in method references. */

var _arrayLikeKeys_objectProto = Object.prototype;
/** Used to check objects for own properties. */

var _arrayLikeKeys_hasOwnProperty = _arrayLikeKeys_objectProto.hasOwnProperty;
/**
 * Creates an array of the enumerable property names of the array-like `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @param {boolean} inherited Specify returning inherited property names.
 * @returns {Array} Returns the array of property names.
 */

function arrayLikeKeys(value, inherited) {
  var isArr = lodash_es_isArray(value),
      isArg = !isArr && lodash_es_isArguments(value),
      isBuff = !isArr && !isArg && Object(isBuffer["a" /* default */])(value),
      isType = !isArr && !isArg && !isBuff && lodash_es_isTypedArray(value),
      skipIndexes = isArr || isArg || isBuff || isType,
      result = skipIndexes ? _baseTimes(value.length, String) : [],
      length = result.length;

  for (var key in value) {
    if ((inherited || _arrayLikeKeys_hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode.
    key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers.
    isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays.
    isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties.
    _isIndex(key, length)))) {
      result.push(key);
    }
  }

  return result;
}

/* harmony default export */ var _arrayLikeKeys = (arrayLikeKeys);
// CONCATENATED MODULE: ./node_modules/lodash-es/_isPrototype.js
/** Used for built-in method references. */
var _isPrototype_objectProto = Object.prototype;
/**
 * Checks if `value` is likely a prototype object.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
 */

function isPrototype(value) {
  var Ctor = value && value.constructor,
      proto = typeof Ctor == 'function' && Ctor.prototype || _isPrototype_objectProto;
  return value === proto;
}

/* harmony default export */ var _isPrototype = (isPrototype);
// CONCATENATED MODULE: ./node_modules/lodash-es/_overArg.js
/**
 * Creates a unary function that invokes `func` with its argument transformed.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {Function} transform The argument transform.
 * @returns {Function} Returns the new function.
 */
function overArg(func, transform) {
  return function (arg) {
    return func(transform(arg));
  };
}

/* harmony default export */ var _overArg = (overArg);
// CONCATENATED MODULE: ./node_modules/lodash-es/_nativeKeys.js

/* Built-in method references for those with the same name as other `lodash` methods. */

var nativeKeys = _overArg(Object.keys, Object);
/* harmony default export */ var _nativeKeys = (nativeKeys);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseKeys.js


/** Used for built-in method references. */

var _baseKeys_objectProto = Object.prototype;
/** Used to check objects for own properties. */

var _baseKeys_hasOwnProperty = _baseKeys_objectProto.hasOwnProperty;
/**
 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */

function baseKeys(object) {
  if (!_isPrototype(object)) {
    return _nativeKeys(object);
  }

  var result = [];

  for (var key in Object(object)) {
    if (_baseKeys_hasOwnProperty.call(object, key) && key != 'constructor') {
      result.push(key);
    }
  }

  return result;
}

/* harmony default export */ var _baseKeys = (baseKeys);
// CONCATENATED MODULE: ./node_modules/lodash-es/isArrayLike.js


/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */

function isArrayLike(value) {
  return value != null && lodash_es_isLength(value.length) && !lodash_es_isFunction(value);
}

/* harmony default export */ var lodash_es_isArrayLike = (isArrayLike);
// CONCATENATED MODULE: ./node_modules/lodash-es/keys.js



/**
 * Creates an array of the own enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects. See the
 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * for more details.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keys(new Foo);
 * // => ['a', 'b'] (iteration order is not guaranteed)
 *
 * _.keys('hi');
 * // => ['0', '1']
 */

function keys_keys(object) {
  return lodash_es_isArrayLike(object) ? _arrayLikeKeys(object) : _baseKeys(object);
}

/* harmony default export */ var lodash_es_keys = (keys_keys);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseAssign.js


/**
 * The base implementation of `_.assign` without support for multiple sources
 * or `customizer` functions.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @returns {Object} Returns `object`.
 */

function baseAssign(object, source) {
  return object && _copyObject(source, lodash_es_keys(source), object);
}

/* harmony default export */ var _baseAssign = (baseAssign);
// CONCATENATED MODULE: ./node_modules/lodash-es/_nativeKeysIn.js
/**
 * This function is like
 * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * except that it includes inherited enumerable properties.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function nativeKeysIn(object) {
  var result = [];

  if (object != null) {
    for (var key in Object(object)) {
      result.push(key);
    }
  }

  return result;
}

/* harmony default export */ var _nativeKeysIn = (nativeKeysIn);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseKeysIn.js



/** Used for built-in method references. */

var _baseKeysIn_objectProto = Object.prototype;
/** Used to check objects for own properties. */

var _baseKeysIn_hasOwnProperty = _baseKeysIn_objectProto.hasOwnProperty;
/**
 * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */

function baseKeysIn(object) {
  if (!lodash_es_isObject(object)) {
    return _nativeKeysIn(object);
  }

  var isProto = _isPrototype(object),
      result = [];

  for (var key in object) {
    if (!(key == 'constructor' && (isProto || !_baseKeysIn_hasOwnProperty.call(object, key)))) {
      result.push(key);
    }
  }

  return result;
}

/* harmony default export */ var _baseKeysIn = (baseKeysIn);
// CONCATENATED MODULE: ./node_modules/lodash-es/keysIn.js



/**
 * Creates an array of the own and inherited enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keysIn(new Foo);
 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
 */

function keysIn(object) {
  return lodash_es_isArrayLike(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
}

/* harmony default export */ var lodash_es_keysIn = (keysIn);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseAssignIn.js


/**
 * The base implementation of `_.assignIn` without support for multiple sources
 * or `customizer` functions.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @returns {Object} Returns `object`.
 */

function baseAssignIn(object, source) {
  return object && _copyObject(source, lodash_es_keysIn(source), object);
}

/* harmony default export */ var _baseAssignIn = (baseAssignIn);
// EXTERNAL MODULE: ./node_modules/lodash-es/_cloneBuffer.js
var _cloneBuffer = __webpack_require__(157);

// CONCATENATED MODULE: ./node_modules/lodash-es/_copyArray.js
/**
 * Copies the values of `source` to `array`.
 *
 * @private
 * @param {Array} source The array to copy values from.
 * @param {Array} [array=[]] The array to copy values to.
 * @returns {Array} Returns `array`.
 */
function copyArray(source, array) {
  var index = -1,
      length = source.length;
  array || (array = Array(length));

  while (++index < length) {
    array[index] = source[index];
  }

  return array;
}

/* harmony default export */ var _copyArray = (copyArray);
// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayFilter.js
/**
 * A specialized version of `_.filter` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 */
function arrayFilter(array, predicate) {
  var index = -1,
      length = array == null ? 0 : array.length,
      resIndex = 0,
      result = [];

  while (++index < length) {
    var value = array[index];

    if (predicate(value, index, array)) {
      result[resIndex++] = value;
    }
  }

  return result;
}

/* harmony default export */ var _arrayFilter = (arrayFilter);
// CONCATENATED MODULE: ./node_modules/lodash-es/stubArray.js
/**
 * This method returns a new empty array.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {Array} Returns the new empty array.
 * @example
 *
 * var arrays = _.times(2, _.stubArray);
 *
 * console.log(arrays);
 * // => [[], []]
 *
 * console.log(arrays[0] === arrays[1]);
 * // => false
 */
function stubArray() {
  return [];
}

/* harmony default export */ var lodash_es_stubArray = (stubArray);
// CONCATENATED MODULE: ./node_modules/lodash-es/_getSymbols.js


/** Used for built-in method references. */

var _getSymbols_objectProto = Object.prototype;
/** Built-in value references. */

var _getSymbols_propertyIsEnumerable = _getSymbols_objectProto.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */

var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
 * Creates an array of the own enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */

var getSymbols = !nativeGetSymbols ? lodash_es_stubArray : function (object) {
  if (object == null) {
    return [];
  }

  object = Object(object);
  return _arrayFilter(nativeGetSymbols(object), function (symbol) {
    return _getSymbols_propertyIsEnumerable.call(object, symbol);
  });
};
/* harmony default export */ var _getSymbols = (getSymbols);
// CONCATENATED MODULE: ./node_modules/lodash-es/_copySymbols.js


/**
 * Copies own symbols of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy symbols from.
 * @param {Object} [object={}] The object to copy symbols to.
 * @returns {Object} Returns `object`.
 */

function copySymbols(source, object) {
  return _copyObject(source, _getSymbols(source), object);
}

/* harmony default export */ var _copySymbols = (copySymbols);
// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayPush.js
/**
 * Appends the elements of `values` to `array`.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {Array} values The values to append.
 * @returns {Array} Returns `array`.
 */
function arrayPush(array, values) {
  var index = -1,
      length = values.length,
      offset = array.length;

  while (++index < length) {
    array[offset + index] = values[index];
  }

  return array;
}

/* harmony default export */ var _arrayPush = (arrayPush);
// CONCATENATED MODULE: ./node_modules/lodash-es/_getPrototype.js

/** Built-in value references. */

var getPrototype = _overArg(Object.getPrototypeOf, Object);
/* harmony default export */ var _getPrototype = (getPrototype);
// CONCATENATED MODULE: ./node_modules/lodash-es/_getSymbolsIn.js




/* Built-in method references for those with the same name as other `lodash` methods. */

var _getSymbolsIn_nativeGetSymbols = Object.getOwnPropertySymbols;
/**
 * Creates an array of the own and inherited enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */

var getSymbolsIn = !_getSymbolsIn_nativeGetSymbols ? lodash_es_stubArray : function (object) {
  var result = [];

  while (object) {
    _arrayPush(result, _getSymbols(object));
    object = _getPrototype(object);
  }

  return result;
};
/* harmony default export */ var _getSymbolsIn = (getSymbolsIn);
// CONCATENATED MODULE: ./node_modules/lodash-es/_copySymbolsIn.js


/**
 * Copies own and inherited symbols of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy symbols from.
 * @param {Object} [object={}] The object to copy symbols to.
 * @returns {Object} Returns `object`.
 */

function copySymbolsIn(source, object) {
  return _copyObject(source, _getSymbolsIn(source), object);
}

/* harmony default export */ var _copySymbolsIn = (copySymbolsIn);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseGetAllKeys.js


/**
 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @param {Function} symbolsFunc The function to get the symbols of `object`.
 * @returns {Array} Returns the array of property names and symbols.
 */

function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  var result = keysFunc(object);
  return lodash_es_isArray(object) ? result : _arrayPush(result, symbolsFunc(object));
}

/* harmony default export */ var _baseGetAllKeys = (baseGetAllKeys);
// CONCATENATED MODULE: ./node_modules/lodash-es/_getAllKeys.js



/**
 * Creates an array of own enumerable property names and symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */

function getAllKeys(object) {
  return _baseGetAllKeys(object, lodash_es_keys, _getSymbols);
}

/* harmony default export */ var _getAllKeys = (getAllKeys);
// CONCATENATED MODULE: ./node_modules/lodash-es/_getAllKeysIn.js



/**
 * Creates an array of own and inherited enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */

function getAllKeysIn(object) {
  return _baseGetAllKeys(object, lodash_es_keysIn, _getSymbolsIn);
}

/* harmony default export */ var _getAllKeysIn = (getAllKeysIn);
// CONCATENATED MODULE: ./node_modules/lodash-es/_DataView.js


/* Built-in method references that are verified to be native. */

var DataView = _getNative(_root["a" /* default */], 'DataView');
/* harmony default export */ var _DataView = (DataView);
// CONCATENATED MODULE: ./node_modules/lodash-es/_Promise.js


/* Built-in method references that are verified to be native. */

var _Promise_Promise = _getNative(_root["a" /* default */], 'Promise');
/* harmony default export */ var _Promise = (_Promise_Promise);
// CONCATENATED MODULE: ./node_modules/lodash-es/_Set.js


/* Built-in method references that are verified to be native. */

var _Set_Set = _getNative(_root["a" /* default */], 'Set');
/* harmony default export */ var _Set = (_Set_Set);
// CONCATENATED MODULE: ./node_modules/lodash-es/_WeakMap.js


/* Built-in method references that are verified to be native. */

var _WeakMap_WeakMap = _getNative(_root["a" /* default */], 'WeakMap');
/* harmony default export */ var _WeakMap = (_WeakMap_WeakMap);
// CONCATENATED MODULE: ./node_modules/lodash-es/_getTag.js







/** `Object#toString` result references. */

var _getTag_mapTag = '[object Map]',
    _getTag_objectTag = '[object Object]',
    promiseTag = '[object Promise]',
    _getTag_setTag = '[object Set]',
    _getTag_weakMapTag = '[object WeakMap]';
var _getTag_dataViewTag = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */

var dataViewCtorString = _toSource(_DataView),
    mapCtorString = _toSource(_Map),
    promiseCtorString = _toSource(_Promise),
    setCtorString = _toSource(_Set),
    weakMapCtorString = _toSource(_WeakMap);
/**
 * Gets the `toStringTag` of `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */

var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.

if (_DataView && getTag(new _DataView(new ArrayBuffer(1))) != _getTag_dataViewTag || _Map && getTag(new _Map()) != _getTag_mapTag || _Promise && getTag(_Promise.resolve()) != promiseTag || _Set && getTag(new _Set()) != _getTag_setTag || _WeakMap && getTag(new _WeakMap()) != _getTag_weakMapTag) {
  getTag = function (value) {
    var result = _baseGetTag(value),
        Ctor = result == _getTag_objectTag ? value.constructor : undefined,
        ctorString = Ctor ? _toSource(Ctor) : '';

    if (ctorString) {
      switch (ctorString) {
        case dataViewCtorString:
          return _getTag_dataViewTag;

        case mapCtorString:
          return _getTag_mapTag;

        case promiseCtorString:
          return promiseTag;

        case setCtorString:
          return _getTag_setTag;

        case weakMapCtorString:
          return _getTag_weakMapTag;
      }
    }

    return result;
  };
}

/* harmony default export */ var _getTag = (getTag);
// CONCATENATED MODULE: ./node_modules/lodash-es/_initCloneArray.js
/** Used for built-in method references. */
var _initCloneArray_objectProto = Object.prototype;
/** Used to check objects for own properties. */

var _initCloneArray_hasOwnProperty = _initCloneArray_objectProto.hasOwnProperty;
/**
 * Initializes an array clone.
 *
 * @private
 * @param {Array} array The array to clone.
 * @returns {Array} Returns the initialized clone.
 */

function initCloneArray(array) {
  var length = array.length,
      result = new array.constructor(length); // Add properties assigned by `RegExp#exec`.

  if (length && typeof array[0] == 'string' && _initCloneArray_hasOwnProperty.call(array, 'index')) {
    result.index = array.index;
    result.input = array.input;
  }

  return result;
}

/* harmony default export */ var _initCloneArray = (initCloneArray);
// CONCATENATED MODULE: ./node_modules/lodash-es/_Uint8Array.js

/** Built-in value references. */

var _Uint8Array_Uint8Array = _root["a" /* default */].Uint8Array;
/* harmony default export */ var _Uint8Array = (_Uint8Array_Uint8Array);
// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneArrayBuffer.js

/**
 * Creates a clone of `arrayBuffer`.
 *
 * @private
 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
 * @returns {ArrayBuffer} Returns the cloned array buffer.
 */

function cloneArrayBuffer(arrayBuffer) {
  var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
  return result;
}

/* harmony default export */ var _cloneArrayBuffer = (cloneArrayBuffer);
// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneDataView.js

/**
 * Creates a clone of `dataView`.
 *
 * @private
 * @param {Object} dataView The data view to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned data view.
 */

function cloneDataView(dataView, isDeep) {
  var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}

/* harmony default export */ var _cloneDataView = (cloneDataView);
// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneRegExp.js
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
 * Creates a clone of `regexp`.
 *
 * @private
 * @param {Object} regexp The regexp to clone.
 * @returns {Object} Returns the cloned regexp.
 */

function cloneRegExp(regexp) {
  var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  result.lastIndex = regexp.lastIndex;
  return result;
}

/* harmony default export */ var _cloneRegExp = (cloneRegExp);
// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneSymbol.js

/** Used to convert symbols to primitives and strings. */

var symbolProto = _Symbol ? _Symbol.prototype : undefined,
    symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
 * Creates a clone of the `symbol` object.
 *
 * @private
 * @param {Object} symbol The symbol object to clone.
 * @returns {Object} Returns the cloned symbol object.
 */

function cloneSymbol(symbol) {
  return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}

/* harmony default export */ var _cloneSymbol = (cloneSymbol);
// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneTypedArray.js

/**
 * Creates a clone of `typedArray`.
 *
 * @private
 * @param {Object} typedArray The typed array to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned typed array.
 */

function cloneTypedArray(typedArray, isDeep) {
  var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}

/* harmony default export */ var _cloneTypedArray = (cloneTypedArray);
// CONCATENATED MODULE: ./node_modules/lodash-es/_initCloneByTag.js





/** `Object#toString` result references. */

var _initCloneByTag_boolTag = '[object Boolean]',
    _initCloneByTag_dateTag = '[object Date]',
    _initCloneByTag_mapTag = '[object Map]',
    _initCloneByTag_numberTag = '[object Number]',
    _initCloneByTag_regexpTag = '[object RegExp]',
    _initCloneByTag_setTag = '[object Set]',
    _initCloneByTag_stringTag = '[object String]',
    symbolTag = '[object Symbol]';
var _initCloneByTag_arrayBufferTag = '[object ArrayBuffer]',
    _initCloneByTag_dataViewTag = '[object DataView]',
    _initCloneByTag_float32Tag = '[object Float32Array]',
    _initCloneByTag_float64Tag = '[object Float64Array]',
    _initCloneByTag_int8Tag = '[object Int8Array]',
    _initCloneByTag_int16Tag = '[object Int16Array]',
    _initCloneByTag_int32Tag = '[object Int32Array]',
    _initCloneByTag_uint8Tag = '[object Uint8Array]',
    _initCloneByTag_uint8ClampedTag = '[object Uint8ClampedArray]',
    _initCloneByTag_uint16Tag = '[object Uint16Array]',
    _initCloneByTag_uint32Tag = '[object Uint32Array]';
/**
 * Initializes an object clone based on its `toStringTag`.
 *
 * **Note:** This function only supports cloning values with tags of
 * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
 *
 * @private
 * @param {Object} object The object to clone.
 * @param {string} tag The `toStringTag` of the object to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the initialized clone.
 */

function initCloneByTag(object, tag, isDeep) {
  var Ctor = object.constructor;

  switch (tag) {
    case _initCloneByTag_arrayBufferTag:
      return _cloneArrayBuffer(object);

    case _initCloneByTag_boolTag:
    case _initCloneByTag_dateTag:
      return new Ctor(+object);

    case _initCloneByTag_dataViewTag:
      return _cloneDataView(object, isDeep);

    case _initCloneByTag_float32Tag:
    case _initCloneByTag_float64Tag:
    case _initCloneByTag_int8Tag:
    case _initCloneByTag_int16Tag:
    case _initCloneByTag_int32Tag:
    case _initCloneByTag_uint8Tag:
    case _initCloneByTag_uint8ClampedTag:
    case _initCloneByTag_uint16Tag:
    case _initCloneByTag_uint32Tag:
      return _cloneTypedArray(object, isDeep);

    case _initCloneByTag_mapTag:
      return new Ctor();

    case _initCloneByTag_numberTag:
    case _initCloneByTag_stringTag:
      return new Ctor(object);

    case _initCloneByTag_regexpTag:
      return _cloneRegExp(object);

    case _initCloneByTag_setTag:
      return new Ctor();

    case symbolTag:
      return _cloneSymbol(object);
  }
}

/* harmony default export */ var _initCloneByTag = (initCloneByTag);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseCreate.js

/** Built-in value references. */

var objectCreate = Object.create;
/**
 * The base implementation of `_.create` without support for assigning
 * properties to the created object.
 *
 * @private
 * @param {Object} proto The object to inherit from.
 * @returns {Object} Returns the new object.
 */

var baseCreate = function () {
  function object() {}

  return function (proto) {
    if (!lodash_es_isObject(proto)) {
      return {};
    }

    if (objectCreate) {
      return objectCreate(proto);
    }

    object.prototype = proto;
    var result = new object();
    object.prototype = undefined;
    return result;
  };
}();

/* harmony default export */ var _baseCreate = (baseCreate);
// CONCATENATED MODULE: ./node_modules/lodash-es/_initCloneObject.js



/**
 * Initializes an object clone.
 *
 * @private
 * @param {Object} object The object to clone.
 * @returns {Object} Returns the initialized clone.
 */

function initCloneObject(object) {
  return typeof object.constructor == 'function' && !_isPrototype(object) ? _baseCreate(_getPrototype(object)) : {};
}

/* harmony default export */ var _initCloneObject = (initCloneObject);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsMap.js


/** `Object#toString` result references. */

var _baseIsMap_mapTag = '[object Map]';
/**
 * The base implementation of `_.isMap` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
 */

function baseIsMap(value) {
  return lodash_es_isObjectLike(value) && _getTag(value) == _baseIsMap_mapTag;
}

/* harmony default export */ var _baseIsMap = (baseIsMap);
// CONCATENATED MODULE: ./node_modules/lodash-es/isMap.js



/* Node.js helper references. */

var nodeIsMap = _nodeUtil["a" /* default */] && _nodeUtil["a" /* default */].isMap;
/**
 * Checks if `value` is classified as a `Map` object.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
 * @example
 *
 * _.isMap(new Map);
 * // => true
 *
 * _.isMap(new WeakMap);
 * // => false
 */

var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap;
/* harmony default export */ var lodash_es_isMap = (isMap);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsSet.js


/** `Object#toString` result references. */

var _baseIsSet_setTag = '[object Set]';
/**
 * The base implementation of `_.isSet` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
 */

function baseIsSet(value) {
  return lodash_es_isObjectLike(value) && _getTag(value) == _baseIsSet_setTag;
}

/* harmony default export */ var _baseIsSet = (baseIsSet);
// CONCATENATED MODULE: ./node_modules/lodash-es/isSet.js



/* Node.js helper references. */

var nodeIsSet = _nodeUtil["a" /* default */] && _nodeUtil["a" /* default */].isSet;
/**
 * Checks if `value` is classified as a `Set` object.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
 * @example
 *
 * _.isSet(new Set);
 * // => true
 *
 * _.isSet(new WeakSet);
 * // => false
 */

var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet;
/* harmony default export */ var lodash_es_isSet = (isSet);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseClone.js






















/** Used to compose bitmasks for cloning. */

var CLONE_DEEP_FLAG = 1,
    CLONE_FLAT_FLAG = 2,
    CLONE_SYMBOLS_FLAG = 4;
/** `Object#toString` result references. */

var _baseClone_argsTag = '[object Arguments]',
    _baseClone_arrayTag = '[object Array]',
    _baseClone_boolTag = '[object Boolean]',
    _baseClone_dateTag = '[object Date]',
    _baseClone_errorTag = '[object Error]',
    _baseClone_funcTag = '[object Function]',
    _baseClone_genTag = '[object GeneratorFunction]',
    _baseClone_mapTag = '[object Map]',
    _baseClone_numberTag = '[object Number]',
    _baseClone_objectTag = '[object Object]',
    _baseClone_regexpTag = '[object RegExp]',
    _baseClone_setTag = '[object Set]',
    _baseClone_stringTag = '[object String]',
    _baseClone_symbolTag = '[object Symbol]',
    _baseClone_weakMapTag = '[object WeakMap]';
var _baseClone_arrayBufferTag = '[object ArrayBuffer]',
    _baseClone_dataViewTag = '[object DataView]',
    _baseClone_float32Tag = '[object Float32Array]',
    _baseClone_float64Tag = '[object Float64Array]',
    _baseClone_int8Tag = '[object Int8Array]',
    _baseClone_int16Tag = '[object Int16Array]',
    _baseClone_int32Tag = '[object Int32Array]',
    _baseClone_uint8Tag = '[object Uint8Array]',
    _baseClone_uint8ClampedTag = '[object Uint8ClampedArray]',
    _baseClone_uint16Tag = '[object Uint16Array]',
    _baseClone_uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values supported by `_.clone`. */

var cloneableTags = {};
cloneableTags[_baseClone_argsTag] = cloneableTags[_baseClone_arrayTag] = cloneableTags[_baseClone_arrayBufferTag] = cloneableTags[_baseClone_dataViewTag] = cloneableTags[_baseClone_boolTag] = cloneableTags[_baseClone_dateTag] = cloneableTags[_baseClone_float32Tag] = cloneableTags[_baseClone_float64Tag] = cloneableTags[_baseClone_int8Tag] = cloneableTags[_baseClone_int16Tag] = cloneableTags[_baseClone_int32Tag] = cloneableTags[_baseClone_mapTag] = cloneableTags[_baseClone_numberTag] = cloneableTags[_baseClone_objectTag] = cloneableTags[_baseClone_regexpTag] = cloneableTags[_baseClone_setTag] = cloneableTags[_baseClone_stringTag] = cloneableTags[_baseClone_symbolTag] = cloneableTags[_baseClone_uint8Tag] = cloneableTags[_baseClone_uint8ClampedTag] = cloneableTags[_baseClone_uint16Tag] = cloneableTags[_baseClone_uint32Tag] = true;
cloneableTags[_baseClone_errorTag] = cloneableTags[_baseClone_funcTag] = cloneableTags[_baseClone_weakMapTag] = false;
/**
 * The base implementation of `_.clone` and `_.cloneDeep` which tracks
 * traversed objects.
 *
 * @private
 * @param {*} value The value to clone.
 * @param {boolean} bitmask The bitmask flags.
 *  1 - Deep clone
 *  2 - Flatten inherited properties
 *  4 - Clone symbols
 * @param {Function} [customizer] The function to customize cloning.
 * @param {string} [key] The key of `value`.
 * @param {Object} [object] The parent object of `value`.
 * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
 * @returns {*} Returns the cloned value.
 */

function baseClone(value, bitmask, customizer, key, object, stack) {
  var result,
      isDeep = bitmask & CLONE_DEEP_FLAG,
      isFlat = bitmask & CLONE_FLAT_FLAG,
      isFull = bitmask & CLONE_SYMBOLS_FLAG;

  if (customizer) {
    result = object ? customizer(value, key, object, stack) : customizer(value);
  }

  if (result !== undefined) {
    return result;
  }

  if (!lodash_es_isObject(value)) {
    return value;
  }

  var isArr = lodash_es_isArray(value);

  if (isArr) {
    result = _initCloneArray(value);

    if (!isDeep) {
      return _copyArray(value, result);
    }
  } else {
    var tag = _getTag(value),
        isFunc = tag == _baseClone_funcTag || tag == _baseClone_genTag;

    if (Object(isBuffer["a" /* default */])(value)) {
      return Object(_cloneBuffer["a" /* default */])(value, isDeep);
    }

    if (tag == _baseClone_objectTag || tag == _baseClone_argsTag || isFunc && !object) {
      result = isFlat || isFunc ? {} : _initCloneObject(value);

      if (!isDeep) {
        return isFlat ? _copySymbolsIn(value, _baseAssignIn(result, value)) : _copySymbols(value, _baseAssign(result, value));
      }
    } else {
      if (!cloneableTags[tag]) {
        return object ? value : {};
      }

      result = _initCloneByTag(value, tag, isDeep);
    }
  } // Check for circular references and return its corresponding clone.


  stack || (stack = new _Stack());
  var stacked = stack.get(value);

  if (stacked) {
    return stacked;
  }

  stack.set(value, result);

  if (lodash_es_isSet(value)) {
    value.forEach(function (subValue) {
      result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
    });
  } else if (lodash_es_isMap(value)) {
    value.forEach(function (subValue, key) {
      result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
    });
  }

  var keysFunc = isFull ? isFlat ? _getAllKeysIn : _getAllKeys : isFlat ? lodash_es_keysIn : lodash_es_keys;
  var props = isArr ? undefined : keysFunc(value);
  _arrayEach(props || value, function (subValue, key) {
    if (props) {
      key = subValue;
      subValue = value[key];
    } // Recursively populate clone (susceptible to call stack limits).


    _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
  });
  return result;
}

/* harmony default export */ var _baseClone = (baseClone);
// CONCATENATED MODULE: ./node_modules/lodash-es/cloneDeep.js

/** Used to compose bitmasks for cloning. */

var cloneDeep_CLONE_DEEP_FLAG = 1,
    cloneDeep_CLONE_SYMBOLS_FLAG = 4;
/**
 * This method is like `_.clone` except that it recursively clones `value`.
 *
 * @static
 * @memberOf _
 * @since 1.0.0
 * @category Lang
 * @param {*} value The value to recursively clone.
 * @returns {*} Returns the deep cloned value.
 * @see _.clone
 * @example
 *
 * var objects = [{ 'a': 1 }, { 'b': 2 }];
 *
 * var deep = _.cloneDeep(objects);
 * console.log(deep[0] === objects[0]);
 * // => false
 */

function cloneDeep(value) {
  return _baseClone(value, cloneDeep_CLONE_DEEP_FLAG | cloneDeep_CLONE_SYMBOLS_FLAG);
}

/* harmony default export */ var lodash_es_cloneDeep = (cloneDeep);
// CONCATENATED MODULE: ./node_modules/lodash-es/isString.js



/** `Object#toString` result references. */

var isString_stringTag = '[object String]';
/**
 * Checks if `value` is classified as a `String` primitive or object.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a string, else `false`.
 * @example
 *
 * _.isString('abc');
 * // => true
 *
 * _.isString(1);
 * // => false
 */

function isString(value) {
  return typeof value == 'string' || !lodash_es_isArray(value) && lodash_es_isObjectLike(value) && _baseGetTag(value) == isString_stringTag;
}

/* harmony default export */ var lodash_es_isString = (isString);
// CONCATENATED MODULE: ./node_modules/localforage/src/utils/executeCallback.js
function executeCallback(promise, callback) {
  if (callback) {
    promise.then(function (result) {
      callback(null, result);
    }, function (error) {
      callback(error);
    });
  }
}

/* harmony default export */ var utils_executeCallback = (executeCallback);
// CONCATENATED MODULE: ./node_modules/localforage/src/utils/getCallback.js
function getCallback() {
  if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
    return arguments[arguments.length - 1];
  }
}
// CONCATENATED MODULE: ./node_modules/localforage/src/utils/normalizeKey.js
function normalizeKey(key) {
  // Cast the key to a string, as that's all we can set as a key.
  if (typeof key !== 'string') {
    console.warn(`${key} used as a key, but it is not a string.`);
    key = String(key);
  }

  return key;
}
// CONCATENATED MODULE: ./node_modules/localforage/src/utils/createBlob.js
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function createBlob(parts, properties) {
  /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
  parts = parts || [];
  properties = properties || {};

  try {
    return new Blob(parts, properties);
  } catch (e) {
    if (e.name !== 'TypeError') {
      throw e;
    }

    var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
    var builder = new Builder();

    for (var i = 0; i < parts.length; i += 1) {
      builder.append(parts[i]);
    }

    return builder.getBlob(properties.type);
  }
}

/* harmony default export */ var utils_createBlob = (createBlob);
// CONCATENATED MODULE: ./node_modules/localforage/src/utils/serializer.js
/* eslint-disable no-bitwise */
 // Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.

var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations!

var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
var serializer_toString = Object.prototype.toString;

function stringToBuffer(serializedString) {
  // Fill the string into a ArrayBuffer.
  var bufferLength = serializedString.length * 0.75;
  var len = serializedString.length;
  var i;
  var p = 0;
  var encoded1, encoded2, encoded3, encoded4;

  if (serializedString[serializedString.length - 1] === '=') {
    bufferLength--;

    if (serializedString[serializedString.length - 2] === '=') {
      bufferLength--;
    }
  }

  var buffer = new ArrayBuffer(bufferLength);
  var bytes = new Uint8Array(buffer);

  for (i = 0; i < len; i += 4) {
    encoded1 = BASE_CHARS.indexOf(serializedString[i]);
    encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
    encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
    encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
    /*jslint bitwise: true */

    bytes[p++] = encoded1 << 2 | encoded2 >> 4;
    bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
    bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
  }

  return buffer;
} // Converts a buffer to a string to store, serialized, in the backend
// storage library.


function bufferToString(buffer) {
  // base64-arraybuffer
  var bytes = new Uint8Array(buffer);
  var base64String = '';
  var i;

  for (i = 0; i < bytes.length; i += 3) {
    /*jslint bitwise: true */
    base64String += BASE_CHARS[bytes[i] >> 2];
    base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
    base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
    base64String += BASE_CHARS[bytes[i + 2] & 63];
  }

  if (bytes.length % 3 === 2) {
    base64String = base64String.substring(0, base64String.length - 1) + '=';
  } else if (bytes.length % 3 === 1) {
    base64String = base64String.substring(0, base64String.length - 2) + '==';
  }

  return base64String;
} // Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.


function serialize(value, callback) {
  var valueType = '';

  if (value) {
    valueType = serializer_toString.call(value);
  } // Cannot use `value instanceof ArrayBuffer` or such here, as these
  // checks fail when running the tests using casper.js...
  //
  // TODO: See why those tests fail and use a better solution.


  if (value && (valueType === '[object ArrayBuffer]' || value.buffer && serializer_toString.call(value.buffer) === '[object ArrayBuffer]')) {
    // Convert binary arrays to a string and prefix the string with
    // a special marker.
    var buffer;
    var marker = SERIALIZED_MARKER;

    if (value instanceof ArrayBuffer) {
      buffer = value;
      marker += TYPE_ARRAYBUFFER;
    } else {
      buffer = value.buffer;

      if (valueType === '[object Int8Array]') {
        marker += TYPE_INT8ARRAY;
      } else if (valueType === '[object Uint8Array]') {
        marker += TYPE_UINT8ARRAY;
      } else if (valueType === '[object Uint8ClampedArray]') {
        marker += TYPE_UINT8CLAMPEDARRAY;
      } else if (valueType === '[object Int16Array]') {
        marker += TYPE_INT16ARRAY;
      } else if (valueType === '[object Uint16Array]') {
        marker += TYPE_UINT16ARRAY;
      } else if (valueType === '[object Int32Array]') {
        marker += TYPE_INT32ARRAY;
      } else if (valueType === '[object Uint32Array]') {
        marker += TYPE_UINT32ARRAY;
      } else if (valueType === '[object Float32Array]') {
        marker += TYPE_FLOAT32ARRAY;
      } else if (valueType === '[object Float64Array]') {
        marker += TYPE_FLOAT64ARRAY;
      } else {
        callback(new Error('Failed to get type for BinaryArray'));
      }
    }

    callback(marker + bufferToString(buffer));
  } else if (valueType === '[object Blob]') {
    // Conver the blob to a binaryArray and then to a string.
    var fileReader = new FileReader();

    fileReader.onload = function () {
      // Backwards-compatible prefix for the blob type.
      var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
      callback(SERIALIZED_MARKER + TYPE_BLOB + str);
    };

    fileReader.readAsArrayBuffer(value);
  } else {
    try {
      callback(JSON.stringify(value));
    } catch (e) {
      console.error("Couldn't convert value into a JSON string: ", value);
      callback(null, e);
    }
  }
} // Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.


function deserialize(value) {
  // If we haven't marked this string as being specially serialized (i.e.
  // something other than serialized JSON), we can just return it and be
  // done with it.
  if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
    return JSON.parse(value);
  } // The following code deals with deserializing some kind of Blob or
  // TypedArray. First we separate out the type of data we're dealing
  // with from the data itself.


  var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
  var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
  var blobType; // Backwards-compatible blob type serialization strategy.
  // DBs created with older versions of localForage will simply not have the blob type.

  if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
    var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
    blobType = matcher[1];
    serializedString = serializedString.substring(matcher[0].length);
  }

  var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during
  // serialization.

  switch (type) {
    case TYPE_ARRAYBUFFER:
      return buffer;

    case TYPE_BLOB:
      return utils_createBlob([buffer], {
        type: blobType
      });

    case TYPE_INT8ARRAY:
      return new Int8Array(buffer);

    case TYPE_UINT8ARRAY:
      return new Uint8Array(buffer);

    case TYPE_UINT8CLAMPEDARRAY:
      return new Uint8ClampedArray(buffer);

    case TYPE_INT16ARRAY:
      return new Int16Array(buffer);

    case TYPE_UINT16ARRAY:
      return new Uint16Array(buffer);

    case TYPE_INT32ARRAY:
      return new Int32Array(buffer);

    case TYPE_UINT32ARRAY:
      return new Uint32Array(buffer);

    case TYPE_FLOAT32ARRAY:
      return new Float32Array(buffer);

    case TYPE_FLOAT64ARRAY:
      return new Float64Array(buffer);

    default:
      throw new Error('Unkown type: ' + type);
  }
}

var localforageSerializer = {
  serialize: serialize,
  deserialize: deserialize,
  stringToBuffer: stringToBuffer,
  bufferToString: bufferToString
};
/* harmony default export */ var serializer = (localforageSerializer);
// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/drivers/sessionStorage.js
// Copyright 2014 Mozilla
// Copyright 2015 Thodoris Greasidis
// Copyright 2018 JC Brand
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.




const sessionStorage_serialize = serializer["serialize"];
const sessionStorage_deserialize = serializer["deserialize"];

function isSessionStorageValid() {
  // If the app is running inside a Google Chrome packaged webapp, or some
  // other context where sessionStorage isn't available, we don't use
  // sessionStorage. This feature detection is preferred over the old
  // `if (window.chrome && window.chrome.runtime)` code.
  // See: https://github.com/mozilla/localForage/issues/68
  try {
    // If sessionStorage isn't available, we get outta here!
    // This should be inside a try catch
    if (sessionStorage && 'setItem' in sessionStorage) {
      return true;
    }
  } catch (e) {
    console.log(e);
  }

  return false;
}

function _getKeyPrefix(options, defaultConfig) {
  let keyPrefix = options.name + '/';

  if (options.storeName !== defaultConfig.storeName) {
    keyPrefix += options.storeName + '/';
  }

  return keyPrefix;
}

const dbInfo = {
  'serializer': {
    'serialize': sessionStorage_serialize,
    'deserialize': sessionStorage_deserialize
  }
};

function _initStorage(options) {
  dbInfo.keyPrefix = _getKeyPrefix(options, this._defaultConfig);

  if (options) {
    for (const i in options) {
      // eslint-disable-line guard-for-in
      dbInfo[i] = options[i];
    }
  }
} // Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!


function clear(callback) {
  const promise = this.ready().then(function () {
    const keyPrefix = dbInfo.keyPrefix;

    for (let i = sessionStorage.length - 1; i >= 0; i--) {
      const key = sessionStorage.key(i);

      if (key.indexOf(keyPrefix) === 0) {
        sessionStorage.removeItem(key);
      }
    }
  });
  utils_executeCallback(promise, callback);
  return promise;
} // Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.


function getItem(key, callback) {
  key = normalizeKey(key);
  const promise = this.ready().then(function () {
    let result = sessionStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized
    // string into a JS object. If result isn't truthy, the key
    // is likely undefined and we'll pass it straight to the
    // callback.

    if (result) {
      result = dbInfo.serializer.deserialize(result);
    }

    return result;
  });
  utils_executeCallback(promise, callback);
  return promise;
} // Iterate over all items in the store.


function iterate(iterator, callback) {
  const self = this;
  const promise = self.ready().then(function () {
    const keyPrefix = dbInfo.keyPrefix;
    const keyPrefixLength = keyPrefix.length;
    const length = sessionStorage.length; // We use a dedicated iterator instead of the `i` variable below
    // so other keys we fetch in sessionStorage aren't counted in
    // the `iterationNumber` argument passed to the `iterate()`
    // callback.
    //
    // See: github.com/mozilla/localForage/pull/435#discussion_r38061530

    let iterationNumber = 1;

    for (let i = 0; i < length; i++) {
      const key = sessionStorage.key(i);

      if (key.indexOf(keyPrefix) !== 0) {
        continue;
      }

      let value = sessionStorage.getItem(key); // If a result was found, parse it from the serialized
      // string into a JS object. If result isn't truthy, the
      // key is likely undefined and we'll pass it straight
      // to the iterator.

      if (value) {
        value = dbInfo.serializer.deserialize(value);
      }

      value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);

      if (value !== void 0) {
        // eslint-disable-line no-void
        return value;
      }
    }
  });
  utils_executeCallback(promise, callback);
  return promise;
} // Same as sessionStorage's key() method, except takes a callback.


function sessionStorage_key(n, callback) {
  const self = this;
  const promise = self.ready().then(function () {
    let result;

    try {
      result = sessionStorage.key(n);
    } catch (error) {
      result = null;
    } // Remove the prefix from the key, if a key is found.


    if (result) {
      result = result.substring(dbInfo.keyPrefix.length);
    }

    return result;
  });
  utils_executeCallback(promise, callback);
  return promise;
}

function sessionStorage_keys(callback) {
  const self = this;
  const promise = self.ready().then(function () {
    const length = sessionStorage.length;
    const keys = [];

    for (let i = 0; i < length; i++) {
      const itemKey = sessionStorage.key(i);

      if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
        keys.push(itemKey.substring(dbInfo.keyPrefix.length));
      }
    }

    return keys;
  });
  utils_executeCallback(promise, callback);
  return promise;
} // Supply the number of keys in the datastore to the callback function.


function sessionStorage_length(callback) {
  const self = this;
  const promise = self.keys().then(function (keys) {
    return keys.length;
  });
  utils_executeCallback(promise, callback);
  return promise;
} // Remove an item from the store, nice and simple.


function removeItem(key, callback) {
  key = normalizeKey(key);
  const promise = this.ready().then(function () {
    sessionStorage.removeItem(dbInfo.keyPrefix + key);
  });
  utils_executeCallback(promise, callback);
  return promise;
} // Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.


function setItem(key, value, callback) {
  key = normalizeKey(key);
  const promise = this.ready().then(function () {
    // Convert undefined values to null.
    // https://github.com/mozilla/localForage/pull/42
    if (value === undefined) {
      value = null;
    } // Save the original value to pass to the callback.


    const originalValue = value;
    return new Promise(function (resolve, reject) {
      dbInfo.serializer.serialize(value, function (value, error) {
        if (error) {
          reject(error);
        } else {
          try {
            sessionStorage.setItem(dbInfo.keyPrefix + key, value);
            resolve(originalValue);
          } catch (e) {
            // sessionStorage capacity exceeded.
            // TODO: Make this a specific error/event.
            if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
              reject(e);
            }

            reject(e);
          }
        }
      });
    });
  });
  utils_executeCallback(promise, callback);
  return promise;
}

function dropInstance(options, callback) {
  callback = getCallback.apply(this, arguments);
  options = typeof options !== 'function' && options || {};

  if (!options.name) {
    const currentConfig = this.config();
    options.name = options.name || currentConfig.name;
    options.storeName = options.storeName || currentConfig.storeName;
  }

  const self = this;
  let promise;

  if (!options.name) {
    promise = Promise.reject(new Error('Invalid arguments'));
  } else {
    promise = new Promise(function (resolve) {
      if (!options.storeName) {
        resolve(`${options.name}/`);
      } else {
        resolve(_getKeyPrefix(options, self._defaultConfig));
      }
    }).then(function (keyPrefix) {
      for (let i = sessionStorage.length - 1; i >= 0; i--) {
        const key = sessionStorage.key(i);

        if (key.indexOf(keyPrefix) === 0) {
          sessionStorage.removeItem(key);
        }
      }
    });
  }

  utils_executeCallback(promise, callback);
  return promise;
}

const sessionStorageWrapper = {
  _driver: 'sessionStorageWrapper',
  _initStorage: _initStorage,
  _support: isSessionStorageValid(),
  iterate: iterate,
  getItem: getItem,
  setItem: setItem,
  removeItem: removeItem,
  clear: clear,
  length: sessionStorage_length,
  key: sessionStorage_key,
  keys: sessionStorage_keys,
  dropInstance: dropInstance
};
/* harmony default export */ var drivers_sessionStorage = (sessionStorageWrapper);
// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/storage.js
/**
 * IndexedDB, localStorage and sessionStorage adapter
 */






function S4() {
  // Generate four random hex digits.
  return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);
}

function guid() {
  // Generate a pseudo-GUID by concatenating random hexadecimal.
  return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4();
}

class storage_Storage {
  constructor(name, type) {
    if (type === 'local' && !window.localStorage) {
      throw new Error("Skeletor.storage: Environment does not support localStorage.");
    } else if (type === 'session' && !window.sessionStorage) {
      throw new Error("Skeletor.storage: Environment does not support sessionStorage.");
    }

    if (lodash_es_isString(type)) {
      this.storeInitialized = this.initStore(type);
    } else {
      this.store = type;
      this.storeInitialized = Promise.resolve();
    }

    this.name = name;
  }

  async initStore(type) {
    if (type === 'session') {
      localforage["setDriver"](drivers_sessionStorage._driver);
    } else if (type === 'local') {
      await localforage["config"]({
        'driver': localforage["LOCALSTORAGE"]
      });
    } else if (type !== 'indexed') {
      throw new Error("Skeletor.storage: No storage type was specified");
    }

    this.store = localforage;
  }

  async clear() {
    await this.store.removeItem(this.name).catch(e => console.error(e));
    const re = new RegExp(`^${this.name}-`);
    const keys = await this.store.keys();
    const removed_keys = keys.filter(k => re.test(k));
    await Promise.all(removed_keys.map(k => this.store.removeItem(k).catch(e => console.error(e))));
  }

  sync(name) {
    const that = this;

    async function localSync(method, model, options) {
      let resp, errorMessage, promise, new_attributes; // We get the collection (and if necessary the model attribute.
      // Waiting for storeInitialized will cause another iteration of
      // the event loop, after which the collection reference will
      // be removed from the model.

      const collection = model.collection;

      if (['patch', 'update'].includes(method)) {
        new_attributes = lodash_es_cloneDeep(model.attributes);
      }

      await that.storeInitialized;

      try {
        const original_attributes = model.attributes;

        switch (method) {
          case "read":
            if (model.id !== undefined) {
              resp = await that.find(model);
            } else {
              resp = await that.findAll();
            }

            break;

          case "create":
            resp = await that.create(model, options);
            break;

          case 'patch':
          case "update":
            if (options.wait) {
              // When `wait` is set to true, Skeletor waits until
              // confirmation of storage before setting the values on
              // the model.
              // However, the new attributes needs to be sent, so it
              // sets them manually on the model and then removes
              // them after calling `sync`.
              // Because our `sync` method is asynchronous and we
              // wait for `storeInitialized`, the attributes are
              // already restored once we get here, so we need to do
              // the attributes dance again.
              model.attributes = new_attributes;
            }

            promise = that.update(model, options);

            if (options.wait) {
              model.attributes = original_attributes;
            }

            resp = await promise;
            break;

          case "delete":
            resp = await that.destroy(model, collection);
            break;
        }
      } catch (error) {
        if (error.code === 22 && that.getStorageSize() === 0) {
          errorMessage = "Private browsing is unsupported";
        } else {
          errorMessage = error.message;
        }
      }

      if (resp) {
        if (options && options.success) {
          // When storing, we don't pass back the response (which is
          // the set attributes returned from localforage because
          // Skeletor sets them again on the model and due to the async
          // nature of localforage it can cause stale attributes to be
          // set on a model after it's been updated in the meantime.
          const data = method === "read" ? resp : null;
          options.success(data, options);
        }
      } else {
        errorMessage = errorMessage ? errorMessage : "Record Not Found";

        if (options && options.error) {
          options.error(errorMessage);
        }
      }
    }

    localSync.__name__ = 'localSync';
    return localSync;
  }

  removeCollectionReference(model, collection) {
    if (!collection) {
      return;
    }

    const ids = collection.filter(m => m.id !== model.id).map(m => this.getItemName(m.id));
    return this.store.setItem(this.name, ids);
  }

  addCollectionReference(model, collection) {
    if (!collection) {
      return;
    }

    const ids = collection.map(m => this.getItemName(m.id));
    const new_id = this.getItemName(model.id);

    if (!ids.includes(new_id)) {
      ids.push(new_id);
    }

    return this.store.setItem(this.name, ids);
  }

  async save(model, options = {}) {
    const key = this.getItemName(model.id);
    const data = await this.store.setItem(key, model.toJSON());
    await this.addCollectionReference(model, model.collection);
    return data;
  }

  create(model, options) {
    /* Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
     * have an id of it's own.
     */
    if (!model.id) {
      model.id = guid();
      model.set(model.idAttribute, model.id, options);
    }

    return this.save(model);
  }

  update(model, options) {
    return this.save(model, options);
  }

  find(model) {
    return this.store.getItem(this.getItemName(model.id));
  }

  async findAll() {
    /* Return the array of all models currently in storage.
     */
    const data = await this.store.getItem(this.name);

    if (data && data.length) {
      return Promise.all(data.map(item => this.store.getItem(item)));
    }

    return [];
  }

  async destroy(model, collection) {
    await this.store.removeItem(this.getItemName(model.id));
    await this.removeCollectionReference(model, collection);
    return model;
  }

  getStorageSize() {
    return this.store.length;
  }

  getItemName(id) {
    return this.name + "-" + id;
  }

}

storage_Storage.sessionStorageInitialized = localforage["defineDriver"](drivers_sessionStorage);
storage_Storage.localForage = localforage;
/* harmony default export */ var src_storage = (storage_Storage);
// EXTERNAL MODULE: ./node_modules/dayjs/plugin/advancedFormat.js
var advancedFormat = __webpack_require__(158);
var advancedFormat_default = /*#__PURE__*/__webpack_require__.n(advancedFormat);

// EXTERNAL MODULE: ./node_modules/dayjs/dayjs.min.js
var dayjs_min = __webpack_require__(3);
var dayjs_min_default = /*#__PURE__*/__webpack_require__.n(dayjs_min);

// CONCATENATED MODULE: ./node_modules/lodash-es/isPlainObject.js



/** `Object#toString` result references. */

var isPlainObject_objectTag = '[object Object]';
/** Used for built-in method references. */

var isPlainObject_funcProto = Function.prototype,
    isPlainObject_objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */

var isPlainObject_funcToString = isPlainObject_funcProto.toString;
/** Used to check objects for own properties. */

var isPlainObject_hasOwnProperty = isPlainObject_objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */

var objectCtorString = isPlainObject_funcToString.call(Object);
/**
 * Checks if `value` is a plain object, that is, an object created by the
 * `Object` constructor or one with a `[[Prototype]]` of `null`.
 *
 * @static
 * @memberOf _
 * @since 0.8.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 * }
 *
 * _.isPlainObject(new Foo);
 * // => false
 *
 * _.isPlainObject([1, 2, 3]);
 * // => false
 *
 * _.isPlainObject({ 'x': 0, 'y': 0 });
 * // => true
 *
 * _.isPlainObject(Object.create(null));
 * // => true
 */

function isPlainObject(value) {
  if (!lodash_es_isObjectLike(value) || _baseGetTag(value) != isPlainObject_objectTag) {
    return false;
  }

  var proto = _getPrototype(value);

  if (proto === null) {
    return true;
  }

  var Ctor = isPlainObject_hasOwnProperty.call(proto, 'constructor') && proto.constructor;
  return typeof Ctor == 'function' && Ctor instanceof Ctor && isPlainObject_funcToString.call(Ctor) == objectCtorString;
}

/* harmony default export */ var lodash_es_isPlainObject = (isPlainObject);
// CONCATENATED MODULE: ./node_modules/lodash-es/isElement.js


/**
 * Checks if `value` is likely a DOM element.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
 * @example
 *
 * _.isElement(document.body);
 * // => true
 *
 * _.isElement('<body>');
 * // => false
 */

function isElement(value) {
  return lodash_es_isObjectLike(value) && value.nodeType === 1 && !lodash_es_isPlainObject(value);
}

/* harmony default export */ var lodash_es_isElement = (isElement);
// CONCATENATED MODULE: ./src/headless/log.js
var _console, _console2, _console3, _console4;


const LEVELS = {
  'debug': 0,
  'info': 1,
  'warn': 2,
  'error': 3,
  'fatal': 4
};
const logger = Object.assign({
  'debug': (_console = console) !== null && _console !== void 0 && _console.log ? console.log.bind(console) : function noop() {},
  'error': (_console2 = console) !== null && _console2 !== void 0 && _console2.log ? console.log.bind(console) : function noop() {},
  'info': (_console3 = console) !== null && _console3 !== void 0 && _console3.log ? console.log.bind(console) : function noop() {},
  'warn': (_console4 = console) !== null && _console4 !== void 0 && _console4.log ? console.log.bind(console) : function noop() {}
}, console);
/**
 * The log namespace
 * @namespace log
 */

const log = {
  /**
   * The the log-level, which determines how verbose the logging is.
   * @method log#setLogLevel
   * @param { integer } level - The loglevel which allows for filtering of log messages
   */
  setLogLevel(level) {
    if (!['debug', 'info', 'warn', 'error', 'fatal'].includes(level)) {
      throw new Error(`Invalid loglevel: ${level}`);
    }

    this.loglevel = level;
  },

  /**
   * Logs messages to the browser's developer console.
   * Available loglevels are 0 for 'debug', 1 for 'info', 2 for 'warn',
   * 3 for 'error' and 4 for 'fatal'.
   * When using the 'error' or 'warn' loglevels, a full stacktrace will be
   * logged as well.
   * @method log#log
   * @param { string } message - The message to be logged
   * @param { integer } level - The loglevel which allows for filtering of log messages
   */
  log(message, level, style = '') {
    if (LEVELS[level] < LEVELS[this.loglevel]) {
      return;
    }

    if (level === 'error' || level === 'fatal') {
      style = style || 'color: maroon';
    } else if (level === 'debug') {
      style = style || 'color: green';
    }

    if (message instanceof Error) {
      message = message.stack;
    } else if (lodash_es_isElement(message)) {
      message = message.outerHTML;
    }

    const prefix = style ? '%c' : '';

    if (level === 'error') {
      logger.error(`${prefix} ERROR: ${message}`, style);
    } else if (level === 'warn') {
      logger.warn(`${prefix} ${new Date().toISOString()} WARNING: ${message}`, style);
    } else if (level === 'fatal') {
      logger.error(`${prefix} FATAL: ${message}`, style);
    } else if (level === 'debug') {
      logger.debug(`${prefix} ${new Date().toISOString()} DEBUG: ${message}`, style);
    } else {
      logger.info(`${prefix} ${new Date().toISOString()} INFO: ${message}`, style);
    }
  },

  debug(message, style) {
    this.log(message, 'debug', style);
  },

  error(message, style) {
    this.log(message, 'error', style);
  },

  info(message, style) {
    this.log(message, 'info', style);
  },

  warn(message, style) {
    this.log(message, 'warn', style);
  },

  fatal(message, style) {
    this.log(message, 'fatal', style);
  }

};
/* harmony default export */ var headless_log = (log);
// EXTERNAL MODULE: ./node_modules/lodash/drop.js
var drop = __webpack_require__(159);
var drop_default = /*#__PURE__*/__webpack_require__.n(drop);

// EXTERNAL MODULE: ./node_modules/lodash/each.js
var each = __webpack_require__(41);
var each_default = /*#__PURE__*/__webpack_require__.n(each);

// EXTERNAL MODULE: ./node_modules/lodash/extend.js
var extend = __webpack_require__(42);
var extend_default = /*#__PURE__*/__webpack_require__.n(extend);

// EXTERNAL MODULE: ./node_modules/lodash/includes.js
var lodash_includes = __webpack_require__(32);
var includes_default = /*#__PURE__*/__webpack_require__.n(lodash_includes);

// EXTERNAL MODULE: ./node_modules/lodash/isBoolean.js
var isBoolean = __webpack_require__(160);
var isBoolean_default = /*#__PURE__*/__webpack_require__.n(isBoolean);

// EXTERNAL MODULE: ./node_modules/lodash/isFunction.js
var lodash_isFunction = __webpack_require__(58);
var isFunction_default = /*#__PURE__*/__webpack_require__.n(lodash_isFunction);

// EXTERNAL MODULE: ./node_modules/lodash/isNil.js
var isNil = __webpack_require__(161);
var isNil_default = /*#__PURE__*/__webpack_require__.n(isNil);

// EXTERNAL MODULE: ./node_modules/lodash/keys.js
var lodash_keys = __webpack_require__(29);
var keys_default = /*#__PURE__*/__webpack_require__.n(lodash_keys);

// EXTERNAL MODULE: ./node_modules/lodash/partial.js
var partial = __webpack_require__(90);
var partial_default = /*#__PURE__*/__webpack_require__.n(partial);

// EXTERNAL MODULE: ./node_modules/lodash/pickBy.js
var pickBy = __webpack_require__(162);
var pickBy_default = /*#__PURE__*/__webpack_require__.n(pickBy);

// EXTERNAL MODULE: ./node_modules/lodash/size.js
var lodash_size = __webpack_require__(163);
var size_default = /*#__PURE__*/__webpack_require__.n(lodash_size);

// EXTERNAL MODULE: ./node_modules/lodash/values.js
var lodash_values = __webpack_require__(89);
var values_default = /*#__PURE__*/__webpack_require__.n(lodash_values);

// CONCATENATED MODULE: ./node_modules/pluggable.js/src/pluggable.js
/*
       ____  __                        __    __         _
      / __ \/ /_  __ ___   ___  ____ _/ /_  / /__      (_)____
     / /_/ / / / / / __ \/ __ \/ __/ / __ \/ / _ \    / / ___/
    / ____/ / /_/ / /_/ / /_/ / /_/ / /_/ / /  __/   / (__  )
   /_/   /_/\__,_/\__, /\__, /\__/_/_.___/_/\___(_)_/ /____/
                 /____//____/                    /___/
 */
// Pluggable.js lets you to make your Javascript code pluggable while still
// keeping sensitive objects and data private through closures.

/*global console */











 // The `PluginSocket` class contains the plugin architecture, and gets
// created whenever `pluggable.enable(obj);` is called on the object
// that you want to make pluggable.
// You can also see it as the thing into which the plugins are plugged.
// It takes two parameters, first, the object being made pluggable, and
// then the name by which the pluggable object may be referenced on the
// __super__ object (inside overrides).

function PluginSocket(plugged, name) {
  this.name = name;
  this.plugged = plugged;

  if (typeof this.plugged.__super__ === 'undefined') {
    this.plugged.__super__ = {};
  } else if (typeof this.plugged.__super__ === 'string') {
    this.plugged.__super__ = {
      '__string__': this.plugged.__super__
    };
  }

  this.plugged.__super__[name] = this.plugged;
  this.plugins = {};
  this.initialized_plugins = [];
} // Now we add methods to the PluginSocket by adding them to its
// prototype.


extend_default()(PluginSocket.prototype, {
  // `wrappedOverride` creates a partially applied wrapper function
  // that makes sure to set the proper super method when the
  // overriding method is called. This is done to enable
  // chaining of plugin methods, all the way up to the
  // original method.
  wrappedOverride: function (key, value, super_method, default_super) {
    if (typeof super_method === "function") {
      if (typeof this.__super__ === "undefined") {
        /* We're not on the context of the plugged object.
         * This can happen when the overridden method is called via
         * an event handler or when it's a constructor.
         *
         * In this case, we simply tack on the  __super__ obj.
         */
        this.__super__ = default_super;
      }

      this.__super__[key] = super_method.bind(this);
    }

    return value.apply(this, drop_default()(arguments, 4));
  },
  // `_overrideAttribute` overrides an attribute on the original object
  // (the thing being plugged into).
  //
  // If the attribute being overridden is a function, then the original
  // function will still be available via the `__super__` attribute.
  //
  // If the same function is being overridden multiple times, then
  // the original function will be available at the end of a chain of
  // functions, starting from the most recent override, all the way
  // back to the original function, each being referenced by the
  // previous' __super__ attribute.
  //
  // For example:
  //
  // `plugin2.MyFunc.__super__.myFunc => plugin1.MyFunc.__super__.myFunc => original.myFunc`
  _overrideAttribute: function (key, plugin) {
    let value = plugin.overrides[key];

    if (typeof value === "function") {
      let default_super = {};
      default_super[this.name] = this.plugged;
      let wrapped_function = partial_default()(this.wrappedOverride, key, value, this.plugged[key], default_super);
      this.plugged[key] = wrapped_function;
    } else {
      this.plugged[key] = value;
    }
  },
  _extendObject: function (obj, attributes) {
    if (!obj.prototype.__super__) {
      obj.prototype.__super__ = {};
      obj.prototype.__super__[this.name] = this.plugged;
    }

    let that = this;
    each_default()(attributes, function (value, key) {
      if (key === 'events') {
        obj.prototype[key] = extend_default()(value, obj.prototype[key]);
      } else if (typeof value === 'function') {
        // We create a partially applied wrapper function, that
        // makes sure to set the proper super method when the
        // overriding method is called. This is done to enable
        // chaining of plugin methods, all the way up to the
        // original method.
        let default_super = {};
        default_super[that.name] = that.plugged;
        let wrapped_function = partial_default()(that.wrappedOverride, key, value, obj.prototype[key], default_super);
        obj.prototype[key] = wrapped_function;
      } else {
        obj.prototype[key] = value;
      }
    });
  },
  // Plugins can specify dependencies (by means of the
  // `dependencies` list attribute) which refers to dependencies
  // which will be initialized first, before the plugin itself gets initialized.
  //
  // If `strict_plugin_dependencies` is set to `false` (on the object being
  // made pluggable), then no error will be thrown if any of these plugins aren't
  // available.
  loadPluginDependencies: function (plugin) {
    each_default()(plugin.dependencies, name => {
      let dep = this.plugins[name];

      if (dep) {
        if (includes_default()(dep.dependencies, plugin.__name__)) {
          /* FIXME: circular dependency checking is only one level deep. */
          throw "Found a circular dependency between the plugins \"" + plugin.__name__ + "\" and \"" + name + "\"";
        }

        this.initializePlugin(dep);
      } else {
        this.throwUndefinedDependencyError("Could not find dependency \"" + name + "\" " + "for the plugin \"" + plugin.__name__ + "\". " + "If it's needed, make sure it's loaded by require.js");
      }
    });
  },
  throwUndefinedDependencyError: function (msg) {
    if (this.plugged.strict_plugin_dependencies) {
      throw msg;
    } else {
      if (console.warn) {
        console.warn(msg);
      } else {
        console.log(msg);
      }
    }
  },
  // `applyOverrides` is called by initializePlugin. It applies any
  // and all overrides of methods or Backbone views and models that
  // are defined on any of the plugins.
  applyOverrides: function (plugin) {
    each_default()(Object.keys(plugin.overrides || {}), key => {
      let override = plugin.overrides[key];

      if (typeof override === "object") {
        if (typeof this.plugged[key] === 'undefined') {
          this.throwUndefinedDependencyError(`Plugin "${plugin.__name__}" tried to override "${key}" but it's not found.`);
        } else {
          this._extendObject(this.plugged[key], override);
        }
      } else {
        this._overrideAttribute(key, plugin);
      }
    });
  },
  // `initializePlugin` applies the overrides (if any) defined on all
  // the registered plugins and then calls the initialize method of the plugin
  initializePlugin: function (plugin) {
    if (!includes_default()(keys_default()(this.allowed_plugins), plugin.__name__)) {
      /* Don't initialize disallowed plugins. */
      return;
    }

    if (includes_default()(this.initialized_plugins, plugin.__name__)) {
      /* Don't initialize plugins twice, otherwise we get
      * infinite recursion in overridden methods.
      */
      return;
    }

    if (isBoolean_default()(plugin.enabled) && plugin.enabled || isFunction_default()(plugin.enabled) && plugin.enabled(this.plugged) || isNil_default()(plugin.enabled)) {
      extend_default()(plugin, this.properties);

      if (plugin.dependencies) {
        this.loadPluginDependencies(plugin);
      }

      this.applyOverrides(plugin);

      if (typeof plugin.initialize === "function") {
        plugin.initialize.bind(plugin)(this);
      }

      this.initialized_plugins.push(plugin.__name__);
    }
  },
  // `registerPlugin` registers (or inserts, if you'd like) a plugin,
  // by adding it to the `plugins` map on the PluginSocket instance.
  registerPlugin: function (name, plugin) {
    if (name in this.plugins) {
      throw new Error('Error: Plugin name ' + name + ' is already taken');
    }

    plugin.__name__ = name;
    this.plugins[name] = plugin;
  },
  // `initializePlugins` should get called once all plugins have been
  // registered. It will then iterate through all the plugins, calling
  // `initializePlugin` for each.
  // The passed in  properties variable is an object with attributes and methods
  // which will be attached to the plugins.
  initializePlugins: function (properties = {}, whitelist = [], blacklist = []) {
    if (!size_default()(this.plugins)) {
      return;
    }

    this.properties = properties;
    this.allowed_plugins = pickBy_default()(this.plugins, function (plugin, key) {
      return (!whitelist.length || whitelist.length && includes_default()(whitelist, key)) && !includes_default()(blacklist, key);
    });
    each_default()(values_default()(this.allowed_plugins), this.initializePlugin.bind(this));
  }
});

function enable(object, name, attrname) {
  // Call the `enable` method to make an object pluggable
  //
  // It takes three parameters:
  // - `object`: The object that gets made pluggable.
  // - `name`: The string name by which the now pluggable object
  //     may be referenced on the __super__ obj (in overrides).
  //     The default value is "plugged".
  // - `attrname`: The string name of the attribute on the now
  //     pluggable object, which refers to the PluginSocket instance
  //     that gets created.
  if (typeof attrname === "undefined") {
    attrname = "pluginSocket";
  }

  if (typeof name === 'undefined') {
    name = 'plugged';
  }

  let ref = {};
  ref[attrname] = new PluginSocket(object, name);
  return extend_default()(object, ref);
}


/* harmony default export */ var pluggable = ({
  enable
});
// EXTERNAL MODULE: ./node_modules/localforage-webextensionstorage-driver/sync.js
var sync = __webpack_require__(164);
var sync_default = /*#__PURE__*/__webpack_require__.n(sync);

// EXTERNAL MODULE: ./node_modules/localforage-webextensionstorage-driver/local.js
var local = __webpack_require__(165);
var local_default = /*#__PURE__*/__webpack_require__.n(local);

// EXTERNAL MODULE: ./node_modules/sizzle/dist/sizzle.js
var sizzle = __webpack_require__(2);
var sizzle_default = /*#__PURE__*/__webpack_require__.n(sizzle);

// EXTERNAL MODULE: ./node_modules/strophe.js/src/core.js + 9 modules
var core = __webpack_require__(0);

// CONCATENATED MODULE: ./node_modules/lodash-es/create.js


/**
 * Creates an object that inherits from the `prototype` object. If a
 * `properties` object is given, its own enumerable string keyed properties
 * are assigned to the created object.
 *
 * @static
 * @memberOf _
 * @since 2.3.0
 * @category Object
 * @param {Object} prototype The object to inherit from.
 * @param {Object} [properties] The properties to assign to the object.
 * @returns {Object} Returns the new object.
 * @example
 *
 * function Shape() {
 *   this.x = 0;
 *   this.y = 0;
 * }
 *
 * function Circle() {
 *   Shape.call(this);
 * }
 *
 * Circle.prototype = _.create(Shape.prototype, {
 *   'constructor': Circle
 * });
 *
 * var circle = new Circle;
 * circle instanceof Circle;
 * // => true
 *
 * circle instanceof Shape;
 * // => true
 */

function create_create(prototype, properties) {
  var result = _baseCreate(prototype);
  return properties == null ? result : _baseAssign(result, properties);
}

/* harmony default export */ var lodash_es_create = (create_create);
// CONCATENATED MODULE: ./node_modules/lodash-es/identity.js
/**
 * This method returns the first argument it receives.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {*} value Any value.
 * @returns {*} Returns `value`.
 * @example
 *
 * var object = { 'a': 1 };
 *
 * console.log(_.identity(object) === object);
 * // => true
 */
function identity_identity(value) {
  return value;
}

/* harmony default export */ var lodash_es_identity = (identity_identity);
// CONCATENATED MODULE: ./node_modules/lodash-es/_apply.js
/**
 * A faster alternative to `Function#apply`, this function invokes `func`
 * with the `this` binding of `thisArg` and the arguments of `args`.
 *
 * @private
 * @param {Function} func The function to invoke.
 * @param {*} thisArg The `this` binding of `func`.
 * @param {Array} args The arguments to invoke `func` with.
 * @returns {*} Returns the result of `func`.
 */
function apply(func, thisArg, args) {
  switch (args.length) {
    case 0:
      return func.call(thisArg);

    case 1:
      return func.call(thisArg, args[0]);

    case 2:
      return func.call(thisArg, args[0], args[1]);

    case 3:
      return func.call(thisArg, args[0], args[1], args[2]);
  }

  return func.apply(thisArg, args);
}

/* harmony default export */ var _apply = (apply);
// CONCATENATED MODULE: ./node_modules/lodash-es/_overRest.js

/* Built-in method references for those with the same name as other `lodash` methods. */

var nativeMax = Math.max;
/**
 * A specialized version of `baseRest` which transforms the rest array.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @param {Function} transform The rest array transform.
 * @returns {Function} Returns the new function.
 */

function overRest(func, start, transform) {
  start = nativeMax(start === undefined ? func.length - 1 : start, 0);
  return function () {
    var args = arguments,
        index = -1,
        length = nativeMax(args.length - start, 0),
        array = Array(length);

    while (++index < length) {
      array[index] = args[start + index];
    }

    index = -1;
    var otherArgs = Array(start + 1);

    while (++index < start) {
      otherArgs[index] = args[index];
    }

    otherArgs[start] = transform(array);
    return _apply(func, this, otherArgs);
  };
}

/* harmony default export */ var _overRest = (overRest);
// CONCATENATED MODULE: ./node_modules/lodash-es/constant.js
/**
 * Creates a function that returns `value`.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Util
 * @param {*} value The value to return from the new function.
 * @returns {Function} Returns the new constant function.
 * @example
 *
 * var objects = _.times(2, _.constant({ 'a': 1 }));
 *
 * console.log(objects);
 * // => [{ 'a': 1 }, { 'a': 1 }]
 *
 * console.log(objects[0] === objects[1]);
 * // => true
 */
function constant(value) {
  return function () {
    return value;
  };
}

/* harmony default export */ var lodash_es_constant = (constant);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSetToString.js



/**
 * The base implementation of `setToString` without support for hot loop shorting.
 *
 * @private
 * @param {Function} func The function to modify.
 * @param {Function} string The `toString` result.
 * @returns {Function} Returns `func`.
 */

var baseSetToString = !_defineProperty ? lodash_es_identity : function (func, string) {
  return _defineProperty(func, 'toString', {
    'configurable': true,
    'enumerable': false,
    'value': lodash_es_constant(string),
    'writable': true
  });
};
/* harmony default export */ var _baseSetToString = (baseSetToString);
// CONCATENATED MODULE: ./node_modules/lodash-es/_shortOut.js
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
    HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */

var nativeNow = Date.now;
/**
 * Creates a function that'll short out and invoke `identity` instead
 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
 * milliseconds.
 *
 * @private
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new shortable function.
 */

function shortOut(func) {
  var count = 0,
      lastCalled = 0;
  return function () {
    var stamp = nativeNow(),
        remaining = HOT_SPAN - (stamp - lastCalled);
    lastCalled = stamp;

    if (remaining > 0) {
      if (++count >= HOT_COUNT) {
        return arguments[0];
      }
    } else {
      count = 0;
    }

    return func.apply(undefined, arguments);
  };
}

/* harmony default export */ var _shortOut = (shortOut);
// CONCATENATED MODULE: ./node_modules/lodash-es/_setToString.js


/**
 * Sets the `toString` method of `func` to return `string`.
 *
 * @private
 * @param {Function} func The function to modify.
 * @param {Function} string The `toString` result.
 * @returns {Function} Returns `func`.
 */

var setToString = _shortOut(_baseSetToString);
/* harmony default export */ var _setToString = (setToString);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseRest.js



/**
 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @returns {Function} Returns the new function.
 */

function baseRest(func, start) {
  return _setToString(_overRest(func, start, lodash_es_identity), func + '');
}

/* harmony default export */ var _baseRest = (baseRest);
// CONCATENATED MODULE: ./node_modules/lodash-es/_isIterateeCall.js




/**
 * Checks if the given arguments are from an iteratee call.
 *
 * @private
 * @param {*} value The potential iteratee value argument.
 * @param {*} index The potential iteratee index or key argument.
 * @param {*} object The potential iteratee object argument.
 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
 *  else `false`.
 */

function isIterateeCall(value, index, object) {
  if (!lodash_es_isObject(object)) {
    return false;
  }

  var type = typeof index;

  if (type == 'number' ? lodash_es_isArrayLike(object) && _isIndex(index, object.length) : type == 'string' && index in object) {
    return lodash_es_eq(object[index], value);
  }

  return false;
}

/* harmony default export */ var _isIterateeCall = (isIterateeCall);
// CONCATENATED MODULE: ./node_modules/lodash-es/_createAssigner.js


/**
 * Creates a function like `_.assign`.
 *
 * @private
 * @param {Function} assigner The function to assign values.
 * @returns {Function} Returns the new assigner function.
 */

function createAssigner(assigner) {
  return _baseRest(function (object, sources) {
    var index = -1,
        length = sources.length,
        customizer = length > 1 ? sources[length - 1] : undefined,
        guard = length > 2 ? sources[2] : undefined;
    customizer = assigner.length > 3 && typeof customizer == 'function' ? (length--, customizer) : undefined;

    if (guard && _isIterateeCall(sources[0], sources[1], guard)) {
      customizer = length < 3 ? undefined : customizer;
      length = 1;
    }

    object = Object(object);

    while (++index < length) {
      var source = sources[index];

      if (source) {
        assigner(object, source, index, customizer);
      }
    }

    return object;
  });
}

/* harmony default export */ var _createAssigner = (createAssigner);
// CONCATENATED MODULE: ./node_modules/lodash-es/assignIn.js



/**
 * This method is like `_.assign` except that it iterates over own and
 * inherited source properties.
 *
 * **Note:** This method mutates `object`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @alias extend
 * @category Object
 * @param {Object} object The destination object.
 * @param {...Object} [sources] The source objects.
 * @returns {Object} Returns `object`.
 * @see _.assign
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 * }
 *
 * function Bar() {
 *   this.c = 3;
 * }
 *
 * Foo.prototype.b = 2;
 * Bar.prototype.d = 4;
 *
 * _.assignIn({ 'a': 0 }, new Foo, new Bar);
 * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
 */

var assignIn = _createAssigner(function (object, source) {
  _copyObject(source, lodash_es_keysIn(source), object);
});
/* harmony default export */ var lodash_es_assignIn = (assignIn);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseHas.js
/** Used for built-in method references. */
var _baseHas_objectProto = Object.prototype;
/** Used to check objects for own properties. */

var _baseHas_hasOwnProperty = _baseHas_objectProto.hasOwnProperty;
/**
 * The base implementation of `_.has` without support for deep paths.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {Array|string} key The key to check.
 * @returns {boolean} Returns `true` if `key` exists, else `false`.
 */

function baseHas(object, key) {
  return object != null && _baseHas_hasOwnProperty.call(object, key);
}

/* harmony default export */ var _baseHas = (baseHas);
// CONCATENATED MODULE: ./node_modules/lodash-es/isSymbol.js


/** `Object#toString` result references. */

var isSymbol_symbolTag = '[object Symbol]';
/**
 * Checks if `value` is classified as a `Symbol` primitive or object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
 * @example
 *
 * _.isSymbol(Symbol.iterator);
 * // => true
 *
 * _.isSymbol('abc');
 * // => false
 */

function isSymbol(value) {
  return typeof value == 'symbol' || lodash_es_isObjectLike(value) && _baseGetTag(value) == isSymbol_symbolTag;
}

/* harmony default export */ var lodash_es_isSymbol = (isSymbol);
// CONCATENATED MODULE: ./node_modules/lodash-es/_isKey.js


/** Used to match property names within property paths. */

var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
    reIsPlainProp = /^\w*$/;
/**
 * Checks if `value` is a property name and not a property path.
 *
 * @private
 * @param {*} value The value to check.
 * @param {Object} [object] The object to query keys on.
 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
 */

function isKey(value, object) {
  if (lodash_es_isArray(value)) {
    return false;
  }

  var type = typeof value;

  if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || lodash_es_isSymbol(value)) {
    return true;
  }

  return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
}

/* harmony default export */ var _isKey = (isKey);
// CONCATENATED MODULE: ./node_modules/lodash-es/memoize.js

/** Error message constants. */

var FUNC_ERROR_TEXT = 'Expected a function';
/**
 * Creates a function that memoizes the result of `func`. If `resolver` is
 * provided, it determines the cache key for storing the result based on the
 * arguments provided to the memoized function. By default, the first argument
 * provided to the memoized function is used as the map cache key. The `func`
 * is invoked with the `this` binding of the memoized function.
 *
 * **Note:** The cache is exposed as the `cache` property on the memoized
 * function. Its creation may be customized by replacing the `_.memoize.Cache`
 * constructor with one whose instances implement the
 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to have its output memoized.
 * @param {Function} [resolver] The function to resolve the cache key.
 * @returns {Function} Returns the new memoized function.
 * @example
 *
 * var object = { 'a': 1, 'b': 2 };
 * var other = { 'c': 3, 'd': 4 };
 *
 * var values = _.memoize(_.values);
 * values(object);
 * // => [1, 2]
 *
 * values(other);
 * // => [3, 4]
 *
 * object.a = 2;
 * values(object);
 * // => [1, 2]
 *
 * // Modify the result cache.
 * values.cache.set(object, ['a', 'b']);
 * values(object);
 * // => ['a', 'b']
 *
 * // Replace `_.memoize.Cache`.
 * _.memoize.Cache = WeakMap;
 */

function memoize(func, resolver) {
  if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }

  var memoized = function () {
    var args = arguments,
        key = resolver ? resolver.apply(this, args) : args[0],
        cache = memoized.cache;

    if (cache.has(key)) {
      return cache.get(key);
    }

    var result = func.apply(this, args);
    memoized.cache = cache.set(key, result) || cache;
    return result;
  };

  memoized.cache = new (memoize.Cache || _MapCache)();
  return memoized;
} // Expose `MapCache`.


memoize.Cache = _MapCache;
/* harmony default export */ var lodash_es_memoize = (memoize);
// CONCATENATED MODULE: ./node_modules/lodash-es/_memoizeCapped.js

/** Used as the maximum memoize cache size. */

var MAX_MEMOIZE_SIZE = 500;
/**
 * A specialized version of `_.memoize` which clears the memoized function's
 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
 *
 * @private
 * @param {Function} func The function to have its output memoized.
 * @returns {Function} Returns the new memoized function.
 */

function memoizeCapped(func) {
  var result = lodash_es_memoize(func, function (key) {
    if (cache.size === MAX_MEMOIZE_SIZE) {
      cache.clear();
    }

    return key;
  });
  var cache = result.cache;
  return result;
}

/* harmony default export */ var _memoizeCapped = (memoizeCapped);
// CONCATENATED MODULE: ./node_modules/lodash-es/_stringToPath.js

/** Used to match property names within property paths. */

var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */

var reEscapeChar = /\\(\\)?/g;
/**
 * Converts `string` to a property path array.
 *
 * @private
 * @param {string} string The string to convert.
 * @returns {Array} Returns the property path array.
 */

var stringToPath = _memoizeCapped(function (string) {
  var result = [];

  if (string.charCodeAt(0) === 46
  /* . */
  ) {
      result.push('');
    }

  string.replace(rePropName, function (match, number, quote, subString) {
    result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
  });
  return result;
});
/* harmony default export */ var _stringToPath = (stringToPath);
// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayMap.js
/**
 * A specialized version of `_.map` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 */
function arrayMap(array, iteratee) {
  var index = -1,
      length = array == null ? 0 : array.length,
      result = Array(length);

  while (++index < length) {
    result[index] = iteratee(array[index], index, array);
  }

  return result;
}

/* harmony default export */ var _arrayMap = (arrayMap);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseToString.js




/** Used as references for various `Number` constants. */

var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */

var _baseToString_symbolProto = _Symbol ? _Symbol.prototype : undefined,
    symbolToString = _baseToString_symbolProto ? _baseToString_symbolProto.toString : undefined;
/**
 * The base implementation of `_.toString` which doesn't convert nullish
 * values to empty strings.
 *
 * @private
 * @param {*} value The value to process.
 * @returns {string} Returns the string.
 */

function baseToString(value) {
  // Exit early for strings to avoid a performance hit in some environments.
  if (typeof value == 'string') {
    return value;
  }

  if (lodash_es_isArray(value)) {
    // Recursively convert values (susceptible to call stack limits).
    return _arrayMap(value, baseToString) + '';
  }

  if (lodash_es_isSymbol(value)) {
    return symbolToString ? symbolToString.call(value) : '';
  }

  var result = value + '';
  return result == '0' && 1 / value == -INFINITY ? '-0' : result;
}

/* harmony default export */ var _baseToString = (baseToString);
// CONCATENATED MODULE: ./node_modules/lodash-es/toString.js

/**
 * Converts `value` to a string. An empty string is returned for `null`
 * and `undefined` values. The sign of `-0` is preserved.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 * @example
 *
 * _.toString(null);
 * // => ''
 *
 * _.toString(-0);
 * // => '-0'
 *
 * _.toString([1, 2, 3]);
 * // => '1,2,3'
 */

function toString_toString(value) {
  return value == null ? '' : _baseToString(value);
}

/* harmony default export */ var lodash_es_toString = (toString_toString);
// CONCATENATED MODULE: ./node_modules/lodash-es/_castPath.js




/**
 * Casts `value` to a path array if it's not one.
 *
 * @private
 * @param {*} value The value to inspect.
 * @param {Object} [object] The object to query keys on.
 * @returns {Array} Returns the cast property path array.
 */

function castPath(value, object) {
  if (lodash_es_isArray(value)) {
    return value;
  }

  return _isKey(value, object) ? [value] : _stringToPath(lodash_es_toString(value));
}

/* harmony default export */ var _castPath = (castPath);
// CONCATENATED MODULE: ./node_modules/lodash-es/_toKey.js

/** Used as references for various `Number` constants. */

var _toKey_INFINITY = 1 / 0;
/**
 * Converts `value` to a string key if it's not a string or symbol.
 *
 * @private
 * @param {*} value The value to inspect.
 * @returns {string|symbol} Returns the key.
 */

function toKey(value) {
  if (typeof value == 'string' || lodash_es_isSymbol(value)) {
    return value;
  }

  var result = value + '';
  return result == '0' && 1 / value == -_toKey_INFINITY ? '-0' : result;
}

/* harmony default export */ var _toKey = (toKey);
// CONCATENATED MODULE: ./node_modules/lodash-es/_hasPath.js






/**
 * Checks if `path` exists on `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @param {Function} hasFunc The function to check properties.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 */

function hasPath(object, path, hasFunc) {
  path = _castPath(path, object);
  var index = -1,
      length = path.length,
      result = false;

  while (++index < length) {
    var key = _toKey(path[index]);

    if (!(result = object != null && hasFunc(object, key))) {
      break;
    }

    object = object[key];
  }

  if (result || ++index != length) {
    return result;
  }

  length = object == null ? 0 : object.length;
  return !!length && lodash_es_isLength(length) && _isIndex(key, length) && (lodash_es_isArray(object) || lodash_es_isArguments(object));
}

/* harmony default export */ var _hasPath = (hasPath);
// CONCATENATED MODULE: ./node_modules/lodash-es/has.js


/**
 * Checks if `path` is a direct property of `object`.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 * @example
 *
 * var object = { 'a': { 'b': 2 } };
 * var other = _.create({ 'a': _.create({ 'b': 2 }) });
 *
 * _.has(object, 'a');
 * // => true
 *
 * _.has(object, 'a.b');
 * // => true
 *
 * _.has(object, ['a', 'b']);
 * // => true
 *
 * _.has(other, 'a');
 * // => false
 */

function has(object, path) {
  return object != null && _hasPath(object, path, _baseHas);
}

/* harmony default export */ var lodash_es_has = (has);
// CONCATENATED MODULE: ./node_modules/lodash-es/result.js



/**
 * This method is like `_.get` except that if the resolved value is a
 * function it's invoked with the `this` binding of its parent object and
 * its result is returned.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to resolve.
 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
 * @returns {*} Returns the resolved value.
 * @example
 *
 * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
 *
 * _.result(object, 'a[0].b.c1');
 * // => 3
 *
 * _.result(object, 'a[0].b.c2');
 * // => 4
 *
 * _.result(object, 'a[0].b.c3', 'default');
 * // => 'default'
 *
 * _.result(object, 'a[0].b.c3', _.constant('default'));
 * // => 'default'
 */

function result_result(object, path, defaultValue) {
  path = _castPath(path, object);
  var index = -1,
      length = path.length; // Ensure the loop is entered when path is empty.

  if (!length) {
    length = 1;
    object = undefined;
  }

  while (++index < length) {
    var value = object == null ? undefined : object[_toKey(path[index])];

    if (value === undefined) {
      index = length;
      value = defaultValue;
    }

    object = lodash_es_isFunction(value) ? value.call(object) : value;
  }

  return object;
}

/* harmony default export */ var lodash_es_result = (result_result);
// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/helpers.js
//     (c) 2010-2019 Jeremy Ashkenas and DocumentCloud




/**
 * Custom error for indicating timeouts
 * @namespace _converse
 */

class NotImplementedError extends Error {} // Helpers
// -------
// Helper function to correctly set up the prototype chain for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
//

function inherits(protoProps, staticProps) {
  const parent = this;
  let child; // The constructor function for the new subclass is either defined by you
  // (the "constructor" property in your `extend` definition), or defaulted
  // by us to simply call the parent constructor.

  if (protoProps && lodash_es_has(protoProps, 'constructor')) {
    child = protoProps.constructor;
  } else {
    child = function () {
      return parent.apply(this, arguments);
    };
  } // Add static properties to the constructor function, if supplied.


  lodash_es_assignIn(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling
  // `parent`'s constructor function and add the prototype properties.

  child.prototype = lodash_es_create(parent.prototype, protoProps);
  child.prototype.constructor = child; // Set a convenience property in case the parent's prototype is needed
  // later.

  child.__super__ = parent.prototype;
  return child;
}
function getResolveablePromise() {
  const wrapper = {
    isResolved: false,
    isPending: true,
    isRejected: false
  };
  const promise = new Promise((resolve, reject) => {
    wrapper.resolve = resolve;
    wrapper.reject = reject;
  });
  Object.assign(promise, wrapper);
  promise.then(function (v) {
    promise.isResolved = true;
    promise.isPending = false;
    promise.isRejected = false;
    return v;
  }, function (e) {
    promise.isResolved = false;
    promise.isPending = false;
    promise.isRejected = true;
    throw e;
  });
  return promise;
} // Throw an error when a URL is needed, and none is supplied.

function urlError() {
  throw new Error('A "url" property or function must be specified');
} // Wrap an optional error callback with a fallback error event.

function wrapError(model, options) {
  const error = options.error;

  options.error = function (resp) {
    if (error) error.call(options.context, model, resp, options);
    model.trigger('error', model, resp, options);
  };
} // Map from CRUD to HTTP for our default `sync` implementation.

const methodMap = {
  create: 'POST',
  update: 'PUT',
  patch: 'PATCH',
  delete: 'DELETE',
  read: 'GET'
};
function getSyncMethod(model) {
  const store = lodash_es_result(model, 'browserStorage') || lodash_es_result(model.collection, 'browserStorage');
  return store ? store.sync() : helpers_sync;
} // sync
// ----
// Override this function to change the manner in which Backbone persists
// models to the server. You will be passed the type of request, and the
// model in question. By default, makes a RESTful Ajax request
// to the model's `url()`. Some possible customizations could be:
//
// * Use `setTimeout` to batch rapid-fire updates into a single request.
// * Send up the models as XML instead of JSON.
// * Persist models via WebSockets instead of Ajax.
//

function helpers_sync(method, model, options = {}) {
  const type = methodMap[method]; // Default JSON-request options.

  const params = {
    type: type,
    dataType: 'json'
  }; // Ensure that we have a URL.

  if (!options.url) {
    params.url = lodash_es_result(model, 'url') || urlError();
  } // Ensure that we have the appropriate request data.


  if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
    params.contentType = 'application/json';
    params.data = JSON.stringify(options.attrs || model.toJSON(options));
  } // Don't process data on a non-GET request.


  if (params.type !== 'GET') {
    params.processData = false;
  } // Pass along `textStatus` and `errorThrown` from jQuery.


  const error = options.error;

  options.error = function (xhr, textStatus, errorThrown) {
    options.textStatus = textStatus;
    options.errorThrown = errorThrown;
    if (error) error.call(options.context, xhr, textStatus, errorThrown);
  }; // Make the request, allowing the user to override any Ajax options.


  const xhr = options.xhr = ajax(lodash_es_assignIn(params, options));
  model.trigger('request', model, xhr, options);
  return xhr;
}
function ajax() {
  return fetch.apply(this, arguments);
}
// CONCATENATED MODULE: ./node_modules/lodash-es/isEmpty.js








/** `Object#toString` result references. */

var isEmpty_mapTag = '[object Map]',
    isEmpty_setTag = '[object Set]';
/** Used for built-in method references. */

var isEmpty_objectProto = Object.prototype;
/** Used to check objects for own properties. */

var isEmpty_hasOwnProperty = isEmpty_objectProto.hasOwnProperty;
/**
 * Checks if `value` is an empty object, collection, map, or set.
 *
 * Objects are considered empty if they have no own enumerable string keyed
 * properties.
 *
 * Array-like values such as `arguments` objects, arrays, buffers, strings, or
 * jQuery-like collections are considered empty if they have a `length` of `0`.
 * Similarly, maps and sets are considered empty if they have a `size` of `0`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
 * @example
 *
 * _.isEmpty(null);
 * // => true
 *
 * _.isEmpty(true);
 * // => true
 *
 * _.isEmpty(1);
 * // => true
 *
 * _.isEmpty([1, 2, 3]);
 * // => false
 *
 * _.isEmpty({ 'a': 1 });
 * // => false
 */

function isEmpty(value) {
  if (value == null) {
    return true;
  }

  if (lodash_es_isArrayLike(value) && (lodash_es_isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || Object(isBuffer["a" /* default */])(value) || lodash_es_isTypedArray(value) || lodash_es_isArguments(value))) {
    return !value.length;
  }

  var tag = _getTag(value);

  if (tag == isEmpty_mapTag || tag == isEmpty_setTag) {
    return !value.size;
  }

  if (_isPrototype(value)) {
    return !_baseKeys(value).length;
  }

  for (var key in value) {
    if (isEmpty_hasOwnProperty.call(value, key)) {
      return false;
    }
  }

  return true;
}

/* harmony default export */ var lodash_es_isEmpty = (isEmpty);
// CONCATENATED MODULE: ./node_modules/lodash-es/_trimmedEndIndex.js
/** Used to match a single whitespace character. */
var reWhitespace = /\s/;
/**
 * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
 * character of `string`.
 *
 * @private
 * @param {string} string The string to inspect.
 * @returns {number} Returns the index of the last non-whitespace character.
 */

function trimmedEndIndex(string) {
  var index = string.length;

  while (index-- && reWhitespace.test(string.charAt(index))) {}

  return index;
}

/* harmony default export */ var _trimmedEndIndex = (trimmedEndIndex);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseTrim.js

/** Used to match leading whitespace. */

var reTrimStart = /^\s+/;
/**
 * The base implementation of `_.trim`.
 *
 * @private
 * @param {string} string The string to trim.
 * @returns {string} Returns the trimmed string.
 */

function baseTrim(string) {
  return string ? string.slice(0, _trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string;
}

/* harmony default export */ var _baseTrim = (baseTrim);
// CONCATENATED MODULE: ./node_modules/lodash-es/toNumber.js



/** Used as references for various `Number` constants. */

var NAN = 0 / 0;
/** Used to detect bad signed hexadecimal string values. */

var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */

var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */

var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */

var freeParseInt = parseInt;
/**
 * Converts `value` to a number.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to process.
 * @returns {number} Returns the number.
 * @example
 *
 * _.toNumber(3.2);
 * // => 3.2
 *
 * _.toNumber(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toNumber(Infinity);
 * // => Infinity
 *
 * _.toNumber('3.2');
 * // => 3.2
 */

function toNumber(value) {
  if (typeof value == 'number') {
    return value;
  }

  if (lodash_es_isSymbol(value)) {
    return NAN;
  }

  if (lodash_es_isObject(value)) {
    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
    value = lodash_es_isObject(other) ? other + '' : other;
  }

  if (typeof value != 'string') {
    return value === 0 ? value : +value;
  }

  value = _baseTrim(value);
  var isBinary = reIsBinary.test(value);
  return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}

/* harmony default export */ var lodash_es_toNumber = (toNumber);
// CONCATENATED MODULE: ./node_modules/lodash-es/toFinite.js

/** Used as references for various `Number` constants. */

var toFinite_INFINITY = 1 / 0,
    MAX_INTEGER = 1.7976931348623157e+308;
/**
 * Converts `value` to a finite number.
 *
 * @static
 * @memberOf _
 * @since 4.12.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted number.
 * @example
 *
 * _.toFinite(3.2);
 * // => 3.2
 *
 * _.toFinite(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toFinite(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toFinite('3.2');
 * // => 3.2
 */

function toFinite(value) {
  if (!value) {
    return value === 0 ? value : 0;
  }

  value = lodash_es_toNumber(value);

  if (value === toFinite_INFINITY || value === -toFinite_INFINITY) {
    var sign = value < 0 ? -1 : 1;
    return sign * MAX_INTEGER;
  }

  return value === value ? value : 0;
}

/* harmony default export */ var lodash_es_toFinite = (toFinite);
// CONCATENATED MODULE: ./node_modules/lodash-es/toInteger.js

/**
 * Converts `value` to an integer.
 *
 * **Note:** This method is loosely based on
 * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted integer.
 * @example
 *
 * _.toInteger(3.2);
 * // => 3
 *
 * _.toInteger(Number.MIN_VALUE);
 * // => 0
 *
 * _.toInteger(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toInteger('3.2');
 * // => 3
 */

function toInteger(value) {
  var result = lodash_es_toFinite(value),
      remainder = result % 1;
  return result === result ? remainder ? result - remainder : result : 0;
}

/* harmony default export */ var lodash_es_toInteger = (toInteger);
// CONCATENATED MODULE: ./node_modules/lodash-es/before.js

/** Error message constants. */

var before_FUNC_ERROR_TEXT = 'Expected a function';
/**
 * Creates a function that invokes `func`, with the `this` binding and arguments
 * of the created function, while it's called less than `n` times. Subsequent
 * calls to the created function return the result of the last `func` invocation.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Function
 * @param {number} n The number of calls at which `func` is no longer invoked.
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new restricted function.
 * @example
 *
 * jQuery(element).on('click', _.before(5, addContactToList));
 * // => Allows adding up to 4 contacts to the list.
 */

function before(n, func) {
  var result;

  if (typeof func != 'function') {
    throw new TypeError(before_FUNC_ERROR_TEXT);
  }

  n = lodash_es_toInteger(n);
  return function () {
    if (--n > 0) {
      result = func.apply(this, arguments);
    }

    if (n <= 1) {
      func = undefined;
    }

    return result;
  };
}

/* harmony default export */ var lodash_es_before = (before);
// CONCATENATED MODULE: ./node_modules/lodash-es/once.js

/**
 * Creates a function that is restricted to invoking `func` once. Repeat calls
 * to the function return the value of the first invocation. The `func` is
 * invoked with the `this` binding and arguments of the created function.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new restricted function.
 * @example
 *
 * var initialize = _.once(createApplication);
 * initialize();
 * initialize();
 * // => `createApplication` is invoked once
 */

function once(func) {
  return lodash_es_before(2, func);
}

/* harmony default export */ var lodash_es_once = (once);
// CONCATENATED MODULE: ./node_modules/lodash-es/uniqueId.js

/** Used to generate unique IDs. */

var idCounter = 0;
/**
 * Generates a unique ID. If `prefix` is given, the ID is appended to it.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {string} [prefix=''] The value to prefix the ID with.
 * @returns {string} Returns the unique ID.
 * @example
 *
 * _.uniqueId('contact_');
 * // => 'contact_104'
 *
 * _.uniqueId();
 * // => '105'
 */

function uniqueId(prefix) {
  var id = ++idCounter;
  return lodash_es_toString(prefix) + id;
}

/* harmony default export */ var lodash_es_uniqueId = (uniqueId);
// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/events.js
//     Backbone.js 1.4.0
//     (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
//     Backbone may be freely distributed under the MIT license.
// Events
// ------
// A module that can be mixed in to *any object* in order to provide it with
// a custom event channel. You may bind a callback to an event with `on` or
// remove with `off`; `trigger`-ing an event fires all callbacks in
// succession.
//
//     let object = {};
//     extend(object, Backbone.Events);
//     object.on('expand', function(){ alert('expanded'); });
//     object.trigger('expand');
//




const Events = {}; // Regular expression used to split event strings.

const eventSplitter = /\s+/; // A private global variable to share between listeners and listenees.

let _listening; // Iterates over the standard `event, callback` (as well as the fancy multiple
// space-separated events `"change blur", callback` and jQuery-style event
// maps `{event: callback}`).


const eventsApi = function (iteratee, events, name, callback, opts) {
  let i = 0,
      names;

  if (name && typeof name === 'object') {
    // Handle event maps.
    if (callback !== undefined && 'context' in opts && opts.context === undefined) opts.context = callback;

    for (names = lodash_es_keys(name); i < names.length; i++) {
      events = eventsApi(iteratee, events, names[i], name[names[i]], opts);
    }
  } else if (name && eventSplitter.test(name)) {
    // Handle space-separated event names by delegating them individually.
    for (names = name.split(eventSplitter); i < names.length; i++) {
      events = iteratee(events, names[i], callback, opts);
    }
  } else {
    // Finally, standard events.
    events = iteratee(events, name, callback, opts);
  }

  return events;
}; // Bind an event to a `callback` function. Passing `"all"` will bind
// the callback to all events fired.


Events.on = function (name, callback, context) {
  this._events = eventsApi(onApi, this._events || {}, name, callback, {
    context: context,
    ctx: this,
    listening: _listening
  });

  if (_listening) {
    const listeners = this._listeners || (this._listeners = {});
    listeners[_listening.id] = _listening; // Allow the listening to use a counter, instead of tracking
    // callbacks for library interop

    _listening.interop = false;
  }

  return this;
}; // Inversion-of-control versions of `on`. Tell *this* object to listen to
// an event in another object... keeping track of what it's listening to
// for easier unbinding later.


Events.listenTo = function (obj, name, callback) {
  if (!obj) return this;
  const id = obj._listenId || (obj._listenId = lodash_es_uniqueId('l'));
  const listeningTo = this._listeningTo || (this._listeningTo = {});
  let listening = _listening = listeningTo[id]; // This object is not listening to any other events on `obj` yet.
  // Setup the necessary references to track the listening callbacks.

  if (!listening) {
    this._listenId || (this._listenId = lodash_es_uniqueId('l'));
    listening = _listening = listeningTo[id] = new Listening(this, obj);
  } // Bind callbacks on obj.


  const error = tryCatchOn(obj, name, callback, this);
  _listening = undefined;
  if (error) throw error; // If the target obj is not Backbone.Events, track events manually.

  if (listening.interop) listening.on(name, callback);
  return this;
}; // The reducing API that adds a callback to the `events` object.


const onApi = function (events, name, callback, options) {
  if (callback) {
    const handlers = events[name] || (events[name] = []);
    const context = options.context,
          ctx = options.ctx,
          listening = options.listening;
    if (listening) listening.count++;
    handlers.push({
      callback: callback,
      context: context,
      ctx: context || ctx,
      listening: listening
    });
  }

  return events;
}; // An try-catch guarded #on function, to prevent poisoning the global
// `_listening` variable.


const tryCatchOn = function (obj, name, callback, context) {
  try {
    obj.on(name, callback, context);
  } catch (e) {
    return e;
  }
}; // Remove one or many callbacks. If `context` is null, removes all
// callbacks with that function. If `callback` is null, removes all
// callbacks for the event. If `name` is null, removes all bound
// callbacks for all events.


Events.off = function (name, callback, context) {
  if (!this._events) return this;
  this._events = eventsApi(offApi, this._events, name, callback, {
    context: context,
    listeners: this._listeners
  });
  return this;
}; // Tell this object to stop listening to either specific events ... or
// to every object it's currently listening to.


Events.stopListening = function (obj, name, callback) {
  const listeningTo = this._listeningTo;
  if (!listeningTo) return this;
  const ids = obj ? [obj._listenId] : lodash_es_keys(listeningTo);

  for (let i = 0; i < ids.length; i++) {
    const listening = listeningTo[ids[i]]; // If listening doesn't exist, this object is not currently
    // listening to obj. Break out early.

    if (!listening) break;
    listening.obj.off(name, callback, this);
    if (listening.interop) listening.off(name, callback);
  }

  if (lodash_es_isEmpty(listeningTo)) this._listeningTo = undefined;
  return this;
}; // The reducing API that removes a callback from the `events` object.


const offApi = function (events, name, callback, options) {
  if (!events) return;
  const context = options.context,
        listeners = options.listeners;
  let i = 0,
      names; // Delete all event listeners and "drop" events.

  if (!name && !context && !callback) {
    for (names = lodash_es_keys(listeners); i < names.length; i++) {
      listeners[names[i]].cleanup();
    }

    return;
  }

  names = name ? [name] : lodash_es_keys(events);

  for (; i < names.length; i++) {
    name = names[i];
    const handlers = events[name]; // Bail out if there are no events stored.

    if (!handlers) {
      break;
    } // Find any remaining events.


    const remaining = [];

    for (let j = 0; j < handlers.length; j++) {
      const handler = handlers[j];

      if (callback && callback !== handler.callback && callback !== handler.callback._callback || context && context !== handler.context) {
        remaining.push(handler);
      } else {
        const listening = handler.listening;
        if (listening) listening.off(name, callback);
      }
    } // Replace events if there are any remaining.  Otherwise, clean up.


    if (remaining.length) {
      events[name] = remaining;
    } else {
      delete events[name];
    }
  }

  return events;
}; // Bind an event to only be triggered a single time. After the first time
// the callback is invoked, its listener will be removed. If multiple events
// are passed in using the space-separated syntax, the handler will fire
// once for each event, not once for a combination of all events.


Events.once = function (name, callback, context) {
  // Map the event into a `{event: once}` object.
  const events = eventsApi(onceMap, {}, name, callback, this.off.bind(this));
  if (typeof name === 'string' && (context === null || context === undefined)) callback = undefined;
  return this.on(events, callback, context);
}; // Inversion-of-control versions of `once`.


Events.listenToOnce = function (obj, name, callback) {
  // Map the event into a `{event: once}` object.
  const events = eventsApi(onceMap, {}, name, callback, this.stopListening.bind(this, obj));
  return this.listenTo(obj, events);
}; // Reduces the event callbacks into a map of `{event: onceWrapper}`.
// `offer` unbinds the `onceWrapper` after it has been called.


const onceMap = function (map, name, callback, offer) {
  if (callback) {
    const _once = map[name] = lodash_es_once(function () {
      offer(name, _once);
      callback.apply(this, arguments);
    });

    _once._callback = callback;
  }

  return map;
}; // Trigger one or many events, firing all bound callbacks. Callbacks are
// passed the same arguments as `trigger` is, apart from the event name
// (unless you're listening on `"all"`, which will cause your callback to
// receive the true name of the event as the first argument).


Events.trigger = function (name) {
  if (!this._events) return this;
  const length = Math.max(0, arguments.length - 1);
  const args = Array(length);

  for (let i = 0; i < length; i++) args[i] = arguments[i + 1];

  eventsApi(triggerApi, this._events, name, undefined, args);
  return this;
}; // Handles triggering the appropriate event callbacks.


const triggerApi = function (objEvents, name, callback, args) {
  if (objEvents) {
    const events = objEvents[name];
    let allEvents = objEvents.all;
    if (events && allEvents) allEvents = allEvents.slice();
    if (events) triggerEvents(events, args);
    if (allEvents) triggerEvents(allEvents, [name].concat(args));
  }

  return objEvents;
}; // A difficult-to-believe, but optimized internal dispatch function for
// triggering events. Tries to keep the usual cases speedy (most internal
// Backbone events have 3 arguments).


const triggerEvents = function (events, args) {
  let ev,
      i = -1;
  const l = events.length,
        a1 = args[0],
        a2 = args[1],
        a3 = args[2];

  switch (args.length) {
    case 0:
      while (++i < l) (ev = events[i]).callback.call(ev.ctx);

      return;

    case 1:
      while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1);

      return;

    case 2:
      while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2);

      return;

    case 3:
      while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3);

      return;

    default:
      while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);

      return;
  }
}; // A listening class that tracks and cleans up memory bindings
// when all callbacks have been offed.


const Listening = function (listener, obj) {
  this.id = listener._listenId;
  this.listener = listener;
  this.obj = obj;
  this.interop = true;
  this.count = 0;
  this._events = undefined;
};

Listening.prototype.on = Events.on; // Offs a callback (or several).
// Uses an optimized counter if the listenee uses Backbone.Events.
// Otherwise, falls back to manual tracking to support events
// library interop.

Listening.prototype.off = function (name, callback) {
  let cleanup;

  if (this.interop) {
    this._events = eventsApi(offApi, this._events, name, callback, {
      context: undefined,
      listeners: undefined
    });
    cleanup = !this._events;
  } else {
    this.count--;
    cleanup = this.count === 0;
  }

  if (cleanup) this.cleanup();
}; // Cleans up memory bindings between the listener and the listenee.


Listening.prototype.cleanup = function () {
  delete this.listener._listeningTo[this.obj._listenId];
  if (!this.interop) delete this.obj._listeners[this.id];
}; // Aliases for backwards compatibility.


Events.bind = Events.on;
Events.unbind = Events.off;
// CONCATENATED MODULE: ./node_modules/lodash-es/clone.js

/** Used to compose bitmasks for cloning. */

var clone_CLONE_SYMBOLS_FLAG = 4;
/**
 * Creates a shallow clone of `value`.
 *
 * **Note:** This method is loosely based on the
 * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
 * and supports cloning arrays, array buffers, booleans, date objects, maps,
 * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
 * arrays. The own enumerable properties of `arguments` objects are cloned
 * as plain objects. An empty object is returned for uncloneable values such
 * as error objects, functions, DOM nodes, and WeakMaps.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to clone.
 * @returns {*} Returns the cloned value.
 * @see _.cloneDeep
 * @example
 *
 * var objects = [{ 'a': 1 }, { 'b': 2 }];
 *
 * var shallow = _.clone(objects);
 * console.log(shallow[0] === objects[0]);
 * // => true
 */

function clone(value) {
  return _baseClone(value, clone_CLONE_SYMBOLS_FLAG);
}

/* harmony default export */ var lodash_es_clone = (clone);
// CONCATENATED MODULE: ./node_modules/lodash-es/defaults.js




/** Used for built-in method references. */

var defaults_objectProto = Object.prototype;
/** Used to check objects for own properties. */

var defaults_hasOwnProperty = defaults_objectProto.hasOwnProperty;
/**
 * Assigns own and inherited enumerable string keyed properties of source
 * objects to the destination object for all destination properties that
 * resolve to `undefined`. Source objects are applied from left to right.
 * Once a property is set, additional values of the same property are ignored.
 *
 * **Note:** This method mutates `object`.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The destination object.
 * @param {...Object} [sources] The source objects.
 * @returns {Object} Returns `object`.
 * @see _.defaultsDeep
 * @example
 *
 * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
 * // => { 'a': 1, 'b': 2 }
 */

var defaults_defaults = _baseRest(function (object, sources) {
  object = Object(object);
  var index = -1;
  var length = sources.length;
  var guard = length > 2 ? sources[2] : undefined;

  if (guard && _isIterateeCall(sources[0], sources[1], guard)) {
    length = 1;
  }

  while (++index < length) {
    var source = sources[index];
    var props = lodash_es_keysIn(source);
    var propsIndex = -1;
    var propsLength = props.length;

    while (++propsIndex < propsLength) {
      var key = props[propsIndex];
      var value = object[key];

      if (value === undefined || lodash_es_eq(value, defaults_objectProto[key]) && !defaults_hasOwnProperty.call(object, key)) {
        object[key] = source[key];
      }
    }
  }

  return object;
});
/* harmony default export */ var lodash_es_defaults = (defaults_defaults);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseDelay.js
/** Error message constants. */
var _baseDelay_FUNC_ERROR_TEXT = 'Expected a function';
/**
 * The base implementation of `_.delay` and `_.defer` which accepts `args`
 * to provide to `func`.
 *
 * @private
 * @param {Function} func The function to delay.
 * @param {number} wait The number of milliseconds to delay invocation.
 * @param {Array} args The arguments to provide to `func`.
 * @returns {number|Object} Returns the timer id or timeout object.
 */

function baseDelay(func, wait, args) {
  if (typeof func != 'function') {
    throw new TypeError(_baseDelay_FUNC_ERROR_TEXT);
  }

  return setTimeout(function () {
    func.apply(undefined, args);
  }, wait);
}

/* harmony default export */ var _baseDelay = (baseDelay);
// CONCATENATED MODULE: ./node_modules/lodash-es/defer.js


/**
 * Defers invoking the `func` until the current call stack has cleared. Any
 * additional arguments are provided to `func` when it's invoked.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to defer.
 * @param {...*} [args] The arguments to invoke `func` with.
 * @returns {number} Returns the timer id.
 * @example
 *
 * _.defer(function(text) {
 *   console.log(text);
 * }, 'deferred');
 * // => Logs 'deferred' after one millisecond.
 */

var defer = _baseRest(function (func, args) {
  return _baseDelay(func, 1, args);
});
/* harmony default export */ var lodash_es_defer = (defer);
// CONCATENATED MODULE: ./node_modules/lodash-es/_basePropertyOf.js
/**
 * The base implementation of `_.propertyOf` without support for deep paths.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Function} Returns the new accessor function.
 */
function basePropertyOf(object) {
  return function (key) {
    return object == null ? undefined : object[key];
  };
}

/* harmony default export */ var _basePropertyOf = (basePropertyOf);
// CONCATENATED MODULE: ./node_modules/lodash-es/_escapeHtmlChar.js

/** Used to map characters to HTML entities. */

var htmlEscapes = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;'
};
/**
 * Used by `_.escape` to convert characters to HTML entities.
 *
 * @private
 * @param {string} chr The matched character to escape.
 * @returns {string} Returns the escaped character.
 */

var escapeHtmlChar = _basePropertyOf(htmlEscapes);
/* harmony default export */ var _escapeHtmlChar = (escapeHtmlChar);
// CONCATENATED MODULE: ./node_modules/lodash-es/escape.js


/** Used to match HTML entities and HTML characters. */

var reUnescapedHtml = /[&<>"']/g,
    reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
/**
 * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
 * corresponding HTML entities.
 *
 * **Note:** No other characters are escaped. To escape additional
 * characters use a third-party library like [_he_](https://mths.be/he).
 *
 * Though the ">" character is escaped for symmetry, characters like
 * ">" and "/" don't need escaping in HTML and have no special meaning
 * unless they're part of a tag or unquoted attribute value. See
 * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
 * (under "semi-related fun fact") for more details.
 *
 * When working with HTML you should always
 * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
 * XSS vectors.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category String
 * @param {string} [string=''] The string to escape.
 * @returns {string} Returns the escaped string.
 * @example
 *
 * _.escape('fred, barney, & pebbles');
 * // => 'fred, barney, &amp; pebbles'
 */

function escape_escape(string) {
  string = lodash_es_toString(string);
  return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, _escapeHtmlChar) : string;
}

/* harmony default export */ var lodash_es_escape = (escape_escape);
// CONCATENATED MODULE: ./node_modules/lodash-es/_createBaseFor.js
/**
 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
 *
 * @private
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new base function.
 */
function createBaseFor(fromRight) {
  return function (object, iteratee, keysFunc) {
    var index = -1,
        iterable = Object(object),
        props = keysFunc(object),
        length = props.length;

    while (length--) {
      var key = props[fromRight ? length : ++index];

      if (iteratee(iterable[key], key, iterable) === false) {
        break;
      }
    }

    return object;
  };
}

/* harmony default export */ var _createBaseFor = (createBaseFor);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseFor.js

/**
 * The base implementation of `baseForOwn` which iterates over `object`
 * properties returned by `keysFunc` and invokes `iteratee` for each property.
 * Iteratee functions may exit iteration early by explicitly returning `false`.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @returns {Object} Returns `object`.
 */

var baseFor = _createBaseFor();
/* harmony default export */ var _baseFor = (baseFor);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseForOwn.js


/**
 * The base implementation of `_.forOwn` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Object} Returns `object`.
 */

function baseForOwn(object, iteratee) {
  return object && _baseFor(object, iteratee, lodash_es_keys);
}

/* harmony default export */ var _baseForOwn = (baseForOwn);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseInverter.js

/**
 * The base implementation of `_.invert` and `_.invertBy` which inverts
 * `object` with values transformed by `iteratee` and set by `setter`.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} setter The function to set `accumulator` values.
 * @param {Function} iteratee The iteratee to transform values.
 * @param {Object} accumulator The initial inverted object.
 * @returns {Function} Returns `accumulator`.
 */

function baseInverter(object, setter, iteratee, accumulator) {
  _baseForOwn(object, function (value, key, object) {
    setter(accumulator, iteratee(value), key, object);
  });
  return accumulator;
}

/* harmony default export */ var _baseInverter = (baseInverter);
// CONCATENATED MODULE: ./node_modules/lodash-es/_createInverter.js

/**
 * Creates a function like `_.invertBy`.
 *
 * @private
 * @param {Function} setter The function to set accumulator values.
 * @param {Function} toIteratee The function to resolve iteratees.
 * @returns {Function} Returns the new inverter function.
 */

function createInverter(setter, toIteratee) {
  return function (object, iteratee) {
    return _baseInverter(object, setter, toIteratee(iteratee), {});
  };
}

/* harmony default export */ var _createInverter = (createInverter);
// CONCATENATED MODULE: ./node_modules/lodash-es/invert.js



/** Used for built-in method references. */

var invert_objectProto = Object.prototype;
/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */

var invert_nativeObjectToString = invert_objectProto.toString;
/**
 * Creates an object composed of the inverted keys and values of `object`.
 * If `object` contains duplicate values, subsequent values overwrite
 * property assignments of previous values.
 *
 * @static
 * @memberOf _
 * @since 0.7.0
 * @category Object
 * @param {Object} object The object to invert.
 * @returns {Object} Returns the new inverted object.
 * @example
 *
 * var object = { 'a': 1, 'b': 2, 'c': 1 };
 *
 * _.invert(object);
 * // => { '1': 'c', '2': 'b' }
 */

var invert = _createInverter(function (result, value, key) {
  if (value != null && typeof value.toString != 'function') {
    value = invert_nativeObjectToString.call(value);
  }

  result[value] = key;
}, lodash_es_constant(lodash_es_identity));
/* harmony default export */ var lodash_es_invert = (invert);
// CONCATENATED MODULE: ./node_modules/lodash-es/_setCacheAdd.js
/** Used to stand-in for `undefined` hash values. */
var _setCacheAdd_HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
 * Adds `value` to the array cache.
 *
 * @private
 * @name add
 * @memberOf SetCache
 * @alias push
 * @param {*} value The value to cache.
 * @returns {Object} Returns the cache instance.
 */

function setCacheAdd(value) {
  this.__data__.set(value, _setCacheAdd_HASH_UNDEFINED);

  return this;
}

/* harmony default export */ var _setCacheAdd = (setCacheAdd);
// CONCATENATED MODULE: ./node_modules/lodash-es/_setCacheHas.js
/**
 * Checks if `value` is in the array cache.
 *
 * @private
 * @name has
 * @memberOf SetCache
 * @param {*} value The value to search for.
 * @returns {number} Returns `true` if `value` is found, else `false`.
 */
function setCacheHas(value) {
  return this.__data__.has(value);
}

/* harmony default export */ var _setCacheHas = (setCacheHas);
// CONCATENATED MODULE: ./node_modules/lodash-es/_SetCache.js



/**
 *
 * Creates an array cache object to store unique values.
 *
 * @private
 * @constructor
 * @param {Array} [values] The values to cache.
 */

function SetCache(values) {
  var index = -1,
      length = values == null ? 0 : values.length;
  this.__data__ = new _MapCache();

  while (++index < length) {
    this.add(values[index]);
  }
} // Add methods to `SetCache`.


SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
SetCache.prototype.has = _setCacheHas;
/* harmony default export */ var _SetCache = (SetCache);
// CONCATENATED MODULE: ./node_modules/lodash-es/_arraySome.js
/**
 * A specialized version of `_.some` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if any element passes the predicate check,
 *  else `false`.
 */
function arraySome(array, predicate) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    if (predicate(array[index], index, array)) {
      return true;
    }
  }

  return false;
}

/* harmony default export */ var _arraySome = (arraySome);
// CONCATENATED MODULE: ./node_modules/lodash-es/_cacheHas.js
/**
 * Checks if a `cache` value for `key` exists.
 *
 * @private
 * @param {Object} cache The cache to query.
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function cacheHas(cache, key) {
  return cache.has(key);
}

/* harmony default export */ var _cacheHas = (cacheHas);
// CONCATENATED MODULE: ./node_modules/lodash-es/_equalArrays.js



/** Used to compose bitmasks for value comparisons. */

var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;
/**
 * A specialized version of `baseIsEqualDeep` for arrays with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Array} array The array to compare.
 * @param {Array} other The other array to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `array` and `other` objects.
 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
 */

function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
      arrLength = array.length,
      othLength = other.length;

  if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
    return false;
  } // Check that cyclic values are equal.


  var arrStacked = stack.get(array);
  var othStacked = stack.get(other);

  if (arrStacked && othStacked) {
    return arrStacked == other && othStacked == array;
  }

  var index = -1,
      result = true,
      seen = bitmask & COMPARE_UNORDERED_FLAG ? new _SetCache() : undefined;
  stack.set(array, other);
  stack.set(other, array); // Ignore non-index properties.

  while (++index < arrLength) {
    var arrValue = array[index],
        othValue = other[index];

    if (customizer) {
      var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
    }

    if (compared !== undefined) {
      if (compared) {
        continue;
      }

      result = false;
      break;
    } // Recursively compare arrays (susceptible to call stack limits).


    if (seen) {
      if (!_arraySome(other, function (othValue, othIndex) {
        if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
          return seen.push(othIndex);
        }
      })) {
        result = false;
        break;
      }
    } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
      result = false;
      break;
    }
  }

  stack['delete'](array);
  stack['delete'](other);
  return result;
}

/* harmony default export */ var _equalArrays = (equalArrays);
// CONCATENATED MODULE: ./node_modules/lodash-es/_mapToArray.js
/**
 * Converts `map` to its key-value pairs.
 *
 * @private
 * @param {Object} map The map to convert.
 * @returns {Array} Returns the key-value pairs.
 */
function mapToArray(map) {
  var index = -1,
      result = Array(map.size);
  map.forEach(function (value, key) {
    result[++index] = [key, value];
  });
  return result;
}

/* harmony default export */ var _mapToArray = (mapToArray);
// CONCATENATED MODULE: ./node_modules/lodash-es/_setToArray.js
/**
 * Converts `set` to an array of its values.
 *
 * @private
 * @param {Object} set The set to convert.
 * @returns {Array} Returns the values.
 */
function setToArray(set) {
  var index = -1,
      result = Array(set.size);
  set.forEach(function (value) {
    result[++index] = value;
  });
  return result;
}

/* harmony default export */ var _setToArray = (setToArray);
// CONCATENATED MODULE: ./node_modules/lodash-es/_equalByTag.js






/** Used to compose bitmasks for value comparisons. */

var _equalByTag_COMPARE_PARTIAL_FLAG = 1,
    _equalByTag_COMPARE_UNORDERED_FLAG = 2;
/** `Object#toString` result references. */

var _equalByTag_boolTag = '[object Boolean]',
    _equalByTag_dateTag = '[object Date]',
    _equalByTag_errorTag = '[object Error]',
    _equalByTag_mapTag = '[object Map]',
    _equalByTag_numberTag = '[object Number]',
    _equalByTag_regexpTag = '[object RegExp]',
    _equalByTag_setTag = '[object Set]',
    _equalByTag_stringTag = '[object String]',
    _equalByTag_symbolTag = '[object Symbol]';
var _equalByTag_arrayBufferTag = '[object ArrayBuffer]',
    _equalByTag_dataViewTag = '[object DataView]';
/** Used to convert symbols to primitives and strings. */

var _equalByTag_symbolProto = _Symbol ? _Symbol.prototype : undefined,
    _equalByTag_symbolValueOf = _equalByTag_symbolProto ? _equalByTag_symbolProto.valueOf : undefined;
/**
 * A specialized version of `baseIsEqualDeep` for comparing objects of
 * the same `toStringTag`.
 *
 * **Note:** This function only supports comparing values with tags of
 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {string} tag The `toStringTag` of the objects to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */

function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  switch (tag) {
    case _equalByTag_dataViewTag:
      if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
        return false;
      }

      object = object.buffer;
      other = other.buffer;

    case _equalByTag_arrayBufferTag:
      if (object.byteLength != other.byteLength || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
        return false;
      }

      return true;

    case _equalByTag_boolTag:
    case _equalByTag_dateTag:
    case _equalByTag_numberTag:
      // Coerce booleans to `1` or `0` and dates to milliseconds.
      // Invalid dates are coerced to `NaN`.
      return lodash_es_eq(+object, +other);

    case _equalByTag_errorTag:
      return object.name == other.name && object.message == other.message;

    case _equalByTag_regexpTag:
    case _equalByTag_stringTag:
      // Coerce regexes to strings and treat strings, primitives and objects,
      // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
      // for more details.
      return object == other + '';

    case _equalByTag_mapTag:
      var convert = _mapToArray;

    case _equalByTag_setTag:
      var isPartial = bitmask & _equalByTag_COMPARE_PARTIAL_FLAG;
      convert || (convert = _setToArray);

      if (object.size != other.size && !isPartial) {
        return false;
      } // Assume cyclic values are equal.


      var stacked = stack.get(object);

      if (stacked) {
        return stacked == other;
      }

      bitmask |= _equalByTag_COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits).

      stack.set(object, other);
      var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
      stack['delete'](object);
      return result;

    case _equalByTag_symbolTag:
      if (_equalByTag_symbolValueOf) {
        return _equalByTag_symbolValueOf.call(object) == _equalByTag_symbolValueOf.call(other);
      }

  }

  return false;
}

/* harmony default export */ var _equalByTag = (equalByTag);
// CONCATENATED MODULE: ./node_modules/lodash-es/_equalObjects.js

/** Used to compose bitmasks for value comparisons. */

var _equalObjects_COMPARE_PARTIAL_FLAG = 1;
/** Used for built-in method references. */

var _equalObjects_objectProto = Object.prototype;
/** Used to check objects for own properties. */

var _equalObjects_hasOwnProperty = _equalObjects_objectProto.hasOwnProperty;
/**
 * A specialized version of `baseIsEqualDeep` for objects with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */

function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & _equalObjects_COMPARE_PARTIAL_FLAG,
      objProps = _getAllKeys(object),
      objLength = objProps.length,
      othProps = _getAllKeys(other),
      othLength = othProps.length;

  if (objLength != othLength && !isPartial) {
    return false;
  }

  var index = objLength;

  while (index--) {
    var key = objProps[index];

    if (!(isPartial ? key in other : _equalObjects_hasOwnProperty.call(other, key))) {
      return false;
    }
  } // Check that cyclic values are equal.


  var objStacked = stack.get(object);
  var othStacked = stack.get(other);

  if (objStacked && othStacked) {
    return objStacked == other && othStacked == object;
  }

  var result = true;
  stack.set(object, other);
  stack.set(other, object);
  var skipCtor = isPartial;

  while (++index < objLength) {
    key = objProps[index];
    var objValue = object[key],
        othValue = other[key];

    if (customizer) {
      var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
    } // Recursively compare objects (susceptible to call stack limits).


    if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
      result = false;
      break;
    }

    skipCtor || (skipCtor = key == 'constructor');
  }

  if (result && !skipCtor) {
    var objCtor = object.constructor,
        othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal.

    if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
      result = false;
    }
  }

  stack['delete'](object);
  stack['delete'](other);
  return result;
}

/* harmony default export */ var _equalObjects = (equalObjects);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsEqualDeep.js








/** Used to compose bitmasks for value comparisons. */

var _baseIsEqualDeep_COMPARE_PARTIAL_FLAG = 1;
/** `Object#toString` result references. */

var _baseIsEqualDeep_argsTag = '[object Arguments]',
    _baseIsEqualDeep_arrayTag = '[object Array]',
    _baseIsEqualDeep_objectTag = '[object Object]';
/** Used for built-in method references. */

var _baseIsEqualDeep_objectProto = Object.prototype;
/** Used to check objects for own properties. */

var _baseIsEqualDeep_hasOwnProperty = _baseIsEqualDeep_objectProto.hasOwnProperty;
/**
 * A specialized version of `baseIsEqual` for arrays and objects which performs
 * deep comparisons and tracks traversed objects enabling objects with circular
 * references to be compared.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */

function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  var objIsArr = lodash_es_isArray(object),
      othIsArr = lodash_es_isArray(other),
      objTag = objIsArr ? _baseIsEqualDeep_arrayTag : _getTag(object),
      othTag = othIsArr ? _baseIsEqualDeep_arrayTag : _getTag(other);
  objTag = objTag == _baseIsEqualDeep_argsTag ? _baseIsEqualDeep_objectTag : objTag;
  othTag = othTag == _baseIsEqualDeep_argsTag ? _baseIsEqualDeep_objectTag : othTag;
  var objIsObj = objTag == _baseIsEqualDeep_objectTag,
      othIsObj = othTag == _baseIsEqualDeep_objectTag,
      isSameTag = objTag == othTag;

  if (isSameTag && Object(isBuffer["a" /* default */])(object)) {
    if (!Object(isBuffer["a" /* default */])(other)) {
      return false;
    }

    objIsArr = true;
    objIsObj = false;
  }

  if (isSameTag && !objIsObj) {
    stack || (stack = new _Stack());
    return objIsArr || lodash_es_isTypedArray(object) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  }

  if (!(bitmask & _baseIsEqualDeep_COMPARE_PARTIAL_FLAG)) {
    var objIsWrapped = objIsObj && _baseIsEqualDeep_hasOwnProperty.call(object, '__wrapped__'),
        othIsWrapped = othIsObj && _baseIsEqualDeep_hasOwnProperty.call(other, '__wrapped__');

    if (objIsWrapped || othIsWrapped) {
      var objUnwrapped = objIsWrapped ? object.value() : object,
          othUnwrapped = othIsWrapped ? other.value() : other;
      stack || (stack = new _Stack());
      return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
    }
  }

  if (!isSameTag) {
    return false;
  }

  stack || (stack = new _Stack());
  return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}

/* harmony default export */ var _baseIsEqualDeep = (baseIsEqualDeep);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsEqual.js


/**
 * The base implementation of `_.isEqual` which supports partial comparisons
 * and tracks traversed objects.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @param {boolean} bitmask The bitmask flags.
 *  1 - Unordered comparison
 *  2 - Partial comparison
 * @param {Function} [customizer] The function to customize comparisons.
 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 */

function baseIsEqual(value, other, bitmask, customizer, stack) {
  if (value === other) {
    return true;
  }

  if (value == null || other == null || !lodash_es_isObjectLike(value) && !lodash_es_isObjectLike(other)) {
    return value !== value && other !== other;
  }

  return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}

/* harmony default export */ var _baseIsEqual = (baseIsEqual);
// CONCATENATED MODULE: ./node_modules/lodash-es/isEqual.js

/**
 * Performs a deep comparison between two values to determine if they are
 * equivalent.
 *
 * **Note:** This method supports comparing arrays, array buffers, booleans,
 * date objects, error objects, maps, numbers, `Object` objects, regexes,
 * sets, strings, symbols, and typed arrays. `Object` objects are compared
 * by their own, not inherited, enumerable properties. Functions and DOM
 * nodes are compared by strict equality, i.e. `===`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.isEqual(object, other);
 * // => true
 *
 * object === other;
 * // => false
 */

function isEqual(value, other) {
  return _baseIsEqual(value, other);
}

/* harmony default export */ var lodash_es_isEqual = (isEqual);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsMatch.js


/** Used to compose bitmasks for value comparisons. */

var _baseIsMatch_COMPARE_PARTIAL_FLAG = 1,
    _baseIsMatch_COMPARE_UNORDERED_FLAG = 2;
/**
 * The base implementation of `_.isMatch` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The object to inspect.
 * @param {Object} source The object of property values to match.
 * @param {Array} matchData The property names, values, and compare flags to match.
 * @param {Function} [customizer] The function to customize comparisons.
 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
 */

function baseIsMatch(object, source, matchData, customizer) {
  var index = matchData.length,
      length = index,
      noCustomizer = !customizer;

  if (object == null) {
    return !length;
  }

  object = Object(object);

  while (index--) {
    var data = matchData[index];

    if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
      return false;
    }
  }

  while (++index < length) {
    data = matchData[index];
    var key = data[0],
        objValue = object[key],
        srcValue = data[1];

    if (noCustomizer && data[2]) {
      if (objValue === undefined && !(key in object)) {
        return false;
      }
    } else {
      var stack = new _Stack();

      if (customizer) {
        var result = customizer(objValue, srcValue, key, object, source, stack);
      }

      if (!(result === undefined ? _baseIsEqual(srcValue, objValue, _baseIsMatch_COMPARE_PARTIAL_FLAG | _baseIsMatch_COMPARE_UNORDERED_FLAG, customizer, stack) : result)) {
        return false;
      }
    }
  }

  return true;
}

/* harmony default export */ var _baseIsMatch = (baseIsMatch);
// CONCATENATED MODULE: ./node_modules/lodash-es/_isStrictComparable.js

/**
 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` if suitable for strict
 *  equality comparisons, else `false`.
 */

function isStrictComparable(value) {
  return value === value && !lodash_es_isObject(value);
}

/* harmony default export */ var _isStrictComparable = (isStrictComparable);
// CONCATENATED MODULE: ./node_modules/lodash-es/_getMatchData.js


/**
 * Gets the property names, values, and compare flags of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the match data of `object`.
 */

function getMatchData(object) {
  var result = lodash_es_keys(object),
      length = result.length;

  while (length--) {
    var key = result[length],
        value = object[key];
    result[length] = [key, value, _isStrictComparable(value)];
  }

  return result;
}

/* harmony default export */ var _getMatchData = (getMatchData);
// CONCATENATED MODULE: ./node_modules/lodash-es/_matchesStrictComparable.js
/**
 * A specialized version of `matchesProperty` for source values suitable
 * for strict equality comparisons, i.e. `===`.
 *
 * @private
 * @param {string} key The key of the property to get.
 * @param {*} srcValue The value to match.
 * @returns {Function} Returns the new spec function.
 */
function matchesStrictComparable(key, srcValue) {
  return function (object) {
    if (object == null) {
      return false;
    }

    return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
  };
}

/* harmony default export */ var _matchesStrictComparable = (matchesStrictComparable);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseMatches.js



/**
 * The base implementation of `_.matches` which doesn't clone `source`.
 *
 * @private
 * @param {Object} source The object of property values to match.
 * @returns {Function} Returns the new spec function.
 */

function baseMatches(source) {
  var matchData = _getMatchData(source);

  if (matchData.length == 1 && matchData[0][2]) {
    return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
  }

  return function (object) {
    return object === source || _baseIsMatch(object, source, matchData);
  };
}

/* harmony default export */ var _baseMatches = (baseMatches);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseGet.js


/**
 * The base implementation of `_.get` without support for default values.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @returns {*} Returns the resolved value.
 */

function baseGet(object, path) {
  path = _castPath(path, object);
  var index = 0,
      length = path.length;

  while (object != null && index < length) {
    object = object[_toKey(path[index++])];
  }

  return index && index == length ? object : undefined;
}

/* harmony default export */ var _baseGet = (baseGet);
// CONCATENATED MODULE: ./node_modules/lodash-es/get.js

/**
 * Gets the value at `path` of `object`. If the resolved value is
 * `undefined`, the `defaultValue` is returned in its place.
 *
 * @static
 * @memberOf _
 * @since 3.7.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
 * @returns {*} Returns the resolved value.
 * @example
 *
 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
 *
 * _.get(object, 'a[0].b.c');
 * // => 3
 *
 * _.get(object, ['a', '0', 'b', 'c']);
 * // => 3
 *
 * _.get(object, 'a.b.c', 'default');
 * // => 'default'
 */

function get(object, path, defaultValue) {
  var result = object == null ? undefined : _baseGet(object, path);
  return result === undefined ? defaultValue : result;
}

/* harmony default export */ var lodash_es_get = (get);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseHasIn.js
/**
 * The base implementation of `_.hasIn` without support for deep paths.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {Array|string} key The key to check.
 * @returns {boolean} Returns `true` if `key` exists, else `false`.
 */
function baseHasIn(object, key) {
  return object != null && key in Object(object);
}

/* harmony default export */ var _baseHasIn = (baseHasIn);
// CONCATENATED MODULE: ./node_modules/lodash-es/hasIn.js


/**
 * Checks if `path` is a direct or inherited property of `object`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 * @example
 *
 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
 *
 * _.hasIn(object, 'a');
 * // => true
 *
 * _.hasIn(object, 'a.b');
 * // => true
 *
 * _.hasIn(object, ['a', 'b']);
 * // => true
 *
 * _.hasIn(object, 'b');
 * // => false
 */

function hasIn(object, path) {
  return object != null && _hasPath(object, path, _baseHasIn);
}

/* harmony default export */ var lodash_es_hasIn = (hasIn);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseMatchesProperty.js







/** Used to compose bitmasks for value comparisons. */

var _baseMatchesProperty_COMPARE_PARTIAL_FLAG = 1,
    _baseMatchesProperty_COMPARE_UNORDERED_FLAG = 2;
/**
 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
 *
 * @private
 * @param {string} path The path of the property to get.
 * @param {*} srcValue The value to match.
 * @returns {Function} Returns the new spec function.
 */

function baseMatchesProperty(path, srcValue) {
  if (_isKey(path) && _isStrictComparable(srcValue)) {
    return _matchesStrictComparable(_toKey(path), srcValue);
  }

  return function (object) {
    var objValue = lodash_es_get(object, path);
    return objValue === undefined && objValue === srcValue ? lodash_es_hasIn(object, path) : _baseIsEqual(srcValue, objValue, _baseMatchesProperty_COMPARE_PARTIAL_FLAG | _baseMatchesProperty_COMPARE_UNORDERED_FLAG);
  };
}

/* harmony default export */ var _baseMatchesProperty = (baseMatchesProperty);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseProperty.js
/**
 * The base implementation of `_.property` without support for deep paths.
 *
 * @private
 * @param {string} key The key of the property to get.
 * @returns {Function} Returns the new accessor function.
 */
function baseProperty(key) {
  return function (object) {
    return object == null ? undefined : object[key];
  };
}

/* harmony default export */ var _baseProperty = (baseProperty);
// CONCATENATED MODULE: ./node_modules/lodash-es/_basePropertyDeep.js

/**
 * A specialized version of `baseProperty` which supports deep paths.
 *
 * @private
 * @param {Array|string} path The path of the property to get.
 * @returns {Function} Returns the new accessor function.
 */

function basePropertyDeep(path) {
  return function (object) {
    return _baseGet(object, path);
  };
}

/* harmony default export */ var _basePropertyDeep = (basePropertyDeep);
// CONCATENATED MODULE: ./node_modules/lodash-es/property.js




/**
 * Creates a function that returns the value at `path` of a given object.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Util
 * @param {Array|string} path The path of the property to get.
 * @returns {Function} Returns the new accessor function.
 * @example
 *
 * var objects = [
 *   { 'a': { 'b': 2 } },
 *   { 'a': { 'b': 1 } }
 * ];
 *
 * _.map(objects, _.property('a.b'));
 * // => [2, 1]
 *
 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
 * // => [1, 2]
 */

function property(path) {
  return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
}

/* harmony default export */ var lodash_es_property = (property);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIteratee.js





/**
 * The base implementation of `_.iteratee`.
 *
 * @private
 * @param {*} [value=_.identity] The value to convert to an iteratee.
 * @returns {Function} Returns the iteratee.
 */

function baseIteratee(value) {
  // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  if (typeof value == 'function') {
    return value;
  }

  if (value == null) {
    return lodash_es_identity;
  }

  if (typeof value == 'object') {
    return lodash_es_isArray(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value);
  }

  return lodash_es_property(value);
}

/* harmony default export */ var _baseIteratee = (baseIteratee);
// CONCATENATED MODULE: ./node_modules/lodash-es/iteratee.js


/** Used to compose bitmasks for cloning. */

var iteratee_CLONE_DEEP_FLAG = 1;
/**
 * Creates a function that invokes `func` with the arguments of the created
 * function. If `func` is a property name, the created function returns the
 * property value for a given element. If `func` is an array or object, the
 * created function returns `true` for elements that contain the equivalent
 * source properties, otherwise it returns `false`.
 *
 * @static
 * @since 4.0.0
 * @memberOf _
 * @category Util
 * @param {*} [func=_.identity] The value to convert to a callback.
 * @returns {Function} Returns the callback.
 * @example
 *
 * var users = [
 *   { 'user': 'barney', 'age': 36, 'active': true },
 *   { 'user': 'fred',   'age': 40, 'active': false }
 * ];
 *
 * // The `_.matches` iteratee shorthand.
 * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
 * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.filter(users, _.iteratee(['user', 'fred']));
 * // => [{ 'user': 'fred', 'age': 40 }]
 *
 * // The `_.property` iteratee shorthand.
 * _.map(users, _.iteratee('user'));
 * // => ['barney', 'fred']
 *
 * // Create custom iteratee shorthands.
 * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
 *   return !_.isRegExp(func) ? iteratee(func) : function(string) {
 *     return func.test(string);
 *   };
 * });
 *
 * _.filter(['abc', 'def'], /ef/);
 * // => ['def']
 */

function iteratee_iteratee(func) {
  return _baseIteratee(typeof func == 'function' ? func : _baseClone(func, iteratee_CLONE_DEEP_FLAG));
}

/* harmony default export */ var lodash_es_iteratee = (iteratee_iteratee);
// CONCATENATED MODULE: ./node_modules/lodash-es/last.js
/**
 * Gets the last element of `array`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to query.
 * @returns {*} Returns the last element of `array`.
 * @example
 *
 * _.last([1, 2, 3]);
 * // => 3
 */
function last(array) {
  var length = array == null ? 0 : array.length;
  return length ? array[length - 1] : undefined;
}

/* harmony default export */ var lodash_es_last = (last);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSlice.js
/**
 * The base implementation of `_.slice` without an iteratee call guard.
 *
 * @private
 * @param {Array} array The array to slice.
 * @param {number} [start=0] The start position.
 * @param {number} [end=array.length] The end position.
 * @returns {Array} Returns the slice of `array`.
 */
function baseSlice(array, start, end) {
  var index = -1,
      length = array.length;

  if (start < 0) {
    start = -start > length ? 0 : length + start;
  }

  end = end > length ? length : end;

  if (end < 0) {
    end += length;
  }

  length = start > end ? 0 : end - start >>> 0;
  start >>>= 0;
  var result = Array(length);

  while (++index < length) {
    result[index] = array[index + start];
  }

  return result;
}

/* harmony default export */ var _baseSlice = (baseSlice);
// CONCATENATED MODULE: ./node_modules/lodash-es/_parent.js


/**
 * Gets the parent value at `path` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array} path The path to get the parent value of.
 * @returns {*} Returns the parent value.
 */

function _parent_parent(object, path) {
  return path.length < 2 ? object : _baseGet(object, _baseSlice(path, 0, -1));
}

/* harmony default export */ var _parent = (_parent_parent);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseUnset.js




/**
 * The base implementation of `_.unset`.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {Array|string} path The property path to unset.
 * @returns {boolean} Returns `true` if the property is deleted, else `false`.
 */

function baseUnset(object, path) {
  path = _castPath(path, object);
  object = _parent(object, path);
  return object == null || delete object[_toKey(lodash_es_last(path))];
}

/* harmony default export */ var _baseUnset = (baseUnset);
// CONCATENATED MODULE: ./node_modules/lodash-es/_customOmitClone.js

/**
 * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
 * objects.
 *
 * @private
 * @param {*} value The value to inspect.
 * @param {string} key The key of the property to inspect.
 * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
 */

function customOmitClone(value) {
  return lodash_es_isPlainObject(value) ? undefined : value;
}

/* harmony default export */ var _customOmitClone = (customOmitClone);
// CONCATENATED MODULE: ./node_modules/lodash-es/_isFlattenable.js



/** Built-in value references. */

var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
/**
 * Checks if `value` is a flattenable `arguments` object or array.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
 */

function isFlattenable(value) {
  return lodash_es_isArray(value) || lodash_es_isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
}

/* harmony default export */ var _isFlattenable = (isFlattenable);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseFlatten.js


/**
 * The base implementation of `_.flatten` with support for restricting flattening.
 *
 * @private
 * @param {Array} array The array to flatten.
 * @param {number} depth The maximum recursion depth.
 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
 * @param {Array} [result=[]] The initial result value.
 * @returns {Array} Returns the new flattened array.
 */

function baseFlatten(array, depth, predicate, isStrict, result) {
  var index = -1,
      length = array.length;
  predicate || (predicate = _isFlattenable);
  result || (result = []);

  while (++index < length) {
    var value = array[index];

    if (depth > 0 && predicate(value)) {
      if (depth > 1) {
        // Recursively flatten arrays (susceptible to call stack limits).
        baseFlatten(value, depth - 1, predicate, isStrict, result);
      } else {
        _arrayPush(result, value);
      }
    } else if (!isStrict) {
      result[result.length] = value;
    }
  }

  return result;
}

/* harmony default export */ var _baseFlatten = (baseFlatten);
// CONCATENATED MODULE: ./node_modules/lodash-es/flatten.js

/**
 * Flattens `array` a single level deep.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to flatten.
 * @returns {Array} Returns the new flattened array.
 * @example
 *
 * _.flatten([1, [2, [3, [4]], 5]]);
 * // => [1, 2, [3, [4]], 5]
 */

function flatten(array) {
  var length = array == null ? 0 : array.length;
  return length ? _baseFlatten(array, 1) : [];
}

/* harmony default export */ var lodash_es_flatten = (flatten);
// CONCATENATED MODULE: ./node_modules/lodash-es/_flatRest.js



/**
 * A specialized version of `baseRest` which flattens the rest array.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @returns {Function} Returns the new function.
 */

function flatRest(func) {
  return _setToString(_overRest(func, undefined, lodash_es_flatten), func + '');
}

/* harmony default export */ var _flatRest = (flatRest);
// CONCATENATED MODULE: ./node_modules/lodash-es/omit.js








/** Used to compose bitmasks for cloning. */

var omit_CLONE_DEEP_FLAG = 1,
    omit_CLONE_FLAT_FLAG = 2,
    omit_CLONE_SYMBOLS_FLAG = 4;
/**
 * The opposite of `_.pick`; this method creates an object composed of the
 * own and inherited enumerable property paths of `object` that are not omitted.
 *
 * **Note:** This method is considerably slower than `_.pick`.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The source object.
 * @param {...(string|string[])} [paths] The property paths to omit.
 * @returns {Object} Returns the new object.
 * @example
 *
 * var object = { 'a': 1, 'b': '2', 'c': 3 };
 *
 * _.omit(object, ['a', 'c']);
 * // => { 'b': '2' }
 */

var omit = _flatRest(function (object, paths) {
  var result = {};

  if (object == null) {
    return result;
  }

  var isDeep = false;
  paths = _arrayMap(paths, function (path) {
    path = _castPath(path, object);
    isDeep || (isDeep = path.length > 1);
    return path;
  });
  _copyObject(object, _getAllKeysIn(object), result);

  if (isDeep) {
    result = _baseClone(result, omit_CLONE_DEEP_FLAG | omit_CLONE_FLAT_FLAG | omit_CLONE_SYMBOLS_FLAG, _customOmitClone);
  }

  var length = paths.length;

  while (length--) {
    _baseUnset(result, paths[length]);
  }

  return result;
});
/* harmony default export */ var lodash_es_omit = (omit);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSet.js





/**
 * The base implementation of `_.set`.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {Array|string} path The path of the property to set.
 * @param {*} value The value to set.
 * @param {Function} [customizer] The function to customize path creation.
 * @returns {Object} Returns `object`.
 */

function baseSet(object, path, value, customizer) {
  if (!lodash_es_isObject(object)) {
    return object;
  }

  path = _castPath(path, object);
  var index = -1,
      length = path.length,
      lastIndex = length - 1,
      nested = object;

  while (nested != null && ++index < length) {
    var key = _toKey(path[index]),
        newValue = value;

    if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
      return object;
    }

    if (index != lastIndex) {
      var objValue = nested[key];
      newValue = customizer ? customizer(objValue, key, nested) : undefined;

      if (newValue === undefined) {
        newValue = lodash_es_isObject(objValue) ? objValue : _isIndex(path[index + 1]) ? [] : {};
      }
    }

    _assignValue(nested, key, newValue);
    nested = nested[key];
  }

  return object;
}

/* harmony default export */ var _baseSet = (baseSet);
// CONCATENATED MODULE: ./node_modules/lodash-es/_basePickBy.js



/**
 * The base implementation of  `_.pickBy` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The source object.
 * @param {string[]} paths The property paths to pick.
 * @param {Function} predicate The function invoked per property.
 * @returns {Object} Returns the new object.
 */

function basePickBy(object, paths, predicate) {
  var index = -1,
      length = paths.length,
      result = {};

  while (++index < length) {
    var path = paths[index],
        value = _baseGet(object, path);

    if (predicate(value, path)) {
      _baseSet(result, _castPath(path, object), value);
    }
  }

  return result;
}

/* harmony default export */ var _basePickBy = (basePickBy);
// CONCATENATED MODULE: ./node_modules/lodash-es/_basePick.js


/**
 * The base implementation of `_.pick` without support for individual
 * property identifiers.
 *
 * @private
 * @param {Object} object The source object.
 * @param {string[]} paths The property paths to pick.
 * @returns {Object} Returns the new object.
 */

function basePick(object, paths) {
  return _basePickBy(object, paths, function (value, path) {
    return lodash_es_hasIn(object, path);
  });
}

/* harmony default export */ var _basePick = (basePick);
// CONCATENATED MODULE: ./node_modules/lodash-es/pick.js


/**
 * Creates an object composed of the picked `object` properties.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The source object.
 * @param {...(string|string[])} [paths] The property paths to pick.
 * @returns {Object} Returns the new object.
 * @example
 *
 * var object = { 'a': 1, 'b': '2', 'c': 3 };
 *
 * _.pick(object, ['a', 'c']);
 * // => { 'a': 1, 'c': 3 }
 */

var pick = _flatRest(function (object, paths) {
  return object == null ? {} : _basePick(object, paths);
});
/* harmony default export */ var lodash_es_pick = (pick);
// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/model.js
//     Backbone.js 1.4.0
//     (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
//     Backbone may be freely distributed under the MIT license.
// Model
// -----
// **Models** are the basic data object in the framework --
// frequently representing a row in a table in a database on your server.
// A discrete chunk of data and a bunch of useful, related methods for
// performing computations and transformations on that data.
// Create a new model with the specified attributes. A client id (`cid`)
// is automatically generated and assigned for you.


















const model_Model = function (attributes, options) {
  let attrs = attributes || {};
  options || (options = {});
  this.preinitialize.apply(this, arguments);
  this.cid = lodash_es_uniqueId(this.cidPrefix);
  this.attributes = {};
  if (options.collection) this.collection = options.collection;
  if (options.parse) attrs = this.parse(attrs, options) || {};
  const default_attrs = lodash_es_result(this, 'defaults');
  attrs = lodash_es_defaults(lodash_es_assignIn({}, default_attrs, attrs), default_attrs);
  this.set(attrs, options);
  this.changed = {};
  this.initialize.apply(this, arguments);
};
model_Model.extend = inherits; // Attach all inheritable methods to the Model prototype.

Object.assign(model_Model.prototype, Events, {
  // A hash of attributes whose current and previous value differ.
  changed: null,
  // The value returned during the last failed validation.
  validationError: null,
  // The default name for the JSON `id` attribute is `"id"`. MongoDB and
  // CouchDB users may want to set this to `"_id"`.
  idAttribute: 'id',
  // The prefix is used to create the client id which is used to identify models locally.
  // You may want to override this if you're experiencing name clashes with model ids.
  cidPrefix: 'c',
  // preinitialize is an empty function by default. You can override it with a function
  // or object.  preinitialize will run before any instantiation logic is run in the Model.
  preinitialize: function () {},
  // Initialize is an empty function by default. Override it with your own
  // initialization logic.
  initialize: function () {},
  // Return a copy of the model's `attributes` object.
  toJSON: function (options) {
    return lodash_es_clone(this.attributes);
  },
  // Proxy `Backbone.sync` by default -- but override this if you need
  // custom syncing semantics for *this* particular model.
  sync: function (method, model, options) {
    return getSyncMethod(this)(method, model, options);
  },
  // Get the value of an attribute.
  get: function (attr) {
    return this.attributes[attr];
  },
  keys: function () {
    return Object.keys(this.attributes);
  },
  values: function () {
    return Object.values(this.attributes);
  },
  pairs: function () {
    return this.entries();
  },
  entries: function () {
    return Object.entries(this.attributes);
  },
  invert: function () {
    return lodash_es_invert(this.attributes);
  },
  pick: function (...args) {
    if (args.length === 1 && Array.isArray(args[0])) {
      args = args[0];
    }

    return lodash_es_pick(this.attributes, args);
  },
  omit: function (...args) {
    if (args.length === 1 && Array.isArray(args[0])) {
      args = args[0];
    }

    return lodash_es_omit(this.attributes, args);
  },
  isEmpty: function () {
    return lodash_es_isEmpty(this.attributes);
  },
  // Get the HTML-escaped value of an attribute.
  escape: function (attr) {
    return lodash_es_escape(this.get(attr));
  },
  // Returns `true` if the attribute contains a value that is not null
  // or undefined.
  has: function (attr) {
    return this.get(attr) != null;
  },
  // Special-cased proxy to lodash's `matches` method.
  matches: function (attrs) {
    return !!lodash_es_iteratee(attrs, this)(this.attributes);
  },
  // Set a hash of model attributes on the object, firing `"change"`. This is
  // the core primitive operation of a model, updating the data and notifying
  // anyone who needs to know about the change in state. The heart of the beast.
  set: function (key, val, options) {
    if (key == null) return this; // Handle both `"key", value` and `{key: value}` -style arguments.

    let attrs;

    if (typeof key === 'object') {
      attrs = key;
      options = val;
    } else {
      (attrs = {})[key] = val;
    }

    options || (options = {}); // Run validation.

    if (!this._validate(attrs, options)) return false; // Extract attributes and options.

    const unset = options.unset;
    const silent = options.silent;
    const changes = [];
    const changing = this._changing;
    this._changing = true;

    if (!changing) {
      this._previousAttributes = lodash_es_clone(this.attributes);
      this.changed = {};
    }

    const current = this.attributes;
    const changed = this.changed;
    const prev = this._previousAttributes; // For each `set` attribute, update or delete the current value.

    for (const attr in attrs) {
      val = attrs[attr];
      if (!lodash_es_isEqual(current[attr], val)) changes.push(attr);

      if (!lodash_es_isEqual(prev[attr], val)) {
        changed[attr] = val;
      } else {
        delete changed[attr];
      }

      unset ? delete current[attr] : current[attr] = val;
    } // Update the `id`.


    if (this.idAttribute in attrs) this.id = this.get(this.idAttribute); // Trigger all relevant attribute changes.

    if (!silent) {
      if (changes.length) this._pending = options;

      for (let i = 0; i < changes.length; i++) {
        this.trigger('change:' + changes[i], this, current[changes[i]], options);
      }
    } // You might be wondering why there's a `while` loop here. Changes can
    // be recursively nested within `"change"` events.


    if (changing) return this;

    if (!silent) {
      while (this._pending) {
        options = this._pending;
        this._pending = false;
        this.trigger('change', this, options);
      }
    }

    this._pending = false;
    this._changing = false;
    return this;
  },
  // Remove an attribute from the model, firing `"change"`. `unset` is a noop
  // if the attribute doesn't exist.
  unset: function (attr, options) {
    return this.set(attr, undefined, lodash_es_assignIn({}, options, {
      unset: true
    }));
  },
  // Clear all attributes on the model, firing `"change"`.
  clear: function (options) {
    const attrs = {};

    for (const key in this.attributes) attrs[key] = undefined;

    return this.set(attrs, lodash_es_assignIn({}, options, {
      unset: true
    }));
  },
  // Determine if the model has changed since the last `"change"` event.
  // If you specify an attribute name, determine if that attribute has changed.
  hasChanged: function (attr) {
    if (attr == null) return !lodash_es_isEmpty(this.changed);
    return lodash_es_has(this.changed, attr);
  },
  // Return an object containing all the attributes that have changed, or
  // false if there are no changed attributes. Useful for determining what
  // parts of a view need to be updated and/or what attributes need to be
  // persisted to the server. Unset attributes will be set to undefined.
  // You can also pass an attributes object to diff against the model,
  // determining if there *would be* a change.
  changedAttributes: function (diff) {
    if (!diff) return this.hasChanged() ? lodash_es_clone(this.changed) : false;
    const old = this._changing ? this._previousAttributes : this.attributes;
    const changed = {};
    let hasChanged;

    for (const attr in diff) {
      const val = diff[attr];
      if (lodash_es_isEqual(old[attr], val)) continue;
      changed[attr] = val;
      hasChanged = true;
    }

    return hasChanged ? changed : false;
  },
  // Get the previous value of an attribute, recorded at the time the last
  // `"change"` event was fired.
  previous: function (attr) {
    if (attr == null || !this._previousAttributes) return null;
    return this._previousAttributes[attr];
  },
  // Get all of the attributes of the model at the time of the previous
  // `"change"` event.
  previousAttributes: function () {
    return lodash_es_clone(this._previousAttributes);
  },
  // Fetch the model from the server, merging the response with the model's
  // local attributes. Any changed attributes will trigger a "change" event.
  fetch: function (options) {
    options = lodash_es_assignIn({
      parse: true
    }, options);
    const model = this;
    const success = options.success;

    options.success = function (resp) {
      const serverAttrs = options.parse ? model.parse(resp, options) : resp;
      if (!model.set(serverAttrs, options)) return false;
      if (success) success.call(options.context, model, resp, options);
      model.trigger('sync', model, resp, options);
    };

    wrapError(this, options);
    return this.sync('read', this, options);
  },
  // Set a hash of model attributes, and sync the model to the server.
  // If the server returns an attributes hash that differs, the model's
  // state will be `set` again.
  save: function (key, val, options) {
    // Handle both `"key", value` and `{key: value}` -style arguments.
    let attrs;

    if (key == null || typeof key === 'object') {
      attrs = key;
      options = val;
    } else {
      (attrs = {})[key] = val;
    }

    options = lodash_es_assignIn({
      validate: true,
      parse: true
    }, options);
    const wait = options.wait;
    const return_promise = options.promise;
    const promise = return_promise && getResolveablePromise(); // If we're not waiting and attributes exist, save acts as
    // `set(attr).save(null, opts)` with validation. Otherwise, check if
    // the model will be valid when the attributes, if any, are set.

    if (attrs && !wait) {
      if (!this.set(attrs, options)) return false;
    } else if (!this._validate(attrs, options)) {
      return false;
    } // After a successful server-side save, the client is (optionally)
    // updated with the server-side state.


    const model = this;
    const success = options.success;
    const error = options.error;
    const attributes = this.attributes;

    options.success = function (resp) {
      // Ensure attributes are restored during synchronous saves.
      model.attributes = attributes;
      let serverAttrs = options.parse ? model.parse(resp, options) : resp;
      if (wait) serverAttrs = lodash_es_assignIn({}, attrs, serverAttrs);
      if (serverAttrs && !model.set(serverAttrs, options)) return false;
      if (success) success.call(options.context, model, resp, options);
      model.trigger('sync', model, resp, options);
      return_promise && promise.resolve();
    };

    options.error = function (model, e, options) {
      error && error.call(options.context, model, e, options);
      return_promise && promise.reject(e);
    };

    wrapError(this, options); // Set temporary attributes if `{wait: true}` to properly find new ids.

    if (attrs && wait) this.attributes = lodash_es_assignIn({}, attributes, attrs);
    const method = this.isNew() ? 'create' : options.patch ? 'patch' : 'update';
    if (method === 'patch' && !options.attrs) options.attrs = attrs;
    const xhr = this.sync(method, this, options); // Restore attributes.

    this.attributes = attributes;

    if (return_promise) {
      return promise;
    } else {
      return xhr;
    }
  },
  // Destroy this model on the server if it was already persisted.
  // Optimistically removes the model from its collection, if it has one.
  // If `wait: true` is passed, waits for the server to respond before removal.
  destroy: function (options) {
    options = options ? lodash_es_clone(options) : {};
    const model = this;
    const success = options.success;
    const wait = options.wait;

    const destroy = function () {
      model.stopListening();
      model.trigger('destroy', model, model.collection, options);
    };

    options.success = function (resp) {
      if (wait) destroy();
      if (success) success.call(options.context, model, resp, options);
      if (!model.isNew()) model.trigger('sync', model, resp, options);
    };

    let xhr = false;

    if (this.isNew()) {
      lodash_es_defer(options.success);
    } else {
      wrapError(this, options);
      xhr = this.sync('delete', this, options);
    }

    if (!wait) destroy();
    return xhr;
  },
  // Default URL for the model's representation on the server -- if you're
  // using Backbone's restful methods, override this to change the endpoint
  // that will be called.
  url: function () {
    const base = lodash_es_result(this, 'urlRoot') || lodash_es_result(this.collection, 'url') || urlError();
    if (this.isNew()) return base;
    const id = this.get(this.idAttribute);
    return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
  },
  // **parse** converts a response into the hash of attributes to be `set` on
  // the model. The default implementation is just to pass the response along.
  parse: function (resp, options) {
    return resp;
  },
  // Create a new model with identical attributes to this one.
  clone: function () {
    return new this.constructor(this.attributes);
  },
  // A model is new if it has never been saved to the server, and lacks an id.
  isNew: function () {
    return !this.has(this.idAttribute);
  },
  // Check if the model is currently in a valid state.
  isValid: function (options) {
    return this._validate({}, lodash_es_assignIn({}, options, {
      validate: true
    }));
  },
  // Run validation against the next complete set of model attributes,
  // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
  _validate: function (attrs, options) {
    if (!options.validate || !this.validate) return true;
    attrs = lodash_es_assignIn({}, this.attributes, attrs);
    const error = this.validationError = this.validate(attrs, options) || null;
    if (!error) return true;
    this.trigger('invalid', this, error, lodash_es_assignIn(options, {
      validationError: error
    }));
    return false;
  }
});
// CONCATENATED MODULE: ./node_modules/lodash-es/compact.js
/**
 * Creates an array with all falsey values removed. The values `false`, `null`,
 * `0`, `""`, `undefined`, and `NaN` are falsey.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to compact.
 * @returns {Array} Returns the new array of filtered values.
 * @example
 *
 * _.compact([0, 1, false, 2, '', 3]);
 * // => [1, 2, 3]
 */
function compact(array) {
  var index = -1,
      length = array == null ? 0 : array.length,
      resIndex = 0,
      result = [];

  while (++index < length) {
    var value = array[index];

    if (value) {
      result[resIndex++] = value;
    }
  }

  return result;
}

/* harmony default export */ var lodash_es_compact = (compact);
// CONCATENATED MODULE: ./src/headless/utils/core.js
/**
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description This is the core utilities module.
 */





const Strophe = core["g" /* default */].Strophe;
/**
 * The utils object
 * @namespace u
 */

const core_u = {};

core_u.isTagEqual = function (stanza, name) {
  if (stanza.nodeTree) {
    return core_u.isTagEqual(stanza.nodeTree, name);
  } else if (!(stanza instanceof Element)) {
    throw Error("isTagEqual called with value which isn't " + "an element or Strophe.Builder instance");
  } else {
    return Strophe.isTagEqual(stanza, name);
  }
};

const parser = new DOMParser();
const parserErrorNS = parser.parseFromString('invalid', 'text/xml').getElementsByTagName("parsererror")[0].namespaceURI;

core_u.getJIDFromURI = function (jid) {
  return jid.startsWith('xmpp:') && jid.endsWith('?join') ? jid.replace(/^xmpp:/, '').replace(/\?join$/, '') : jid;
};

core_u.toStanza = function (string) {
  const node = parser.parseFromString(string, "text/xml");

  if (node.getElementsByTagNameNS(parserErrorNS, 'parsererror').length) {
    throw new Error(`Parser Error: ${string}`);
  }

  return node.firstElementChild;
};

core_u.getLongestSubstring = function (string, candidates) {
  function reducer(accumulator, current_value) {
    if (string.startsWith(current_value)) {
      if (current_value.length > accumulator.length) {
        return current_value;
      } else {
        return accumulator;
      }
    } else {
      return accumulator;
    }
  }

  return candidates.reduce(reducer, '');
};

core_u.prefixMentions = function (message) {
  /* Given a message object, return its text with @ chars
   * inserted before the mentioned nicknames.
   */
  let text = message.get('message');
  (message.get('references') || []).sort((a, b) => b.begin - a.begin).forEach(ref => {
    text = `${text.slice(0, ref.begin)}@${text.slice(ref.begin)}`;
  });
  return text;
};

core_u.isValidJID = function (jid) {
  if (typeof jid === 'string') {
    return lodash_es_compact(jid.split('@')).length === 2 && !jid.startsWith('@') && !jid.endsWith('@');
  }

  return false;
};

core_u.isValidMUCJID = function (jid) {
  return !jid.startsWith('@') && !jid.endsWith('@');
};

core_u.isSameBareJID = function (jid1, jid2) {
  if (typeof jid1 !== 'string' || typeof jid2 !== 'string') {
    return false;
  }

  return Strophe.getBareJidFromJid(jid1).toLowerCase() === Strophe.getBareJidFromJid(jid2).toLowerCase();
};

core_u.isSameDomain = function (jid1, jid2) {
  if (typeof jid1 !== 'string' || typeof jid2 !== 'string') {
    return false;
  }

  return Strophe.getDomainFromJid(jid1).toLowerCase() === Strophe.getDomainFromJid(jid2).toLowerCase();
};

core_u.isNewMessage = function (message) {
  /* Given a stanza, determine whether it's a new
   * message, i.e. not a MAM archived one.
   */
  if (message instanceof Element) {
    return !(sizzle_default()(`result[xmlns="${Strophe.NS.MAM}"]`, message).length && sizzle_default()(`delay[xmlns="${Strophe.NS.DELAY}"]`, message).length);
  } else if (message instanceof model_Model) {
    message = message.attributes;
  }

  return !(message['is_delayed'] && message['is_archived']);
};

core_u.shouldCreateMessage = function (attrs) {
  return attrs['retracted'] || // Retraction received *before* the message
  !core_u.isEmptyMessage(attrs);
};

core_u.shouldCreateGroupchatMessage = function (attrs) {
  return attrs.nick && (core_u.shouldCreateMessage(attrs) || attrs.is_tombstone);
};

core_u.isEmptyMessage = function (attrs) {
  if (attrs instanceof model_Model) {
    attrs = attrs.attributes;
  }

  return !attrs['oob_url'] && !attrs['file'] && !(attrs['is_encrypted'] && attrs['plaintext']) && !attrs['message'];
}; //TODO: Remove


core_u.isOnlyChatStateNotification = function (msg) {
  if (msg instanceof Element) {
    // See XEP-0085 Chat State Notification
    return msg.querySelector('body') === null && (msg.querySelector('active') !== null || msg.querySelector('composing') !== null || msg.querySelector('inactive') !== null || msg.querySelector('paused') !== null || msg.querySelector('gone') !== null);
  }

  if (msg instanceof model_Model) {
    msg = msg.attributes;
  }

  return msg['chat_state'] && core_u.isEmptyMessage(msg);
};

core_u.isOnlyMessageDeliveryReceipt = function (msg) {
  if (msg instanceof Element) {
    // See XEP-0184 Message Delivery Receipts
    return msg.querySelector('body') === null && msg.querySelector('received') !== null;
  }

  if (msg instanceof model_Model) {
    msg = msg.attributes;
  }

  return msg['received'] && core_u.isEmptyMessage(msg);
};

core_u.isChatRoom = function (model) {
  return model && model.get('type') === 'chatroom';
};

core_u.isErrorObject = function (o) {
  return o instanceof Error;
};

core_u.isErrorStanza = function (stanza) {
  if (!lodash_es_isElement(stanza)) {
    return false;
  }

  return stanza.getAttribute('type') === 'error';
};

core_u.isForbiddenError = function (stanza) {
  if (!lodash_es_isElement(stanza)) {
    return false;
  }

  return sizzle_default()(`error[type="auth"] forbidden[xmlns="${Strophe.NS.STANZAS}"]`, stanza).length > 0;
};

core_u.isServiceUnavailableError = function (stanza) {
  if (!lodash_es_isElement(stanza)) {
    return false;
  }

  return sizzle_default()(`error[type="cancel"] service-unavailable[xmlns="${Strophe.NS.STANZAS}"]`, stanza).length > 0;
};
/**
 * Merge the second object into the first one.
 * @private
 * @method u#merge
 * @param { Object } first
 * @param { Object } second
 */


core_u.merge = function merge(first, second) {
  for (const k in second) {
    if (lodash_es_isObject(first[k])) {
      merge(first[k], second[k]);
    } else {
      first[k] = second[k];
    }
  }
};

core_u.getOuterWidth = function (el, include_margin = false) {
  let width = el.offsetWidth;

  if (!include_margin) {
    return width;
  }

  const style = window.getComputedStyle(el);
  width += parseInt(style.marginLeft ? style.marginLeft : 0, 10) + parseInt(style.marginRight ? style.marginRight : 0, 10);
  return width;
};
/**
 * Converts an HTML string into a DOM element.
 * Expects that the HTML string has only one top-level element,
 * i.e. not multiple ones.
 * @private
 * @method u#stringToElement
 * @param { String } s - The HTML string
 */


core_u.stringToElement = function (s) {
  var div = document.createElement('div');
  div.innerHTML = s;
  return div.firstElementChild;
};
/**
 * Checks whether the DOM element matches the given selector.
 * @private
 * @method u#matchesSelector
 * @param { DOMElement } el - The DOM element
 * @param { String } selector - The selector
 */


core_u.matchesSelector = function (el, selector) {
  const match = el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector;
  return match ? match.call(el, selector) : false;
};
/**
 * Returns a list of children of the DOM element that match the selector.
 * @private
 * @method u#queryChildren
 * @param { DOMElement } el - the DOM element
 * @param { String } selector - the selector they should be matched against
 */


core_u.queryChildren = function (el, selector) {
  return Array.from(el.childNodes).filter(el => core_u.matchesSelector(el, selector));
};

core_u.contains = function (attr, query) {
  const checker = (item, key) => item.get(key).toLowerCase().includes(query.toLowerCase());

  return function (item) {
    if (typeof attr === 'object') {
      return Object.keys(attr).reduce((acc, k) => acc || checker(item, k), false);
    } else if (typeof attr === 'string') {
      return checker(item, attr);
    } else {
      throw new TypeError('contains: wrong attribute type. Must be string or array.');
    }
  };
};

core_u.isOfType = function (type, item) {
  return item.get('type') == type;
};

core_u.isInstance = function (type, item) {
  return item instanceof type;
};

core_u.getAttribute = function (key, item) {
  return item.get(key);
};

core_u.contains.not = function (attr, query) {
  return function (item) {
    return !core_u.contains(attr, query)(item);
  };
};

core_u.rootContains = function (root, el) {
  // The document element does not have the contains method in IE.
  if (root === document && !root.contains) {
    return document.head.contains(el) || document.body.contains(el);
  }

  return root.contains ? root.contains(el) : window.HTMLElement.prototype.contains.call(root, el);
};

core_u.createFragmentFromText = function (markup) {
  /* Returns a DocumentFragment containing DOM nodes based on the
   * passed-in markup text.
   */
  // http://stackoverflow.com/questions/9334645/create-node-from-markup-string
  var frag = document.createDocumentFragment(),
      tmp = document.createElement('body'),
      child;
  tmp.innerHTML = markup; // Append elements in a loop to a DocumentFragment, so that the
  // browser does not re-render the document for each node.

  while (child = tmp.firstChild) {
    // eslint-disable-line no-cond-assign
    frag.appendChild(child);
  }

  return frag;
};

core_u.isPersistableModel = function (model) {
  return model.collection && model.collection.browserStorage;
};
/**
 * Returns a promise object on which `resolve` or `reject` can be called.
 * @private
 * @method u#getResolveablePromise
 */


core_u.getResolveablePromise = function () {
  const wrapper = {
    isResolved: false,
    isPending: true,
    isRejected: false
  };
  const promise = new Promise((resolve, reject) => {
    wrapper.resolve = resolve;
    wrapper.reject = reject;
  });
  Object.assign(promise, wrapper);
  promise.then(function (v) {
    promise.isResolved = true;
    promise.isPending = false;
    promise.isRejected = false;
    return v;
  }, function (e) {
    promise.isResolved = false;
    promise.isPending = false;
    promise.isRejected = true;
    throw e;
  });
  return promise;
};

core_u.interpolate = function (string, o) {
  return string.replace(/{{{([^{}]*)}}}/g, (a, b) => {
    var r = o[b];
    return typeof r === 'string' || typeof r === 'number' ? r : a;
  });
};
/**
 * Call the callback once all the events have been triggered
 * @private
 * @method u#onMultipleEvents
 * @param { Array } events: An array of objects, with keys `object` and
 *   `event`, representing the event name and the object it's triggered upon.
 * @param { Function } callback: The function to call once all events have
 *    been triggered.
 */


core_u.onMultipleEvents = function (events = [], callback) {
  let triggered = [];

  function handler(result) {
    triggered.push(result);

    if (events.length === triggered.length) {
      callback(triggered);
      triggered = [];
    }
  }

  events.forEach(e => e.object.on(e.event, handler));
};

core_u.safeSave = function (model, attributes, options) {
  if (core_u.isPersistableModel(model)) {
    model.save(attributes, options);
  } else {
    model.set(attributes, options);
  }
};

core_u.siblingIndex = function (el) {
  /* eslint-disable no-cond-assign */
  for (var i = 0; el = el.previousElementSibling; i++);

  return i;
};
/**
 * Returns the current word being written in the input element
 * @method u#getCurrentWord
 * @param {HTMLElement} input - The HTMLElement in which text is being entered
 * @param {integer} [index] - An optional rightmost boundary index. If given, the text
 *  value of the input element will only be considered up until this index.
 * @param {string} [delineator] - An optional string delineator to
 *  differentiate between words.
 * @private
 */


core_u.getCurrentWord = function (input, index, delineator) {
  if (!index) {
    index = input.selectionEnd || undefined;
  }

  let [word] = input.value.slice(0, index).split(/\s/).slice(-1);

  if (delineator) {
    [word] = word.split(delineator).slice(-1);
  }

  return word;
};

core_u.replaceCurrentWord = function (input, new_value) {
  const caret = input.selectionEnd || undefined,
        current_word = lodash_es_last(input.value.slice(0, caret).split(' ')),
        value = input.value;
  input.value = value.slice(0, caret - current_word.length) + `${new_value} ` + value.slice(caret);
  input.selectionEnd = caret - current_word.length + new_value.length + 1;
};

core_u.triggerEvent = function (el, name, type = "Event", bubbles = true, cancelable = true) {
  const evt = document.createEvent(type);
  evt.initEvent(name, bubbles, cancelable);
  el.dispatchEvent(evt);
};

core_u.getSelectValues = function (select) {
  const result = [];
  const options = select && select.options;

  for (var i = 0, iLen = options.length; i < iLen; i++) {
    const opt = options[i];

    if (opt.selected) {
      result.push(opt.value || opt.text);
    }
  }

  return result;
};

core_u.formatFingerprint = function (fp) {
  fp = fp.replace(/^05/, '');

  for (let i = 1; i < 8; i++) {
    const idx = i * 8 + i - 1;
    fp = fp.slice(0, idx) + ' ' + fp.slice(idx);
  }

  return fp;
};

core_u.appendArrayBuffer = function (buffer1, buffer2) {
  const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
  tmp.set(new Uint8Array(buffer1), 0);
  tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
  return tmp.buffer;
};

core_u.arrayBufferToHex = function (ab) {
  // https://stackoverflow.com/questions/40031688/javascript-arraybuffer-to-hex#40031979
  return Array.prototype.map.call(new Uint8Array(ab), x => ('00' + x.toString(16)).slice(-2)).join('');
};

core_u.arrayBufferToString = function (ab) {
  return new TextDecoder("utf-8").decode(ab);
};

core_u.stringToArrayBuffer = function (string) {
  const bytes = new TextEncoder("utf-8").encode(string);
  return bytes.buffer;
};

core_u.arrayBufferToBase64 = function (ab) {
  return btoa(new Uint8Array(ab).reduce((data, byte) => data + String.fromCharCode(byte), ''));
};

core_u.base64ToArrayBuffer = function (b64) {
  const binary_string = window.atob(b64),
        len = binary_string.length,
        bytes = new Uint8Array(len);

  for (let i = 0; i < len; i++) {
    bytes[i] = binary_string.charCodeAt(i);
  }

  return bytes.buffer;
};

core_u.getRandomInt = function (max) {
  return Math.floor(Math.random() * Math.floor(max));
};

core_u.placeCaretAtEnd = function (textarea) {
  if (textarea !== document.activeElement) {
    textarea.focus();
  } // Double the length because Opera is inconsistent about whether a carriage return is one character or two.


  const len = textarea.value.length * 2; // Timeout seems to be required for Blink

  setTimeout(() => textarea.setSelectionRange(len, len), 1); // Scroll to the bottom, in case we're in a tall textarea
  // (Necessary for Firefox and Chrome)

  this.scrollTop = 999999;
};

core_u.getUniqueId = function (suffix) {
  const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : r & 0x3 | 0x8;
    return v.toString(16);
  });

  if (typeof suffix === "string" || typeof suffix === "number") {
    return uuid + ":" + suffix;
  } else {
    return uuid;
  }
};
/**
 * Clears the specified timeout and interval.
 * @method u#clearTimers
 * @param {number} timeout - Id if the timeout to clear.
 * @param {number} interval - Id of the interval to clear.
 * @private
 * @copyright Simen Bekkhus 2016
 * @license MIT
 */


function clearTimers(timeout, interval) {
  clearTimeout(timeout);
  clearInterval(interval);
}
/**
 * Creates a {@link Promise} that resolves if the passed in function returns a truthy value.
 * Rejects if it throws or does not return truthy within the given max_wait.
 * @method u#waitUntil
 * @param {Function} func - The function called every check_delay,
 *  and the result of which is the resolved value of the promise.
 * @param {number} [max_wait=300] - The time to wait before rejecting the promise.
 * @param {number} [check_delay=3] - The time to wait before each invocation of {func}.
 * @returns {Promise} A promise resolved with the value of func,
 *  or rejected with the exception thrown by it or it times out.
 * @copyright Simen Bekkhus 2016
 * @license MIT
 */


core_u.waitUntil = function (func, max_wait = 300, check_delay = 3) {
  // Run the function once without setting up any listeners in case it's already true
  try {
    const result = func();

    if (result) {
      return Promise.resolve(result);
    }
  } catch (e) {
    return Promise.reject(e);
  }

  const promise = core_u.getResolveablePromise();
  const timeout_err = new Error();

  function checker() {
    try {
      const result = func();

      if (result) {
        clearTimers(max_wait_timeout, interval);
        promise.resolve(result);
      }
    } catch (e) {
      clearTimers(max_wait_timeout, interval);
      promise.reject(e);
    }
  }

  const interval = setInterval(checker, check_delay);

  function handler() {
    clearTimers(max_wait_timeout, interval);
    const err_msg = `Wait until promise timed out: \n\n${timeout_err.stack}`;
    console.trace();
    headless_log.error(err_msg);
    promise.reject(new Error(err_msg));
  }

  const max_wait_timeout = setTimeout(handler, max_wait);
  return promise;
};

/* harmony default export */ var utils_core = (core_u);
// CONCATENATED MODULE: ./src/headless/utils/stanza.js






const stanza_Strophe = core["g" /* default */].Strophe;
const $msg = core["g" /* default */].$msg;
const {
  NS
} = stanza_Strophe;

function getSpoilerAttributes(stanza) {
  const spoiler = sizzle_default()(`spoiler[xmlns="${stanza_Strophe.NS.SPOILER}"]`, stanza).pop();
  return {
    'is_spoiler': !!spoiler,
    'spoiler_hint': spoiler === null || spoiler === void 0 ? void 0 : spoiler.textContent
  };
}

function getOutOfBandAttributes(stanza) {
  const xform = sizzle_default()(`x[xmlns="${stanza_Strophe.NS.OUTOFBAND}"]`, stanza).pop();

  if (xform) {
    var _xform$querySelector, _xform$querySelector2;

    return {
      'oob_url': (_xform$querySelector = xform.querySelector('url')) === null || _xform$querySelector === void 0 ? void 0 : _xform$querySelector.textContent,
      'oob_desc': (_xform$querySelector2 = xform.querySelector('desc')) === null || _xform$querySelector2 === void 0 ? void 0 : _xform$querySelector2.textContent
    };
  }

  return {};
}

function getCorrectionAttributes(stanza, original_stanza) {
  const el = sizzle_default()(`replace[xmlns="${stanza_Strophe.NS.MESSAGE_CORRECT}"]`, stanza).pop();

  if (el) {
    const replace_id = el.getAttribute('id');
    const msgid = replace_id;

    if (replace_id) {
      const delay = sizzle_default()(`delay[xmlns="${stanza_Strophe.NS.DELAY}"]`, original_stanza).pop();
      const time = delay ? dayjs_min_default()(delay.getAttribute('stamp')).toISOString() : new Date().toISOString();
      return {
        msgid,
        replace_id,
        'edited': time
      };
    }
  }

  return {};
}

function getEncryptionAttributes(stanza, _converse) {
  var _converse$omemo_store;

  const encrypted = sizzle_default()(`encrypted[xmlns="${stanza_Strophe.NS.OMEMO}"]`, stanza).pop();
  const attrs = {
    'is_encrypted': !!encrypted
  };

  if (!encrypted || converse_core_api.settings.get('clear_cache_on_logout')) {
    return attrs;
  }

  const header = encrypted.querySelector('header');
  attrs['encrypted'] = {
    'device_id': header.getAttribute('sid')
  };
  const device_id = (_converse$omemo_store = _converse.omemo_store) === null || _converse$omemo_store === void 0 ? void 0 : _converse$omemo_store.get('device_id');
  const key = device_id && sizzle_default()(`key[rid="${device_id}"]`, encrypted).pop();

  if (key) {
    var _encrypted$querySelec;

    Object.assign(attrs.encrypted, {
      'iv': header.querySelector('iv').textContent,
      'key': key.textContent,
      'payload': ((_encrypted$querySelec = encrypted.querySelector('payload')) === null || _encrypted$querySelec === void 0 ? void 0 : _encrypted$querySelec.textContent) || null,
      'prekey': ['true', '1'].includes(key.getAttribute('prekey'))
    });
  }

  return attrs;
}

function isValidReceiptRequest(stanza, attrs) {
  return attrs.sender !== 'me' && !attrs.is_carbon && !attrs.is_archived && sizzle_default()(`request[xmlns="${stanza_Strophe.NS.RECEIPTS}"]`, stanza).length;
}

function getReceiptId(stanza) {
  const receipt = sizzle_default()(`received[xmlns="${stanza_Strophe.NS.RECEIPTS}"]`, stanza).pop();
  return receipt === null || receipt === void 0 ? void 0 : receipt.getAttribute('id');
}
/**
 * Returns the XEP-0085 chat state contained in a message stanza
 * @private
 * @param { XMLElement } stanza - The message stanza
 */


function getChatState(stanza) {
  var _sizzle$pop;

  return (_sizzle$pop = sizzle_default()(`
        composing[xmlns="${NS.CHATSTATES}"],
        paused[xmlns="${NS.CHATSTATES}"],
        inactive[xmlns="${NS.CHATSTATES}"],
        active[xmlns="${NS.CHATSTATES}"],
        gone[xmlns="${NS.CHATSTATES}"]`, stanza).pop()) === null || _sizzle$pop === void 0 ? void 0 : _sizzle$pop.nodeName;
}
/**
 * Determines whether the passed in stanza is a XEP-0280 Carbon
 * @private
 * @param { XMLElement } stanza - The message stanza
 * @returns { Boolean }
 */


function isCarbon(stanza) {
  const xmlns = stanza_Strophe.NS.CARBONS;
  return sizzle_default()(`message > received[xmlns="${xmlns}"]`, stanza).length > 0 || sizzle_default()(`message > sent[xmlns="${xmlns}"]`, stanza).length > 0;
}
/**
 * Extract the XEP-0359 stanza IDs from the passed in stanza
 * and return a map containing them.
 * @private
 * @param { XMLElement } stanza - The message stanza
 * @returns { Object }
 */


function getStanzaIDs(stanza, original_stanza) {
  const attrs = {}; // Store generic stanza ids

  const sids = sizzle_default()(`stanza-id[xmlns="${stanza_Strophe.NS.SID}"]`, stanza);
  const sid_attrs = sids.reduce((acc, s) => {
    acc[`stanza_id ${s.getAttribute('by')}`] = s.getAttribute('id');
    return acc;
  }, {});
  Object.assign(attrs, sid_attrs); // Store the archive id

  const result = sizzle_default()(`message > result[xmlns="${stanza_Strophe.NS.MAM}"]`, original_stanza).pop();

  if (result) {
    const by_jid = original_stanza.getAttribute('from') || converse_core_converse.bare_jid;

    attrs[`stanza_id ${by_jid}`] = result.getAttribute('id');
  } // Store the origin id


  const origin_id = sizzle_default()(`origin-id[xmlns="${stanza_Strophe.NS.SID}"]`, stanza).pop();

  if (origin_id) {
    attrs['origin_id'] = origin_id.getAttribute('id');
  }

  return attrs;
}
/**
 * @private
 * @param { XMLElement } stanza - The message stanza
 * @param { XMLElement } original_stanza - The original stanza, that contains the
 *  message stanza, if it was contained, otherwise it's the message stanza itself.
 * @returns { Object }
 */


function getModerationAttributes(stanza) {
  const fastening = sizzle_default()(`apply-to[xmlns="${stanza_Strophe.NS.FASTEN}"]`, stanza).pop();

  if (fastening) {
    const applies_to_id = fastening.getAttribute('id');
    const moderated = sizzle_default()(`moderated[xmlns="${stanza_Strophe.NS.MODERATE}"]`, fastening).pop();

    if (moderated) {
      const retracted = sizzle_default()(`retract[xmlns="${stanza_Strophe.NS.RETRACT}"]`, moderated).pop();

      if (retracted) {
        var _moderated$querySelec;

        return {
          'editable': false,
          'moderated': 'retracted',
          'moderated_by': moderated.getAttribute('by'),
          'moderated_id': applies_to_id,
          'moderation_reason': (_moderated$querySelec = moderated.querySelector('reason')) === null || _moderated$querySelec === void 0 ? void 0 : _moderated$querySelec.textContent
        };
      }
    }
  } else {
    const tombstone = sizzle_default()(`> moderated[xmlns="${stanza_Strophe.NS.MODERATE}"]`, stanza).pop();

    if (tombstone) {
      const retracted = sizzle_default()(`retracted[xmlns="${stanza_Strophe.NS.RETRACT}"]`, tombstone).pop();

      if (retracted) {
        var _tombstone$querySelec;

        return {
          'editable': false,
          'is_tombstone': true,
          'moderated_by': tombstone.getAttribute('by'),
          'retracted': tombstone.getAttribute('stamp'),
          'moderation_reason': (_tombstone$querySelec = tombstone.querySelector('reason')) === null || _tombstone$querySelec === void 0 ? void 0 : _tombstone$querySelec.textContent
        };
      }
    }
  }

  return {};
}
/**
 * @private
 * @param { XMLElement } stanza - The message stanza
 * @param { XMLElement } original_stanza - The original stanza, that contains the
 *  message stanza, if it was contained, otherwise it's the message stanza itself.
 * @returns { Object }
 */


function getRetractionAttributes(stanza, original_stanza) {
  const fastening = sizzle_default()(`> apply-to[xmlns="${stanza_Strophe.NS.FASTEN}"]`, stanza).pop();

  if (fastening) {
    const applies_to_id = fastening.getAttribute('id');
    const retracted = sizzle_default()(`> retract[xmlns="${stanza_Strophe.NS.RETRACT}"]`, fastening).pop();

    if (retracted) {
      const delay = sizzle_default()(`delay[xmlns="${stanza_Strophe.NS.DELAY}"]`, original_stanza).pop();
      const time = delay ? dayjs_min_default()(delay.getAttribute('stamp')).toISOString() : new Date().toISOString();
      return {
        'editable': false,
        'retracted': time,
        'retracted_id': applies_to_id
      };
    }
  } else {
    const tombstone = sizzle_default()(`> retracted[xmlns="${stanza_Strophe.NS.RETRACT}"]`, stanza).pop();

    if (tombstone) {
      return {
        'editable': false,
        'is_tombstone': true,
        'retracted': tombstone.getAttribute('stamp')
      };
    }
  }

  return {};
}

function getReferences(stanza) {
  var _stanza$querySelector;

  const text = (_stanza$querySelector = stanza.querySelector('body')) === null || _stanza$querySelector === void 0 ? void 0 : _stanza$querySelector.textContent;
  return sizzle_default()(`reference[xmlns="${stanza_Strophe.NS.REFERENCE}"]`, stanza).map(ref => {
    const begin = ref.getAttribute('begin');
    const end = ref.getAttribute('end');
    return {
      'begin': begin,
      'end': end,
      'type': ref.getAttribute('type'),
      'value': text.slice(begin, end),
      'uri': ref.getAttribute('uri')
    };
  });
}

function rejectMessage(stanza, text) {
  // Reject an incoming message by replying with an error message of type "cancel".
  converse_core_api.send($msg({
    'to': stanza.getAttribute('from'),
    'type': 'error',
    'id': stanza.getAttribute('id')
  }).c('error', {
    'type': 'cancel'
  }).c('not-allowed', {
    xmlns: "urn:ietf:params:xml:ns:xmpp-stanzas"
  }).up().c('text', {
    xmlns: "urn:ietf:params:xml:ns:xmpp-stanzas"
  }).t(text));
  headless_log.warn(`Rejecting message stanza with the following reason: ${text}`);
  headless_log.warn(stanza);
}
/**
 * Returns the human readable error message contained in a `groupchat` message stanza of type `error`.
 * @private
 * @param { XMLElement } stanza - The message stanza
 */


function getErrorAttributes(stanza) {
  if (stanza.getAttribute('type') === 'error') {
    const error = stanza.querySelector('error');
    const text = sizzle_default()(`text[xmlns="${stanza_Strophe.NS.STANZAS}"]`, error).pop();
    return {
      'is_error': true,
      'error_text': text === null || text === void 0 ? void 0 : text.textContent,
      'error_type': error.getAttribute('type'),
      'error_condition': error.firstElementChild.nodeName
    };
  }

  return {};
}

class StanzaParseError extends Error {
  constructor(message, stanza) {
    super(message, stanza);
    this.name = 'StanzaParseError';
    this.stanza = stanza;
  }

}

function rejectUnencapsulatedForward(stanza) {
  const bare_forward = sizzle_default()(`message > forwarded[xmlns="${stanza_Strophe.NS.FORWARD}"]`, stanza).length;

  if (bare_forward) {
    rejectMessage(stanza, 'Forwarded messages not part of an encapsulating protocol are not supported');
    const from_jid = stanza.getAttribute('from');
    return new StanzaParseError(`Ignoring unencapsulated forwarded message from ${from_jid}`, stanza);
  }
}
/**
 * The stanza utils object. Contains utility functions related to stanza processing.
 * @namespace st
 */


const st = {
  isHeadline(stanza) {
    return stanza.getAttribute('type') === 'headline';
  },

  isServerMessage(stanza) {
    const from_jid = stanza.getAttribute('from');

    if (stanza.getAttribute('type') !== 'error' && from_jid && !from_jid.includes('@')) {
      // Some servers (e.g. Prosody) don't set the stanza
      // type to "headline" when sending server messages.
      // For now we check if an @ signal is included, and if not,
      // we assume it's a headline stanza.
      return true;
    }

    return false;
  },

  /**
   * Determines whether the passed in stanza is a XEP-0333 Chat Marker
   * @private
   * @method st#getChatMarker
   * @param { XMLElement } stanza - The message stanza
   * @returns { Boolean }
   */
  getChatMarker(stanza) {
    // If we receive more than one marker (which shouldn't happen), we take
    // the highest level of acknowledgement.
    return sizzle_default()(`
            acknowledged[xmlns="${stanza_Strophe.NS.MARKERS}"],
            displayed[xmlns="${stanza_Strophe.NS.MARKERS}"],
            received[xmlns="${stanza_Strophe.NS.MARKERS}"]`, stanza).pop();
  },

  /**
   * Determines whether the passed in stanza is a XEP-0313 MAM stanza
   * @private
   * @method st#isArchived
   * @param { XMLElement } stanza - The message stanza
   * @returns { Boolean }
   */
  isArchived(original_stanza) {
    return !!sizzle_default()(`message > result[xmlns="${stanza_Strophe.NS.MAM}"]`, original_stanza).pop();
  },

  /**
   * Returns an object containing all attribute names and values for a particular element.
   * @method st#getAttributes
   * @param { XMLElement } stanza
   * @returns { Object }
   */
  getAttributes(stanza) {
    return stanza.getAttributeNames().reduce((acc, name) => {
      acc[name] = stanza_Strophe.xmlunescape(stanza.getAttribute(name));
      return acc;
    }, {});
  },

  /**
   * Parses a passed in message stanza and returns an object of attributes.
   * @method st#parseMessage
   * @param { XMLElement } stanza - The message stanza
   * @param { _converse } _converse
   * @returns { (MessageAttributes|Error) }
   */
  async parseMessage(stanza, _converse) {
    var _stanza$querySelector2, _stanza$querySelector3, _contact, _contact$attributes, _stanza$querySelector4, _stanza$querySelector5;

    const err = rejectUnencapsulatedForward(stanza);

    if (err) {
      return err;
    }

    let to_jid = stanza.getAttribute('to');
    const to_resource = stanza_Strophe.getResourceFromJid(to_jid);

    if (converse_core_api.settings.get('filter_by_resource') && to_resource && to_resource !== _converse.resource) {
      return new StanzaParseError(`Ignoring incoming message intended for a different resource: ${to_jid}`, stanza);
    }

    const original_stanza = stanza;

    let from_jid = stanza.getAttribute('from') || _converse.bare_jid;

    if (isCarbon(stanza)) {
      if (from_jid === _converse.bare_jid) {
        const selector = `[xmlns="${stanza_Strophe.NS.CARBONS}"] > forwarded[xmlns="${stanza_Strophe.NS.FORWARD}"] > message`;
        stanza = sizzle_default()(selector, stanza).pop();
        to_jid = stanza.getAttribute('to');
        from_jid = stanza.getAttribute('from');
      } else {
        // Prevent message forging via carbons: https://xmpp.org/extensions/xep-0280.html#security
        rejectMessage(stanza, 'Rejecting carbon from invalid JID');
        return new StanzaParseError(`Rejecting carbon from invalid JID ${to_jid}`, stanza);
      }
    }

    const is_archived = st.isArchived(stanza);

    if (is_archived) {
      if (from_jid === _converse.bare_jid) {
        const selector = `[xmlns="${stanza_Strophe.NS.MAM}"] > forwarded[xmlns="${stanza_Strophe.NS.FORWARD}"] > message`;
        stanza = sizzle_default()(selector, stanza).pop();
        to_jid = stanza.getAttribute('to');
        from_jid = stanza.getAttribute('from');
      } else {
        return new StanzaParseError(`Invalid Stanza: alleged MAM message from ${stanza.getAttribute('from')}`, stanza);
      }
    }

    const from_bare_jid = stanza_Strophe.getBareJidFromJid(from_jid);
    const is_me = from_bare_jid === _converse.bare_jid;

    if (is_me && to_jid === null) {
      return new StanzaParseError(`Don't know how to handle message stanza without 'to' attribute. ${stanza.outerHTML}`, stanza);
    }

    const is_headline = st.isHeadline(stanza);
    const is_server_message = st.isServerMessage(stanza);
    let contact, contact_jid;

    if (!is_headline && !is_server_message) {
      contact_jid = is_me ? stanza_Strophe.getBareJidFromJid(to_jid) : from_bare_jid;
      contact = await converse_core_api.contacts.get(contact_jid);

      if (contact === undefined && !converse_core_api.settings.get("allow_non_roster_messaging")) {
        headless_log.error(stanza);
        return new StanzaParseError(`Blocking messaging with a JID not in our roster because allow_non_roster_messaging is false.`, stanza);
      }
    }
    /**
     * @typedef { Object } MessageAttributes
     * The object which {@link st.parseMessage} returns
     * @property { ('me'|'them') } sender - Whether the message was sent by the current user or someone else
     * @property { Array<Object> } references - A list of objects representing XEP-0372 references
     * @property { Boolean } editable - Is this message editable via XEP-0308?
     * @property { Boolean } is_archived -  Is this message from a XEP-0313 MAM archive?
     * @property { Boolean } is_carbon - Is this message a XEP-0280 Carbon?
     * @property { Boolean } is_delayed - Was delivery of this message was delayed as per XEP-0203?
     * @property { Boolean } is_encrypted -  Is this message XEP-0384  encrypted?
     * @property { Boolean } is_error - Whether an error was received for this message
     * @property { Boolean } is_headline - Is this a "headline" message?
     * @property { Boolean } is_markable - Can this message be marked with a XEP-0333 chat marker?
     * @property { Boolean } is_marker - Is this message a XEP-0333 Chat Marker?
     * @property { Boolean } is_only_emojis - Does the message body contain only emojis?
     * @property { Boolean } is_valid_receipt_request - Does this message request a XEP-0184 receipt (and is not from us or a carbon or archived message)
     * @property { Boolean } is_spoiler - Is this a XEP-0382 spoiler message?
     * @property { Boolean } is_tombstone - Is this a XEP-0424 tombstone?
     * @property { Object } encrypted -  XEP-0384 encryption payload attributes
     * @property { String } body - The contents of the <body> tag of the message stanza
     * @property { String } chat_state - The XEP-0085 chat state notification contained in this message
     * @property { String } contact_jid - The JID of the other person or entity
     * @property { String } edited - An ISO8601 string recording the time that the message was edited per XEP-0308
     * @property { String } error_condition - The defined error condition
     * @property { String } error_text - The error text received from the server
     * @property { String } error_type - The type of error received from the server
     * @property { String } from - The sender JID
     * @property { String } fullname - The full name of the sender
     * @property { String } marker - The XEP-0333 Chat Marker value
     * @property { String } marker_id - The `id` attribute of a XEP-0333 chat marker
     * @property { String } msgid - The root `id` attribute of the stanza
     * @property { String } nick - The roster nickname of the sender
     * @property { String } oob_desc - The description of the XEP-0066 out of band data
     * @property { String } oob_url - The URL of the XEP-0066 out of band data
     * @property { String } origin_id - The XEP-0359 Origin ID
     * @property { String } receipt_id - The `id` attribute of a XEP-0184 <receipt> element
     * @property { String } received - An ISO8601 string recording the time that the message was received
     * @property { String } replace_id - The `id` attribute of a XEP-0308 <replace> element
     * @property { String } retracted - An ISO8601 string recording the time that the message was retracted
     * @property { String } retracted_id - The `id` attribute of a XEP-424 <retracted> element
     * @property { String } spoiler_hint  The XEP-0382 spoiler hint
     * @property { String } stanza_id - The XEP-0359 Stanza ID. Note: the key is actualy `stanza_id ${by_jid}` and there can be multiple.
     * @property { String } subject - The <subject> element value
     * @property { String } thread - The <thread> element value
     * @property { String } time - The time (in ISO8601 format), either given by the XEP-0203 <delay> element, or of receipt.
     * @property { String } to - The recipient JID
     * @property { String } type - The type of message
     */


    const delay = sizzle_default()(`delay[xmlns="${stanza_Strophe.NS.DELAY}"]`, original_stanza).pop();
    const marker = st.getChatMarker(stanza);
    const now = new Date().toISOString();
    let attrs = Object.assign({
      contact_jid,
      is_archived,
      is_headline,
      is_server_message,
      'body': (_stanza$querySelector2 = stanza.querySelector('body')) === null || _stanza$querySelector2 === void 0 ? void 0 : (_stanza$querySelector3 = _stanza$querySelector2.textContent) === null || _stanza$querySelector3 === void 0 ? void 0 : _stanza$querySelector3.trim(),
      'chat_state': getChatState(stanza),
      'from': stanza_Strophe.getBareJidFromJid(stanza.getAttribute('from')),
      'is_carbon': isCarbon(original_stanza),
      'is_delayed': !!delay,
      'is_markable': !!sizzle_default()(`markable[xmlns="${stanza_Strophe.NS.MARKERS}"]`, stanza).length,
      'is_marker': !!marker,
      'marker_id': marker && marker.getAttribute('id'),
      'msgid': stanza.getAttribute('id') || original_stanza.getAttribute('id'),
      'nick': (_contact = contact) === null || _contact === void 0 ? void 0 : (_contact$attributes = _contact.attributes) === null || _contact$attributes === void 0 ? void 0 : _contact$attributes.nickname,
      'receipt_id': getReceiptId(stanza),
      'received': new Date().toISOString(),
      'references': getReferences(stanza),
      'sender': is_me ? 'me' : 'them',
      'subject': (_stanza$querySelector4 = stanza.querySelector('subject')) === null || _stanza$querySelector4 === void 0 ? void 0 : _stanza$querySelector4.textContent,
      'thread': (_stanza$querySelector5 = stanza.querySelector('thread')) === null || _stanza$querySelector5 === void 0 ? void 0 : _stanza$querySelector5.textContent,
      'time': delay ? dayjs_min_default()(delay.getAttribute('stamp')).toISOString() : now,
      'to': stanza.getAttribute('to'),
      'type': stanza.getAttribute('type')
    }, getErrorAttributes(stanza), getOutOfBandAttributes(stanza), getSpoilerAttributes(stanza), getCorrectionAttributes(stanza, original_stanza), getStanzaIDs(stanza, original_stanza), getRetractionAttributes(stanza, original_stanza), getEncryptionAttributes(stanza, _converse));

    if (attrs.is_archived) {
      const from = original_stanza.getAttribute('from');

      if (from && from !== _converse.bare_jid) {
        return new StanzaParseError(`Invalid Stanza: Forged MAM message from ${from}`, stanza);
      }
    }

    await converse_core_api.emojis.initialize();
    attrs = Object.assign({
      'message': attrs.body || attrs.error,
      // TODO: Remove and use body and error attributes instead
      'is_only_emojis': attrs.body ? utils_core.isOnlyEmojis(attrs.body) : false,
      'is_valid_receipt_request': isValidReceiptRequest(stanza, attrs)
    }, attrs); // We prefer to use one of the XEP-0359 unique and stable stanza IDs
    // as the Model id, to avoid duplicates.

    attrs['id'] = attrs['origin_id'] || attrs[`stanza_id ${attrs.from}`] || utils_core.getUniqueId();
    /**
     * *Hook* which allows plugins to add additional parsing
     * @event _converse#parseMessage
     */

    return converse_core_api.hook('parseMessage', stanza, attrs);
  },

  /**
   * Parses a passed in message stanza and returns an object of attributes.
   * @method st#parseMUCMessage
   * @param { XMLElement } stanza - The message stanza
   * @param { XMLElement } original_stanza - The original stanza, that contains the
   *  message stanza, if it was contained, otherwise it's the message stanza itself.
   * @param { _converse.ChatRoom } chatbox
   * @param { _converse } _converse
   * @returns { Promise<MUCMessageAttributes|Error> }
   */
  async parseMUCMessage(stanza, chatbox, _converse) {
    var _stanza$querySelector6, _stanza$querySelector7, _chatbox$occupants$fi, _stanza$querySelector8, _stanza$querySelector9;

    const err = rejectUnencapsulatedForward(stanza);

    if (err) {
      return err;
    }

    const selector = `[xmlns="${NS.MAM}"] > forwarded[xmlns="${NS.FORWARD}"] > message`;
    const original_stanza = stanza;
    stanza = sizzle_default()(selector, stanza).pop() || stanza;

    if (sizzle_default()(`message > forwarded[xmlns="${stanza_Strophe.NS.FORWARD}"]`, stanza).length) {
      return new StanzaParseError(`Invalid Stanza: Forged MAM groupchat message from ${stanza.getAttribute('from')}`, stanza);
    }

    const delay = sizzle_default()(`delay[xmlns="${stanza_Strophe.NS.DELAY}"]`, original_stanza).pop();
    const from = stanza.getAttribute('from');
    const nick = stanza_Strophe.unescapeNode(stanza_Strophe.getResourceFromJid(from));
    const marker = st.getChatMarker(stanza);
    const now = new Date().toISOString();
    /**
     * @typedef { Object } MUCMessageAttributes
     * The object which {@link st.parseMUCMessage} returns
     * @property { ('me'|'them') } sender - Whether the message was sent by the current user or someone else
     * @property { Array<Object> } references - A list of objects representing XEP-0372 references
     * @property { Boolean } editable - Is this message editable via XEP-0308?
     * @property { Boolean } is_archived -  Is this message from a XEP-0313 MAM archive?
     * @property { Boolean } is_carbon - Is this message a XEP-0280 Carbon?
     * @property { Boolean } is_delayed - Was delivery of this message was delayed as per XEP-0203?
     * @property { Boolean } is_encrypted -  Is this message XEP-0384  encrypted?
     * @property { Boolean } is_error - Whether an error was received for this message
     * @property { Boolean } is_headline - Is this a "headline" message?
     * @property { Boolean } is_markable - Can this message be marked with a XEP-0333 chat marker?
     * @property { Boolean } is_marker - Is this message a XEP-0333 Chat Marker?
     * @property { Boolean } is_only_emojis - Does the message body contain only emojis?
     * @property { Boolean } is_valid_receipt_request - Does this message request a XEP-0184 receipt (and is not from us or a carbon or archived message)
     * @property { Boolean } is_spoiler - Is this a XEP-0382 spoiler message?
     * @property { Boolean } is_tombstone - Is this a XEP-0424 tombstone?
     * @property { Object } encrypted -  XEP-0384 encryption payload attributes
     * @property { String } body - The contents of the <body> tag of the message stanza
     * @property { String } chat_state - The XEP-0085 chat state notification contained in this message
     * @property { String } edited - An ISO8601 string recording the time that the message was edited per XEP-0308
     * @property { String } error_condition - The defined error condition
     * @property { String } error_text - The error text received from the server
     * @property { String } error_type - The type of error received from the server
     * @property { String } from - The sender JID (${muc_jid}/${nick})
     * @property { String } from_muc - The JID of the MUC from which this message was sent
     * @property { String } from_real_jid - The real JID of the sender, if available
     * @property { String } fullname - The full name of the sender
     * @property { String } marker - The XEP-0333 Chat Marker value
     * @property { String } marker_id - The `id` attribute of a XEP-0333 chat marker
     * @property { String } moderated - The type of XEP-0425 moderation (if any) that was applied
     * @property { String } moderated_by - The JID of the user that moderated this message
     * @property { String } moderated_id - The  XEP-0359 Stanza ID of the message that this one moderates
     * @property { String } moderation_reason - The reason provided why this message moderates another
     * @property { String } msgid - The root `id` attribute of the stanza
     * @property { String } nick - The MUC nickname of the sender
     * @property { String } oob_desc - The description of the XEP-0066 out of band data
     * @property { String } oob_url - The URL of the XEP-0066 out of band data
     * @property { String } origin_id - The XEP-0359 Origin ID
     * @property { String } receipt_id - The `id` attribute of a XEP-0184 <receipt> element
     * @property { String } received - An ISO8601 string recording the time that the message was received
     * @property { String } replace_id - The `id` attribute of a XEP-0308 <replace> element
     * @property { String } retracted - An ISO8601 string recording the time that the message was retracted
     * @property { String } retracted_id - The `id` attribute of a XEP-424 <retracted> element
     * @property { String } spoiler_hint  The XEP-0382 spoiler hint
     * @property { String } stanza_id - The XEP-0359 Stanza ID. Note: the key is actualy `stanza_id ${by_jid}` and there can be multiple.
     * @property { String } subject - The <subject> element value
     * @property { String } thread - The <thread> element value
     * @property { String } time - The time (in ISO8601 format), either given by the XEP-0203 <delay> element, or of receipt.
     * @property { String } to - The recipient JID
     * @property { String } type - The type of message
     */

    let attrs = Object.assign({
      from,
      nick,
      'body': (_stanza$querySelector6 = stanza.querySelector('body')) === null || _stanza$querySelector6 === void 0 ? void 0 : (_stanza$querySelector7 = _stanza$querySelector6.textContent) === null || _stanza$querySelector7 === void 0 ? void 0 : _stanza$querySelector7.trim(),
      'chat_state': getChatState(stanza),
      'from_muc': stanza_Strophe.getBareJidFromJid(from),
      'from_real_jid': (_chatbox$occupants$fi = chatbox.occupants.findOccupant({
        nick
      })) === null || _chatbox$occupants$fi === void 0 ? void 0 : _chatbox$occupants$fi.get('jid'),
      'is_archived': st.isArchived(original_stanza),
      'is_carbon': isCarbon(original_stanza),
      'is_delayed': !!delay,
      'is_headline': st.isHeadline(stanza),
      'is_markable': !!sizzle_default()(`markable[xmlns="${stanza_Strophe.NS.MARKERS}"]`, stanza).length,
      'is_marker': !!marker,
      'marker_id': marker && marker.getAttribute('id'),
      'msgid': stanza.getAttribute('id') || original_stanza.getAttribute('id'),
      'receipt_id': getReceiptId(stanza),
      'received': new Date().toISOString(),
      'references': getReferences(stanza),
      'subject': (_stanza$querySelector8 = stanza.querySelector('subject')) === null || _stanza$querySelector8 === void 0 ? void 0 : _stanza$querySelector8.textContent,
      'thread': (_stanza$querySelector9 = stanza.querySelector('thread')) === null || _stanza$querySelector9 === void 0 ? void 0 : _stanza$querySelector9.textContent,
      'time': delay ? dayjs_min_default()(delay.getAttribute('stamp')).toISOString() : now,
      'to': stanza.getAttribute('to'),
      'type': stanza.getAttribute('type')
    }, getErrorAttributes(stanza), getOutOfBandAttributes(stanza), getSpoilerAttributes(stanza), getCorrectionAttributes(stanza, original_stanza), getStanzaIDs(stanza, original_stanza), getRetractionAttributes(stanza, original_stanza), getModerationAttributes(stanza), getEncryptionAttributes(stanza, _converse));
    await converse_core_api.emojis.initialize();
    attrs = Object.assign({
      'is_only_emojis': attrs.body ? utils_core.isOnlyEmojis(attrs.body) : false,
      'is_valid_receipt_request': isValidReceiptRequest(stanza, attrs),
      'message': attrs.body || attrs.error,
      // TODO: Remove and use body and error attributes instead
      'sender': attrs.nick === chatbox.get('nick') ? 'me' : 'them'
    }, attrs);

    if (attrs.is_archived && original_stanza.getAttribute('from') !== attrs.from_muc) {
      return new StanzaParseError(`Invalid Stanza: Forged MAM message from ${original_stanza.getAttribute('from')}`, stanza);
    } else if (attrs.is_archived && original_stanza.getAttribute('from') !== chatbox.get('jid')) {
      return new StanzaParseError(`Invalid Stanza: Forged MAM groupchat message from ${stanza.getAttribute('from')}`, stanza);
    } else if (attrs.is_carbon) {
      return new StanzaParseError("Invalid Stanza: MUC messages SHOULD NOT be XEP-0280 carbon copied", stanza);
    } // We prefer to use one of the XEP-0359 unique and stable stanza IDs as the Model id, to avoid duplicates.


    attrs['id'] = attrs['origin_id'] || attrs[`stanza_id ${attrs.from_muc || attrs.from}`] || utils_core.getUniqueId();
    /**
     * *Hook* which allows plugins to add additional parsing
     * @event _converse#parseMUCMessage
     */

    return converse_core_api.hook('parseMUCMessage', stanza, attrs);
  },

  /**
   * Parses a passed in MUC presence stanza and returns an object of attributes.
   * @method st#parseMUCPresence
   * @param { XMLElement } stanza - The presence stanza
   * @returns { Object }
   */
  parseMUCPresence(stanza) {
    const from = stanza.getAttribute("from");
    const type = stanza.getAttribute("type");
    const data = {
      'from': from,
      'nick': stanza_Strophe.getResourceFromJid(from),
      'type': type,
      'states': [],
      'hats': [],
      'show': type !== 'unavailable' ? 'online' : 'offline'
    };
    Array.from(stanza.children).forEach(child => {
      if (child.matches('status')) {
        data.status = child.textContent || null;
      } else if (child.matches('show')) {
        data.show = child.textContent || 'online';
      } else if (child.matches('x') && child.getAttribute('xmlns') === stanza_Strophe.NS.MUC_USER) {
        Array.from(child.children).forEach(item => {
          if (item.nodeName === "item") {
            data.affiliation = item.getAttribute("affiliation");
            data.role = item.getAttribute("role");
            data.jid = item.getAttribute("jid");
            data.nick = item.getAttribute("nick") || data.nick;
          } else if (item.nodeName == 'status' && item.getAttribute("code")) {
            data.states.push(item.getAttribute("code"));
          }
        });
      } else if (child.matches('x') && child.getAttribute('xmlns') === stanza_Strophe.NS.VCARDUPDATE) {
        var _child$querySelector;

        data.image_hash = (_child$querySelector = child.querySelector('photo')) === null || _child$querySelector === void 0 ? void 0 : _child$querySelector.textContent;
      } else if (child.matches('hats') && child.getAttribute('xmlns') === stanza_Strophe.NS.MUC_HATS) {
        data['hats'] = Array.from(child.children).map(c => c.matches('hat') && {
          'title': c.getAttribute('title'),
          'uri': c.getAttribute('uri')
        });
      }
    });
    return data;
  }

};
/* harmony default export */ var utils_stanza = (st);
// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayAggregator.js
/**
 * A specialized version of `baseAggregator` for arrays.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} setter The function to set `accumulator` values.
 * @param {Function} iteratee The iteratee to transform keys.
 * @param {Object} accumulator The initial aggregated object.
 * @returns {Function} Returns `accumulator`.
 */
function arrayAggregator(array, setter, iteratee, accumulator) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    var value = array[index];
    setter(accumulator, value, iteratee(value), array);
  }

  return accumulator;
}

/* harmony default export */ var _arrayAggregator = (arrayAggregator);
// CONCATENATED MODULE: ./node_modules/lodash-es/_createBaseEach.js

/**
 * Creates a `baseEach` or `baseEachRight` function.
 *
 * @private
 * @param {Function} eachFunc The function to iterate over a collection.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new base function.
 */

function createBaseEach(eachFunc, fromRight) {
  return function (collection, iteratee) {
    if (collection == null) {
      return collection;
    }

    if (!lodash_es_isArrayLike(collection)) {
      return eachFunc(collection, iteratee);
    }

    var length = collection.length,
        index = fromRight ? length : -1,
        iterable = Object(collection);

    while (fromRight ? index-- : ++index < length) {
      if (iteratee(iterable[index], index, iterable) === false) {
        break;
      }
    }

    return collection;
  };
}

/* harmony default export */ var _createBaseEach = (createBaseEach);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseEach.js


/**
 * The base implementation of `_.forEach` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array|Object} Returns `collection`.
 */

var baseEach = _createBaseEach(_baseForOwn);
/* harmony default export */ var _baseEach = (baseEach);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseAggregator.js

/**
 * Aggregates elements of `collection` on `accumulator` with keys transformed
 * by `iteratee` and values set by `setter`.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} setter The function to set `accumulator` values.
 * @param {Function} iteratee The iteratee to transform keys.
 * @param {Object} accumulator The initial aggregated object.
 * @returns {Function} Returns `accumulator`.
 */

function baseAggregator(collection, setter, iteratee, accumulator) {
  _baseEach(collection, function (value, key, collection) {
    setter(accumulator, value, iteratee(value), collection);
  });
  return accumulator;
}

/* harmony default export */ var _baseAggregator = (baseAggregator);
// CONCATENATED MODULE: ./node_modules/lodash-es/_createAggregator.js




/**
 * Creates a function like `_.groupBy`.
 *
 * @private
 * @param {Function} setter The function to set accumulator values.
 * @param {Function} [initializer] The accumulator object initializer.
 * @returns {Function} Returns the new aggregator function.
 */

function createAggregator(setter, initializer) {
  return function (collection, iteratee) {
    var func = lodash_es_isArray(collection) ? _arrayAggregator : _baseAggregator,
        accumulator = initializer ? initializer() : {};
    return func(collection, setter, _baseIteratee(iteratee, 2), accumulator);
  };
}

/* harmony default export */ var _createAggregator = (createAggregator);
// CONCATENATED MODULE: ./node_modules/lodash-es/countBy.js


/** Used for built-in method references. */

var countBy_objectProto = Object.prototype;
/** Used to check objects for own properties. */

var countBy_hasOwnProperty = countBy_objectProto.hasOwnProperty;
/**
 * Creates an object composed of keys generated from the results of running
 * each element of `collection` thru `iteratee`. The corresponding value of
 * each key is the number of times the key was returned by `iteratee`. The
 * iteratee is invoked with one argument: (value).
 *
 * @static
 * @memberOf _
 * @since 0.5.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
 * @returns {Object} Returns the composed aggregate object.
 * @example
 *
 * _.countBy([6.1, 4.2, 6.3], Math.floor);
 * // => { '4': 1, '6': 2 }
 *
 * // The `_.property` iteratee shorthand.
 * _.countBy(['one', 'two', 'three'], 'length');
 * // => { '3': 2, '5': 1 }
 */

var countBy = _createAggregator(function (result, value, key) {
  if (countBy_hasOwnProperty.call(result, key)) {
    ++result[key];
  } else {
    _baseAssignValue(result, key, 1);
  }
});
/* harmony default export */ var lodash_es_countBy = (countBy);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseFindIndex.js
/**
 * The base implementation of `_.findIndex` and `_.findLastIndex` without
 * support for iteratee shorthands.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {Function} predicate The function invoked per iteration.
 * @param {number} fromIndex The index to search from.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function baseFindIndex(array, predicate, fromIndex, fromRight) {
  var length = array.length,
      index = fromIndex + (fromRight ? 1 : -1);

  while (fromRight ? index-- : ++index < length) {
    if (predicate(array[index], index, array)) {
      return index;
    }
  }

  return -1;
}

/* harmony default export */ var _baseFindIndex = (baseFindIndex);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsNaN.js
/**
 * The base implementation of `_.isNaN` without support for number objects.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
 */
function baseIsNaN(value) {
  return value !== value;
}

/* harmony default export */ var _baseIsNaN = (baseIsNaN);
// CONCATENATED MODULE: ./node_modules/lodash-es/_strictIndexOf.js
/**
 * A specialized version of `_.indexOf` which performs strict equality
 * comparisons of values, i.e. `===`.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function strictIndexOf(array, value, fromIndex) {
  var index = fromIndex - 1,
      length = array.length;

  while (++index < length) {
    if (array[index] === value) {
      return index;
    }
  }

  return -1;
}

/* harmony default export */ var _strictIndexOf = (strictIndexOf);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIndexOf.js



/**
 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */

function baseIndexOf(array, value, fromIndex) {
  return value === value ? _strictIndexOf(array, value, fromIndex) : _baseFindIndex(array, _baseIsNaN, fromIndex);
}

/* harmony default export */ var _baseIndexOf = (baseIndexOf);
// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayIncludes.js

/**
 * A specialized version of `_.includes` for arrays without support for
 * specifying an index to search from.
 *
 * @private
 * @param {Array} [array] The array to inspect.
 * @param {*} target The value to search for.
 * @returns {boolean} Returns `true` if `target` is found, else `false`.
 */

function arrayIncludes(array, value) {
  var length = array == null ? 0 : array.length;
  return !!length && _baseIndexOf(array, value, 0) > -1;
}

/* harmony default export */ var _arrayIncludes = (arrayIncludes);
// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayIncludesWith.js
/**
 * This function is like `arrayIncludes` except that it accepts a comparator.
 *
 * @private
 * @param {Array} [array] The array to inspect.
 * @param {*} target The value to search for.
 * @param {Function} comparator The comparator invoked per element.
 * @returns {boolean} Returns `true` if `target` is found, else `false`.
 */
function arrayIncludesWith(array, value, comparator) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    if (comparator(value, array[index])) {
      return true;
    }
  }

  return false;
}

/* harmony default export */ var _arrayIncludesWith = (arrayIncludesWith);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseDifference.js






/** Used as the size to enable large array optimizations. */

var _baseDifference_LARGE_ARRAY_SIZE = 200;
/**
 * The base implementation of methods like `_.difference` without support
 * for excluding multiple arrays or iteratee shorthands.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {Array} values The values to exclude.
 * @param {Function} [iteratee] The iteratee invoked per element.
 * @param {Function} [comparator] The comparator invoked per element.
 * @returns {Array} Returns the new array of filtered values.
 */

function baseDifference(array, values, iteratee, comparator) {
  var index = -1,
      includes = _arrayIncludes,
      isCommon = true,
      length = array.length,
      result = [],
      valuesLength = values.length;

  if (!length) {
    return result;
  }

  if (iteratee) {
    values = _arrayMap(values, _baseUnary(iteratee));
  }

  if (comparator) {
    includes = _arrayIncludesWith;
    isCommon = false;
  } else if (values.length >= _baseDifference_LARGE_ARRAY_SIZE) {
    includes = _cacheHas;
    isCommon = false;
    values = new _SetCache(values);
  }

  outer: while (++index < length) {
    var value = array[index],
        computed = iteratee == null ? value : iteratee(value);
    value = comparator || value !== 0 ? value : 0;

    if (isCommon && computed === computed) {
      var valuesIndex = valuesLength;

      while (valuesIndex--) {
        if (values[valuesIndex] === computed) {
          continue outer;
        }
      }

      result.push(value);
    } else if (!includes(values, computed, comparator)) {
      result.push(value);
    }
  }

  return result;
}

/* harmony default export */ var _baseDifference = (baseDifference);
// CONCATENATED MODULE: ./node_modules/lodash-es/isArrayLikeObject.js


/**
 * This method is like `_.isArrayLike` except that it also checks if `value`
 * is an object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array-like object,
 *  else `false`.
 * @example
 *
 * _.isArrayLikeObject([1, 2, 3]);
 * // => true
 *
 * _.isArrayLikeObject(document.body.children);
 * // => true
 *
 * _.isArrayLikeObject('abc');
 * // => false
 *
 * _.isArrayLikeObject(_.noop);
 * // => false
 */

function isArrayLikeObject(value) {
  return lodash_es_isObjectLike(value) && lodash_es_isArrayLike(value);
}

/* harmony default export */ var lodash_es_isArrayLikeObject = (isArrayLikeObject);
// CONCATENATED MODULE: ./node_modules/lodash-es/difference.js




/**
 * Creates an array of `array` values not included in the other given arrays
 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons. The order and references of result values are
 * determined by the first array.
 *
 * **Note:** Unlike `_.pullAll`, this method returns a new array.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to inspect.
 * @param {...Array} [values] The values to exclude.
 * @returns {Array} Returns the new array of filtered values.
 * @see _.without, _.xor
 * @example
 *
 * _.difference([2, 1], [2, 3]);
 * // => [1]
 */

var difference = _baseRest(function (array, values) {
  return lodash_es_isArrayLikeObject(array) ? _baseDifference(array, _baseFlatten(values, 1, lodash_es_isArrayLikeObject, true)) : [];
});
/* harmony default export */ var lodash_es_difference = (difference);
// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayEvery.js
/**
 * A specialized version of `_.every` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if all elements pass the predicate check,
 *  else `false`.
 */
function arrayEvery(array, predicate) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    if (!predicate(array[index], index, array)) {
      return false;
    }
  }

  return true;
}

/* harmony default export */ var _arrayEvery = (arrayEvery);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseEvery.js

/**
 * The base implementation of `_.every` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if all elements pass the predicate check,
 *  else `false`
 */

function baseEvery(collection, predicate) {
  var result = true;
  _baseEach(collection, function (value, index, collection) {
    result = !!predicate(value, index, collection);
    return result;
  });
  return result;
}

/* harmony default export */ var _baseEvery = (baseEvery);
// CONCATENATED MODULE: ./node_modules/lodash-es/every.js





/**
 * Checks if `predicate` returns truthy for **all** elements of `collection`.
 * Iteration is stopped once `predicate` returns falsey. The predicate is
 * invoked with three arguments: (value, index|key, collection).
 *
 * **Note:** This method returns `true` for
 * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
 * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
 * elements of empty collections.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
 * @returns {boolean} Returns `true` if all elements pass the predicate check,
 *  else `false`.
 * @example
 *
 * _.every([true, 1, null, 'yes'], Boolean);
 * // => false
 *
 * var users = [
 *   { 'user': 'barney', 'age': 36, 'active': false },
 *   { 'user': 'fred',   'age': 40, 'active': false }
 * ];
 *
 * // The `_.matches` iteratee shorthand.
 * _.every(users, { 'user': 'barney', 'active': false });
 * // => false
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.every(users, ['active', false]);
 * // => true
 *
 * // The `_.property` iteratee shorthand.
 * _.every(users, 'active');
 * // => false
 */

function every(collection, predicate, guard) {
  var func = lodash_es_isArray(collection) ? _arrayEvery : _baseEvery;

  if (guard && _isIterateeCall(collection, predicate, guard)) {
    predicate = undefined;
  }

  return func(collection, _baseIteratee(predicate, 3));
}

/* harmony default export */ var lodash_es_every = (every);
// CONCATENATED MODULE: ./node_modules/lodash-es/findIndex.js



/* Built-in method references for those with the same name as other `lodash` methods. */

var findIndex_nativeMax = Math.max;
/**
 * This method is like `_.find` except that it returns the index of the first
 * element `predicate` returns truthy for instead of the element itself.
 *
 * @static
 * @memberOf _
 * @since 1.1.0
 * @category Array
 * @param {Array} array The array to inspect.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @param {number} [fromIndex=0] The index to search from.
 * @returns {number} Returns the index of the found element, else `-1`.
 * @example
 *
 * var users = [
 *   { 'user': 'barney',  'active': false },
 *   { 'user': 'fred',    'active': false },
 *   { 'user': 'pebbles', 'active': true }
 * ];
 *
 * _.findIndex(users, function(o) { return o.user == 'barney'; });
 * // => 0
 *
 * // The `_.matches` iteratee shorthand.
 * _.findIndex(users, { 'user': 'fred', 'active': false });
 * // => 1
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.findIndex(users, ['active', false]);
 * // => 0
 *
 * // The `_.property` iteratee shorthand.
 * _.findIndex(users, 'active');
 * // => 2
 */

function findIndex(array, predicate, fromIndex) {
  var length = array == null ? 0 : array.length;

  if (!length) {
    return -1;
  }

  var index = fromIndex == null ? 0 : lodash_es_toInteger(fromIndex);

  if (index < 0) {
    index = findIndex_nativeMax(length + index, 0);
  }

  return _baseFindIndex(array, _baseIteratee(predicate, 3), index);
}

/* harmony default export */ var lodash_es_findIndex = (findIndex);
// CONCATENATED MODULE: ./node_modules/lodash-es/findLastIndex.js



/* Built-in method references for those with the same name as other `lodash` methods. */

var findLastIndex_nativeMax = Math.max,
    nativeMin = Math.min;
/**
 * This method is like `_.findIndex` except that it iterates over elements
 * of `collection` from right to left.
 *
 * @static
 * @memberOf _
 * @since 2.0.0
 * @category Array
 * @param {Array} array The array to inspect.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @param {number} [fromIndex=array.length-1] The index to search from.
 * @returns {number} Returns the index of the found element, else `-1`.
 * @example
 *
 * var users = [
 *   { 'user': 'barney',  'active': true },
 *   { 'user': 'fred',    'active': false },
 *   { 'user': 'pebbles', 'active': false }
 * ];
 *
 * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
 * // => 2
 *
 * // The `_.matches` iteratee shorthand.
 * _.findLastIndex(users, { 'user': 'barney', 'active': true });
 * // => 0
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.findLastIndex(users, ['active', false]);
 * // => 2
 *
 * // The `_.property` iteratee shorthand.
 * _.findLastIndex(users, 'active');
 * // => 0
 */

function findLastIndex(array, predicate, fromIndex) {
  var length = array == null ? 0 : array.length;

  if (!length) {
    return -1;
  }

  var index = length - 1;

  if (fromIndex !== undefined) {
    index = lodash_es_toInteger(fromIndex);
    index = fromIndex < 0 ? findLastIndex_nativeMax(length + index, 0) : nativeMin(index, length - 1);
  }

  return _baseFindIndex(array, _baseIteratee(predicate, 3), index, true);
}

/* harmony default export */ var lodash_es_findLastIndex = (findLastIndex);
// CONCATENATED MODULE: ./node_modules/lodash-es/groupBy.js


/** Used for built-in method references. */

var groupBy_objectProto = Object.prototype;
/** Used to check objects for own properties. */

var groupBy_hasOwnProperty = groupBy_objectProto.hasOwnProperty;
/**
 * Creates an object composed of keys generated from the results of running
 * each element of `collection` thru `iteratee`. The order of grouped values
 * is determined by the order they occur in `collection`. The corresponding
 * value of each key is an array of elements responsible for generating the
 * key. The iteratee is invoked with one argument: (value).
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
 * @returns {Object} Returns the composed aggregate object.
 * @example
 *
 * _.groupBy([6.1, 4.2, 6.3], Math.floor);
 * // => { '4': [4.2], '6': [6.1, 6.3] }
 *
 * // The `_.property` iteratee shorthand.
 * _.groupBy(['one', 'two', 'three'], 'length');
 * // => { '3': ['one', 'two'], '5': ['three'] }
 */

var groupBy = _createAggregator(function (result, value, key) {
  if (groupBy_hasOwnProperty.call(result, key)) {
    result[key].push(value);
  } else {
    _baseAssignValue(result, key, [value]);
  }
});
/* harmony default export */ var lodash_es_groupBy = (groupBy);
// CONCATENATED MODULE: ./node_modules/lodash-es/indexOf.js


/* Built-in method references for those with the same name as other `lodash` methods. */

var indexOf_nativeMax = Math.max;
/**
 * Gets the index at which the first occurrence of `value` is found in `array`
 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons. If `fromIndex` is negative, it's used as the
 * offset from the end of `array`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} [fromIndex=0] The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 * @example
 *
 * _.indexOf([1, 2, 1, 2], 2);
 * // => 1
 *
 * // Search from the `fromIndex`.
 * _.indexOf([1, 2, 1, 2], 2, 2);
 * // => 3
 */

function indexOf(array, value, fromIndex) {
  var length = array == null ? 0 : array.length;

  if (!length) {
    return -1;
  }

  var index = fromIndex == null ? 0 : lodash_es_toInteger(fromIndex);

  if (index < 0) {
    index = indexOf_nativeMax(length + index, 0);
  }

  return _baseIndexOf(array, value, index);
}

/* harmony default export */ var lodash_es_indexOf = (indexOf);
// CONCATENATED MODULE: ./node_modules/lodash-es/keyBy.js


/**
 * Creates an object composed of keys generated from the results of running
 * each element of `collection` thru `iteratee`. The corresponding value of
 * each key is the last element responsible for generating the key. The
 * iteratee is invoked with one argument: (value).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
 * @returns {Object} Returns the composed aggregate object.
 * @example
 *
 * var array = [
 *   { 'dir': 'left', 'code': 97 },
 *   { 'dir': 'right', 'code': 100 }
 * ];
 *
 * _.keyBy(array, function(o) {
 *   return String.fromCharCode(o.code);
 * });
 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
 *
 * _.keyBy(array, 'dir');
 * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
 */

var keyBy = _createAggregator(function (result, value, key) {
  _baseAssignValue(result, key, value);
});
/* harmony default export */ var lodash_es_keyBy = (keyBy);
// CONCATENATED MODULE: ./node_modules/lodash-es/_strictLastIndexOf.js
/**
 * A specialized version of `_.lastIndexOf` which performs strict equality
 * comparisons of values, i.e. `===`.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function strictLastIndexOf(array, value, fromIndex) {
  var index = fromIndex + 1;

  while (index--) {
    if (array[index] === value) {
      return index;
    }
  }

  return index;
}

/* harmony default export */ var _strictLastIndexOf = (strictLastIndexOf);
// CONCATENATED MODULE: ./node_modules/lodash-es/lastIndexOf.js




/* Built-in method references for those with the same name as other `lodash` methods. */

var lastIndexOf_nativeMax = Math.max,
    lastIndexOf_nativeMin = Math.min;
/**
 * This method is like `_.indexOf` except that it iterates over elements of
 * `array` from right to left.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} [fromIndex=array.length-1] The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 * @example
 *
 * _.lastIndexOf([1, 2, 1, 2], 2);
 * // => 3
 *
 * // Search from the `fromIndex`.
 * _.lastIndexOf([1, 2, 1, 2], 2, 2);
 * // => 1
 */

function lastIndexOf(array, value, fromIndex) {
  var length = array == null ? 0 : array.length;

  if (!length) {
    return -1;
  }

  var index = length;

  if (fromIndex !== undefined) {
    index = lodash_es_toInteger(fromIndex);
    index = index < 0 ? lastIndexOf_nativeMax(length + index, 0) : lastIndexOf_nativeMin(index, length - 1);
  }

  return value === value ? _strictLastIndexOf(array, value, index) : _baseFindIndex(array, _baseIsNaN, index, true);
}

/* harmony default export */ var lodash_es_lastIndexOf = (lastIndexOf);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSome.js

/**
 * The base implementation of `_.some` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if any element passes the predicate check,
 *  else `false`.
 */

function baseSome(collection, predicate) {
  var result;
  _baseEach(collection, function (value, index, collection) {
    result = predicate(value, index, collection);
    return !result;
  });
  return !!result;
}

/* harmony default export */ var _baseSome = (baseSome);
// CONCATENATED MODULE: ./node_modules/lodash-es/some.js





/**
 * Checks if `predicate` returns truthy for **any** element of `collection`.
 * Iteration is stopped once `predicate` returns truthy. The predicate is
 * invoked with three arguments: (value, index|key, collection).
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
 * @returns {boolean} Returns `true` if any element passes the predicate check,
 *  else `false`.
 * @example
 *
 * _.some([null, 0, 'yes', false], Boolean);
 * // => true
 *
 * var users = [
 *   { 'user': 'barney', 'active': true },
 *   { 'user': 'fred',   'active': false }
 * ];
 *
 * // The `_.matches` iteratee shorthand.
 * _.some(users, { 'user': 'barney', 'active': false });
 * // => false
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.some(users, ['active', false]);
 * // => true
 *
 * // The `_.property` iteratee shorthand.
 * _.some(users, 'active');
 * // => true
 */

function some(collection, predicate, guard) {
  var func = lodash_es_isArray(collection) ? _arraySome : _baseSome;

  if (guard && _isIterateeCall(collection, predicate, guard)) {
    predicate = undefined;
  }

  return func(collection, _baseIteratee(predicate, 3));
}

/* harmony default export */ var lodash_es_some = (some);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseMap.js


/**
 * The base implementation of `_.map` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 */

function baseMap(collection, iteratee) {
  var index = -1,
      result = lodash_es_isArrayLike(collection) ? Array(collection.length) : [];
  _baseEach(collection, function (value, key, collection) {
    result[++index] = iteratee(value, key, collection);
  });
  return result;
}

/* harmony default export */ var _baseMap = (baseMap);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSortBy.js
/**
 * The base implementation of `_.sortBy` which uses `comparer` to define the
 * sort order of `array` and replaces criteria objects with their corresponding
 * values.
 *
 * @private
 * @param {Array} array The array to sort.
 * @param {Function} comparer The function to define sort order.
 * @returns {Array} Returns `array`.
 */
function baseSortBy(array, comparer) {
  var length = array.length;
  array.sort(comparer);

  while (length--) {
    array[length] = array[length].value;
  }

  return array;
}

/* harmony default export */ var _baseSortBy = (baseSortBy);
// CONCATENATED MODULE: ./node_modules/lodash-es/_compareAscending.js

/**
 * Compares values to sort them in ascending order.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {number} Returns the sort order indicator for `value`.
 */

function compareAscending(value, other) {
  if (value !== other) {
    var valIsDefined = value !== undefined,
        valIsNull = value === null,
        valIsReflexive = value === value,
        valIsSymbol = lodash_es_isSymbol(value);
    var othIsDefined = other !== undefined,
        othIsNull = other === null,
        othIsReflexive = other === other,
        othIsSymbol = lodash_es_isSymbol(other);

    if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) {
      return 1;
    }

    if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) {
      return -1;
    }
  }

  return 0;
}

/* harmony default export */ var _compareAscending = (compareAscending);
// CONCATENATED MODULE: ./node_modules/lodash-es/_compareMultiple.js

/**
 * Used by `_.orderBy` to compare multiple properties of a value to another
 * and stable sort them.
 *
 * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
 * specify an order of "desc" for descending or "asc" for ascending sort order
 * of corresponding values.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {boolean[]|string[]} orders The order to sort by for each property.
 * @returns {number} Returns the sort order indicator for `object`.
 */

function compareMultiple(object, other, orders) {
  var index = -1,
      objCriteria = object.criteria,
      othCriteria = other.criteria,
      length = objCriteria.length,
      ordersLength = orders.length;

  while (++index < length) {
    var result = _compareAscending(objCriteria[index], othCriteria[index]);

    if (result) {
      if (index >= ordersLength) {
        return result;
      }

      var order = orders[index];
      return result * (order == 'desc' ? -1 : 1);
    }
  } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
  // that causes it, under certain circumstances, to provide the same value for
  // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
  // for more details.
  //
  // This also ensures a stable sort in V8 and other engines.
  // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.


  return object.index - other.index;
}

/* harmony default export */ var _compareMultiple = (compareMultiple);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseOrderBy.js









/**
 * The base implementation of `_.orderBy` without param guards.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
 * @param {string[]} orders The sort orders of `iteratees`.
 * @returns {Array} Returns the new sorted array.
 */

function baseOrderBy(collection, iteratees, orders) {
  if (iteratees.length) {
    iteratees = _arrayMap(iteratees, function (iteratee) {
      if (lodash_es_isArray(iteratee)) {
        return function (value) {
          return _baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
        };
      }

      return iteratee;
    });
  } else {
    iteratees = [lodash_es_identity];
  }

  var index = -1;
  iteratees = _arrayMap(iteratees, _baseUnary(_baseIteratee));
  var result = _baseMap(collection, function (value, key, collection) {
    var criteria = _arrayMap(iteratees, function (iteratee) {
      return iteratee(value);
    });
    return {
      'criteria': criteria,
      'index': ++index,
      'value': value
    };
  });
  return _baseSortBy(result, function (object, other) {
    return _compareMultiple(object, other, orders);
  });
}

/* harmony default export */ var _baseOrderBy = (baseOrderBy);
// CONCATENATED MODULE: ./node_modules/lodash-es/sortBy.js




/**
 * Creates an array of elements, sorted in ascending order by the results of
 * running each element in a collection thru each iteratee. This method
 * performs a stable sort, that is, it preserves the original sort order of
 * equal elements. The iteratees are invoked with one argument: (value).
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {...(Function|Function[])} [iteratees=[_.identity]]
 *  The iteratees to sort by.
 * @returns {Array} Returns the new sorted array.
 * @example
 *
 * var users = [
 *   { 'user': 'fred',   'age': 48 },
 *   { 'user': 'barney', 'age': 36 },
 *   { 'user': 'fred',   'age': 30 },
 *   { 'user': 'barney', 'age': 34 }
 * ];
 *
 * _.sortBy(users, [function(o) { return o.user; }]);
 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
 *
 * _.sortBy(users, ['user', 'age']);
 * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
 */

var sortBy = _baseRest(function (collection, iteratees) {
  if (collection == null) {
    return [];
  }

  var length = iteratees.length;

  if (length > 1 && _isIterateeCall(collection, iteratees[0], iteratees[1])) {
    iteratees = [];
  } else if (length > 2 && _isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
    iteratees = [iteratees[0]];
  }

  return _baseOrderBy(collection, _baseFlatten(iteratees, 1), []);
});
/* harmony default export */ var lodash_es_sortBy = (sortBy);
// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/collection.js
//     Backbone.js 1.4.0
//     (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
//     Backbone may be freely distributed under the MIT license.
// Collection
// ----------
// If models tend to represent a single row of data, a Collection is
// more analogous to a table full of data ... or a small slice or page of that
// table, or a collection of rows that belong together for a particular reason
// -- all of the messages in this particular folder, all of the documents
// belonging to this particular author, and so on. Collections maintain
// indexes of their models, both in order, and for lookup by `id`.



















const slice = Array.prototype.slice; // Create a new **Collection**, perhaps to contain a specific type of `model`.
// If a `comparator` is specified, the Collection will maintain
// its models in sort order, as they're added and removed.

const Collection = function (models, options) {
  options || (options = {});
  this.preinitialize.apply(this, arguments);
  if (options.model) this.model = options.model;
  if (options.comparator !== undefined) this.comparator = options.comparator;

  this._reset();

  this.initialize.apply(this, arguments);
  if (models) this.reset(models, lodash_es_assignIn({
    silent: true
  }, options));
};
Collection.extend = inherits; // Default options for `Collection#set`.

const setOptions = {
  add: true,
  remove: true,
  merge: true
};
const addOptions = {
  add: true,
  remove: false
}; // Splices `insert` into `array` at index `at`.

const collection_splice = function (array, insert, at) {
  at = Math.min(Math.max(at, 0), array.length);
  const tail = Array(array.length - at);
  const length = insert.length;
  let i;

  for (i = 0; i < tail.length; i++) tail[i] = array[i + at];

  for (i = 0; i < length; i++) array[i + at] = insert[i];

  for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i];
}; // Define the Collection's inheritable methods.


Object.assign(Collection.prototype, Events, {
  // The default model for a collection is just a **Backbone.Model**.
  // This should be overridden in most cases.
  model: model_Model,
  // preinitialize is an empty function by default. You can override it with a function
  // or object.  preinitialize will run before any instantiation logic is run in the Collection.
  preinitialize: function () {},
  // Initialize is an empty function by default. Override it with your own
  // initialization logic.
  initialize: function () {},
  // The JSON representation of a Collection is an array of the
  // models' attributes.
  toJSON: function (options) {
    return this.map(function (model) {
      return model.toJSON(options);
    });
  },
  // Proxy `Backbone.sync` by default.
  sync: function (method, model, options) {
    return getSyncMethod(this)(method, model, options);
  },
  // Add a model, or list of models to the set. `models` may be Backbone
  // Models or raw JavaScript objects to be converted to Models, or any
  // combination of the two.
  add: function (models, options) {
    return this.set(models, lodash_es_assignIn({
      merge: false
    }, options, addOptions));
  },
  // Remove a model, or a list of models from the set.
  remove: function (models, options) {
    options = lodash_es_assignIn({}, options);
    const singular = !Array.isArray(models);
    models = singular ? [models] : models.slice();

    const removed = this._removeModels(models, options);

    if (!options.silent && removed.length) {
      options.changes = {
        added: [],
        merged: [],
        removed: removed
      };
      this.trigger('update', this, options);
    }

    return singular ? removed[0] : removed;
  },
  // Update a collection by `set`-ing a new list of models, adding new ones,
  // removing models that are no longer present, and merging models that
  // already exist in the collection, as necessary. Similar to **Model#set**,
  // the core operation for updating the data contained by the collection.
  set: function (models, options) {
    if (models == null) return;
    options = lodash_es_assignIn({}, setOptions, options);

    if (options.parse && !this._isModel(models)) {
      models = this.parse(models, options) || [];
    }

    const singular = !Array.isArray(models);
    models = singular ? [models] : models.slice();
    let at = options.at;
    if (at != null) at = +at;
    if (at > this.length) at = this.length;
    if (at < 0) at += this.length + 1;
    const set = [];
    const toAdd = [];
    const toMerge = [];
    const toRemove = [];
    const modelMap = {};
    const add = options.add;
    const merge = options.merge;
    const remove = options.remove;
    let sort = false;
    const sortable = this.comparator && at == null && options.sort !== false;
    const sortAttr = lodash_es_isString(this.comparator) ? this.comparator : null; // Turn bare objects into model references, and prevent invalid models
    // from being added.

    let model, i;

    for (i = 0; i < models.length; i++) {
      model = models[i]; // If a duplicate is found, prevent it from being added and
      // optionally merge it into the existing model.

      const existing = this.get(model);

      if (existing) {
        if (merge && model !== existing) {
          let attrs = this._isModel(model) ? model.attributes : model;
          if (options.parse) attrs = existing.parse(attrs, options);
          existing.set(attrs, options);
          toMerge.push(existing);
          if (sortable && !sort) sort = existing.hasChanged(sortAttr);
        }

        if (!modelMap[existing.cid]) {
          modelMap[existing.cid] = true;
          set.push(existing);
        }

        models[i] = existing; // If this is a new, valid model, push it to the `toAdd` list.
      } else if (add) {
        model = models[i] = this._prepareModel(model, options);

        if (model) {
          toAdd.push(model);

          this._addReference(model, options);

          modelMap[model.cid] = true;
          set.push(model);
        }
      }
    } // Remove stale models.


    if (remove) {
      for (i = 0; i < this.length; i++) {
        model = this.models[i];
        if (!modelMap[model.cid]) toRemove.push(model);
      }

      if (toRemove.length) this._removeModels(toRemove, options);
    } // See if sorting is needed, update `length` and splice in new models.


    let orderChanged = false;
    const replace = !sortable && add && remove;

    if (set.length && replace) {
      orderChanged = this.length !== set.length || lodash_es_some(this.models, (m, index) => m !== set[index]);
      this.models.length = 0;
      collection_splice(this.models, set, 0);
      this.length = this.models.length;
    } else if (toAdd.length) {
      if (sortable) sort = true;
      collection_splice(this.models, toAdd, at == null ? this.length : at);
      this.length = this.models.length;
    } // Silently sort the collection if appropriate.


    if (sort) this.sort({
      silent: true
    }); // Unless silenced, it's time to fire all appropriate add/sort/update events.

    if (!options.silent) {
      for (i = 0; i < toAdd.length; i++) {
        if (at != null) options.index = at + i;
        model = toAdd[i];
        model.trigger('add', model, this, options);
      }

      if (sort || orderChanged) this.trigger('sort', this, options);

      if (toAdd.length || toRemove.length || toMerge.length) {
        options.changes = {
          added: toAdd,
          removed: toRemove,
          merged: toMerge
        };
        this.trigger('update', this, options);
      }
    } // Return the added (or merged) model (or models).


    return singular ? models[0] : models;
  },
  clearStore: async function (options = {}, filter = o => o) {
    await Promise.all(this.models.filter(filter).map(m => {
      return new Promise(resolve => {
        m.destroy(Object.assign(options, {
          'success': resolve,
          'error': (m, e) => {
            console.error(e);
            resolve();
          }
        }));
      });
    }));
    await this.browserStorage.clear();
    this.reset();
  },
  // When you have more items than you want to add or remove individually,
  // you can reset the entire set with a new list of models, without firing
  // any granular `add` or `remove` events. Fires `reset` when finished.
  // Useful for bulk operations and optimizations.
  reset: function (models, options) {
    options = options ? lodash_es_clone(options) : {};

    for (let i = 0; i < this.models.length; i++) {
      this._removeReference(this.models[i], options);
    }

    options.previousModels = this.models;

    this._reset();

    models = this.add(models, lodash_es_assignIn({
      silent: true
    }, options));
    if (!options.silent) this.trigger('reset', this, options);
    return models;
  },
  // Add a model to the end of the collection.
  push: function (model, options) {
    return this.add(model, lodash_es_assignIn({
      at: this.length
    }, options));
  },
  // Remove a model from the end of the collection.
  pop: function (options) {
    const model = this.at(this.length - 1);
    return this.remove(model, options);
  },
  // Add a model to the beginning of the collection.
  unshift: function (model, options) {
    return this.add(model, lodash_es_assignIn({
      at: 0
    }, options));
  },
  // Remove a model from the beginning of the collection.
  shift: function (options) {
    const model = this.at(0);
    return this.remove(model, options);
  },
  // Slice out a sub-array of models from the collection.
  slice: function () {
    return slice.apply(this.models, arguments);
  },
  filter: function (callback, thisArg) {
    return this.models.filter(lodash_es_isFunction(callback) ? callback : m => m.matches(callback), thisArg);
  },
  every: function (pred) {
    return lodash_es_every(this.models.map(m => m.attributes), pred);
  },
  difference: function (values) {
    return lodash_es_difference(this.models, values);
  },
  max: function () {
    return Math.max.apply(Math, this.models);
  },
  min: function () {
    return Math.min.apply(Math, this.models);
  },
  drop: function (n = 1) {
    return this.models.slice(n);
  },
  some: function (pred) {
    return lodash_es_some(this.models.map(m => m.attributes), pred);
  },
  sortBy: function (iteratee) {
    return lodash_es_sortBy(this.models, lodash_es_isFunction(iteratee) ? iteratee : m => lodash_es_isString(iteratee) ? m.get(iteratee) : m.matches(iteratee));
  },
  isEmpty: function () {
    return lodash_es_isEmpty(this.models);
  },
  keyBy: function (iteratee) {
    return lodash_es_keyBy(this.models, iteratee);
  },
  each: function (callback, thisArg) {
    return this.forEach(callback, thisArg);
  },
  forEach: function (callback, thisArg) {
    return this.models.forEach(callback, thisArg);
  },
  includes: function (item) {
    return this.models.includes(item);
  },
  size: function () {
    return this.models.length;
  },
  countBy: function (f) {
    return lodash_es_countBy(this.models, lodash_es_isFunction(f) ? f : m => lodash_es_isString(f) ? m.get(f) : m.matches(f));
  },
  groupBy: function (pred) {
    return lodash_es_groupBy(this.models, lodash_es_isFunction(pred) ? pred : m => lodash_es_isString(pred) ? m.get(pred) : m.matches(pred));
  },
  indexOf: function (fromIndex) {
    return lodash_es_indexOf(this.models, fromIndex);
  },
  findLastIndex: function (pred, fromIndex) {
    return lodash_es_findLastIndex(this.models, lodash_es_isFunction(pred) ? pred : m => lodash_es_isString(pred) ? m.get(pred) : m.matches(pred), fromIndex);
  },
  lastIndexOf: function (fromIndex) {
    return lodash_es_lastIndexOf(this.models, fromIndex);
  },
  findIndex: function (pred) {
    return lodash_es_findIndex(this.models, lodash_es_isFunction(pred) ? pred : m => lodash_es_isString(pred) ? m.get(pred) : m.matches(pred));
  },
  last: function () {
    const length = this.models == null ? 0 : this.models.length;
    return length ? this.models[length - 1] : undefined;
  },
  head: function () {
    return this.models[0];
  },
  first: function () {
    return this.head();
  },
  map: function (cb, thisArg) {
    return this.models.map(lodash_es_isFunction(cb) ? cb : m => lodash_es_isString(cb) ? m.get(cb) : m.matches(cb), thisArg);
  },
  reduce: function (callback, initialValue) {
    return this.models.reduce(callback, initialValue || this.models[0]);
  },
  reduceRight: function (callback, initialValue) {
    return this.models.reduceRight(callback, initialValue || this.models[0]);
  },
  toArray: function () {
    return Array.from(this.models);
  },
  // Get a model from the set by id, cid, model object with id or cid
  // properties, or an attributes object that is transformed through modelId.
  get: function (obj) {
    if (obj == null) return undefined;
    return this._byId[obj] || this._byId[this.modelId(this._isModel(obj) ? obj.attributes : obj)] || obj.cid && this._byId[obj.cid];
  },
  // Returns `true` if the model is in the collection.
  has: function (obj) {
    return this.get(obj) != null;
  },
  // Get the model at the given index.
  at: function (index) {
    if (index < 0) index += this.length;
    return this.models[index];
  },
  // Return models with matching attributes. Useful for simple cases of
  // `filter`.
  where: function (attrs, first) {
    return this[first ? 'find' : 'filter'](attrs);
  },
  // Return the first model with matching attributes. Useful for simple cases
  // of `find`.
  findWhere: function (attrs) {
    return this.where(attrs, true);
  },
  find: function (predicate, fromIndex) {
    const pred = lodash_es_isFunction(predicate) ? predicate : m => m.matches(predicate);
    return this.models.find(pred, fromIndex);
  },
  // Force the collection to re-sort itself. You don't need to call this under
  // normal circumstances, as the set will maintain sort order as each item
  // is added.
  sort: function (options) {
    let comparator = this.comparator;
    if (!comparator) throw new Error('Cannot sort a set without a comparator');
    options || (options = {});
    const length = comparator.length;
    if (lodash_es_isFunction(comparator)) comparator = comparator.bind(this); // Run sort based on type of `comparator`.

    if (length === 1 || lodash_es_isString(comparator)) {
      this.models = this.sortBy(comparator);
    } else {
      this.models.sort(comparator);
    }

    if (!options.silent) this.trigger('sort', this, options);
    return this;
  },
  // Pluck an attribute from each model in the collection.
  pluck: function (attr) {
    return this.map(attr + '');
  },
  // Fetch the default set of models for this collection, resetting the
  // collection when they arrive. If `reset: true` is passed, the response
  // data will be passed through the `reset` method instead of `set`.
  fetch: function (options) {
    options = lodash_es_assignIn({
      parse: true
    }, options);
    const success = options.success;
    const collection = this;
    const promise = options.promise && getResolveablePromise();

    options.success = function (resp) {
      const method = options.reset ? 'reset' : 'set';
      collection[method](resp, options);
      if (success) success.call(options.context, collection, resp, options);
      promise && promise.resolve();
      collection.trigger('sync', collection, resp, options);
    };

    wrapError(this, options);
    return promise ? promise : this.sync('read', this, options);
  },
  // Create a new instance of a model in this collection. Add the model to the
  // collection immediately, unless `wait: true` is passed, in which case we
  // wait for the server to agree.
  create: function (model, options) {
    options = options ? lodash_es_clone(options) : {};
    const wait = options.wait;
    const return_promise = options.promise;
    const promise = return_promise && getResolveablePromise();
    model = this._prepareModel(model, options);
    if (!model) return false;
    if (!wait) this.add(model, options);
    const collection = this;
    const success = options.success;
    const error = options.error;

    options.success = function (m, resp, callbackOpts) {
      if (wait) {
        collection.add(m, callbackOpts);
      }

      if (success) {
        success.call(callbackOpts.context, m, resp, callbackOpts);
      }

      if (return_promise) {
        promise.resolve(m);
      }
    };

    options.error = function (model, e, options) {
      error && error.call(options.context, model, e, options);
      return_promise && promise.reject(e);
    };

    model.save(null, Object.assign(options, {
      'promise': false
    }));

    if (return_promise) {
      return promise;
    } else {
      return model;
    }
  },
  // **parse** converts a response into a list of models to be added to the
  // collection. The default implementation is just to pass it through.
  parse: function (resp, options) {
    return resp;
  },
  // Create a new collection with an identical list of models as this one.
  clone: function () {
    return new this.constructor(this.models, {
      model: this.model,
      comparator: this.comparator
    });
  },
  // Define how to uniquely identify models in the collection.
  modelId: function (attrs) {
    return attrs[this.model.prototype.idAttribute || 'id'];
  },
  // Get an iterator of all models in this collection.
  values: function () {
    return new CollectionIterator(this, ITERATOR_VALUES);
  },
  // Get an iterator of all model IDs in this collection.
  keys: function () {
    return new CollectionIterator(this, ITERATOR_KEYS);
  },
  // Get an iterator of all [ID, model] tuples in this collection.
  entries: function () {
    return new CollectionIterator(this, ITERATOR_KEYSVALUES);
  },
  // Private method to reset all internal state. Called when the collection
  // is first initialized or reset.
  _reset: function () {
    this.length = 0;
    this.models = [];
    this._byId = {};
  },
  // Prepare a hash of attributes (or other model) to be added to this
  // collection.
  _prepareModel: function (attrs, options) {
    if (this._isModel(attrs)) {
      if (!attrs.collection) attrs.collection = this;
      return attrs;
    }

    options = options ? lodash_es_clone(options) : {};
    options.collection = this;
    const model = new this.model(attrs, options);
    if (!model.validationError) return model;
    this.trigger('invalid', this, model.validationError, options);
    return false;
  },
  // Internal method called by both remove and set.
  _removeModels: function (models, options) {
    const removed = [];

    for (let i = 0; i < models.length; i++) {
      const model = this.get(models[i]);
      if (!model) continue;
      const index = this.indexOf(model);
      this.models.splice(index, 1);
      this.length--; // Remove references before triggering 'remove' event to prevent an
      // infinite loop. #3693

      delete this._byId[model.cid];
      const id = this.modelId(model.attributes);
      if (id != null) delete this._byId[id];

      if (!options.silent) {
        options.index = index;
        model.trigger('remove', model, this, options);
      }

      removed.push(model);

      this._removeReference(model, options);
    }

    return removed;
  },
  // Method for checking whether an object should be considered a model for
  // the purposes of adding to the collection.
  _isModel: function (model) {
    return model instanceof model_Model;
  },
  // Internal method to create a model's ties to a collection.
  _addReference: function (model, options) {
    this._byId[model.cid] = model;
    const id = this.modelId(model.attributes);
    if (id != null) this._byId[id] = model;
    model.on('all', this._onModelEvent, this);
  },
  // Internal method to sever a model's ties to a collection.
  _removeReference: function (model, options) {
    delete this._byId[model.cid];
    const id = this.modelId(model.attributes);
    if (id != null) delete this._byId[id];
    if (this === model.collection) delete model.collection;
    model.off('all', this._onModelEvent, this);
  },
  // Internal method called every time a model in the set fires an event.
  // Sets need to update their indexes when models change ids. All other
  // events simply proxy through. "add" and "remove" events that originate
  // in other collections are ignored.
  _onModelEvent: function (event, model, collection, options) {
    if (model) {
      if ((event === 'add' || event === 'remove') && collection !== this) return;
      if (event === 'destroy') this.remove(model, options);

      if (event === 'change') {
        const prevId = this.modelId(model.previousAttributes());
        const id = this.modelId(model.attributes);

        if (prevId !== id) {
          if (prevId != null) delete this._byId[prevId];
          if (id != null) this._byId[id] = model;
        }
      }
    }

    this.trigger.apply(this, arguments);
  }
}); // Defining an @@iterator method implements JavaScript's Iterable protocol.
// In modern ES2015 browsers, this value is found at Symbol.iterator.

/* global Symbol */

const $$iterator = typeof Symbol === 'function' && Symbol.iterator;

if ($$iterator) {
  Collection.prototype[$$iterator] = Collection.prototype.values;
} // CollectionIterator
// ------------------
// A CollectionIterator implements JavaScript's Iterator protocol, allowing the
// use of `for of` loops in modern browsers and interoperation between
// Collection and other JavaScript functions and third-party libraries
// which can operate on Iterables.


const CollectionIterator = function (collection, kind) {
  this._collection = collection;
  this._kind = kind;
  this._index = 0;
}; // This "enum" defines the three possible kinds of values which can be emitted
// by a CollectionIterator that correspond to the values(), keys() and entries()
// methods on Collection, respectively.


const ITERATOR_VALUES = 1;
const ITERATOR_KEYS = 2;
const ITERATOR_KEYSVALUES = 3; // All Iterators should themselves be Iterable.

if ($$iterator) {
  CollectionIterator.prototype[$$iterator] = function () {
    return this;
  };
}

CollectionIterator.prototype.next = function () {
  if (this._collection) {
    // Only continue iterating if the iterated collection is long enough.
    if (this._index < this._collection.length) {
      const model = this._collection.at(this._index);

      this._index++; // Construct a value depending on what kind of values should be iterated.

      let value;

      if (this._kind === ITERATOR_VALUES) {
        value = model;
      } else {
        const id = this._collection.modelId(model.attributes);

        if (this._kind === ITERATOR_KEYS) {
          value = id;
        } else {
          // ITERATOR_KEYSVALUES
          value = [id, model];
        }
      }

      return {
        value: value,
        done: false
      };
    } // Once exhausted, remove the reference to the collection so future
    // calls to the next method always return done.


    this._collection = undefined;
  }

  return {
    value: undefined,
    done: true
  };
};
// EXTERNAL MODULE: ./node_modules/lodash/lodash.js
var lodash = __webpack_require__(39);

// CONCATENATED MODULE: ./src/headless/connection.js






const BOSH_WAIT = 59;
/**
 * The Connection class manages the connection to the XMPP server. It's
 * agnostic concerning the underlying protocol (i.e. websocket, long-polling
 * via BOSH or websocket inside a shared worker).
 */

class connection_Connection extends core["f" /* Strophe */].Connection {
  constructor(service, options) {
    super(service, options);
    this.debouncedReconnect = Object(lodash["debounce"])(this.reconnect, 2000);
  }

  static generateResource() {
    return `/converse.js-${Math.floor(Math.random() * 139749528).toString()}`;
  }

  async bind() {
    /**
     * Synchronous event triggered before we send an IQ to bind the user's
     * JID resource for this session.
     * @event _converse#beforeResourceBinding
     */
    await converse_core_api.trigger('beforeResourceBinding', {
      'synchronous': true
    });
    super.bind();
  }

  async onDomainDiscovered(response) {
    const text = await response.text();
    const xrd = new window.DOMParser().parseFromString(text, "text/xml").firstElementChild;

    if (xrd.nodeName != "XRD" || xrd.namespaceURI != "http://docs.oasis-open.org/ns/xri/xrd-1.0") {
      return headless_log.warn("Could not discover XEP-0156 connection methods");
    }

    const bosh_links = sizzle_default()(`Link[rel="urn:xmpp:alt-connections:xbosh"]`, xrd);
    const ws_links = sizzle_default()(`Link[rel="urn:xmpp:alt-connections:websocket"]`, xrd);
    const bosh_methods = bosh_links.map(el => el.getAttribute('href'));
    const ws_methods = ws_links.map(el => el.getAttribute('href'));

    if (bosh_methods.length === 0 && ws_methods.length === 0) {
      headless_log.warn("Neither BOSH nor WebSocket connection methods have been specified with XEP-0156.");
    } else {
      // TODO: support multiple endpoints
      converse_core_api.settings.set("websocket_url", ws_methods.pop());
      converse_core_api.settings.set('bosh_service_url', bosh_methods.pop());
      this.service = converse_core_api.settings.get("websocket_url") || converse_core_api.settings.get('bosh_service_url');
      this.setProtocol();
    }
  }
  /**
   * Adds support for XEP-0156 by quering the XMPP server for alternate
   * connection methods. This allows users to use the websocket or BOSH
   * connection of their own XMPP server instead of a proxy provided by the
   * host of Converse.js.
   * @method Connnection.discoverConnectionMethods
   */


  async discoverConnectionMethods(domain) {
    // Use XEP-0156 to check whether this host advertises websocket or BOSH connection methods.
    const options = {
      'mode': 'cors',
      'headers': {
        'Accept': 'application/xrd+xml, text/xml'
      }
    };
    const url = `https://${domain}/.well-known/host-meta`;
    let response;

    try {
      response = await fetch(url, options);
    } catch (e) {
      headless_log.error(`Failed to discover alternative connection methods at ${url}`);
      headless_log.error(e);
      return;
    }

    if (response.status >= 200 && response.status < 400) {
      await this.onDomainDiscovered(response);
    } else {
      headless_log.warn("Could not discover XEP-0156 connection methods");
    }
  }
  /**
   * Establish a new XMPP session by logging in with the supplied JID and
   * password.
   * @method Connnection.connect
   * @param { String } jid
   * @param { String } password
   * @param { Funtion } callback
   */


  async connect(jid, password, callback) {
    if (converse_core_api.settings.get("discover_connection_methods")) {
      const domain = core["f" /* Strophe */].getDomainFromJid(jid);
      await this.discoverConnectionMethods(domain);
    }

    super.connect(jid, password, callback || this.onConnectStatusChanged, BOSH_WAIT);
  }

  async reconnect() {
    const {
      __
    } = converse_core_converse;
    headless_log.debug('RECONNECTING: the connection has dropped, attempting to reconnect.');
    this.setConnectionStatus(core["f" /* Strophe */].Status.RECONNECTING, __('The connection has dropped, attempting to reconnect.'));
    /**
    * Triggered when the connection has dropped, but Converse will attempt
    * to reconnect again.
    *
    * @event _converse#will-reconnect
    */

    converse_core_api.trigger('will-reconnect');
    this.reconnecting = true;
    await tearDown();
    return converse_core_api.user.login();
  }
  /**
   * Called as soon as a new connection has been established, either
   * by logging in or by attaching to an existing BOSH session.
   * @method Connection.onConnected
   * @param { Boolean } reconnecting - Whether Converse.js reconnected from an earlier dropped session.
   */


  async onConnected(reconnecting) {
    delete this.reconnecting;
    this.flush(); // Solves problem of returned PubSub BOSH response not received by browser

    await converse_core_converse.setUserJID(this.jid);
    /**
     * Synchronous event triggered after we've sent an IQ to bind the
     * user's JID resource for this session.
     * @event _converse#afterResourceBinding
     */

    await converse_core_api.trigger('afterResourceBinding', reconnecting, {
      'synchronous': true
    });

    if (reconnecting) {
      /**
       * After the connection has dropped and converse.js has reconnected.
       * Any Strophe stanza handlers (as registered via `converse.listen.stanza`) will
       * have to be registered anew.
       * @event _converse#reconnected
       * @example _converse.api.listen.on('reconnected', () => { ... });
       */
      converse_core_api.trigger('reconnected');
    } else {
      /**
       * Triggered after the connection has been established and Converse
       * has got all its ducks in a row.
       * @event _converse#initialized
       */
      converse_core_api.trigger('connected');
    }
  }
  /**
   * Used to keep track of why we got disconnected, so that we can
   * decide on what the next appropriate action is (in onDisconnected)
   * @method Connection.setDisconnectionCause
   * @param { Number } cause - The status number as received from Strophe.
   * @param { String } [reason] - An optional user-facing message as to why
   *  there was a disconnection.
   * @param { Boolean } [override] - An optional flag to replace any previous
   *  disconnection cause and reason.
   */


  setDisconnectionCause(cause, reason, override) {
    if (cause === undefined) {
      delete this.disconnection_cause;
      delete this.disconnection_reason;
    } else if (this.disconnection_cause === undefined || override) {
      this.disconnection_cause = cause;
      this.disconnection_reason = reason;
    }
  }

  setConnectionStatus(status, message) {
    this.status = status;

    converse_core_converse.connfeedback.set({
      'connection_status': status,
      message
    });
  }

  async finishDisconnection() {
    // Properly tear down the session so that it's possible to manually connect again.
    headless_log.debug('DISCONNECTED');
    delete this.reconnecting;
    this.reset();
    tearDown();
    await clearSession();
    delete converse_core_converse.connection;
    /**
    * Triggered after converse.js has disconnected from the XMPP server.
    * @event _converse#disconnected
    * @memberOf _converse
    * @example _converse.api.listen.on('disconnected', () => { ... });
    */

    converse_core_api.trigger('disconnected');
  }
  /**
   * Gets called once strophe's status reaches Strophe.Status.DISCONNECTED.
   * Will either start a teardown process for converse.js or attempt
   * to reconnect.
   * @method onDisconnected
   */


  onDisconnected() {
    if (converse_core_api.settings.get("auto_reconnect")) {
      const reason = this.disconnection_reason;

      if (this.disconnection_cause === core["f" /* Strophe */].Status.AUTHFAIL) {
        if (converse_core_api.settings.get("credentials_url") || converse_core_api.settings.get("authentication") === converse_core_converse.ANONYMOUS) {
          // If `credentials_url` is set, we reconnect, because we might
          // be receiving expirable tokens from the credentials_url.
          //
          // If `authentication` is anonymous, we reconnect because we
          // might have tried to attach with stale BOSH session tokens
          // or with a cached JID and password
          return converse_core_api.connection.reconnect();
        } else {
          return this.finishDisconnection();
        }
      } else if (this.disconnection_cause === converse_core_converse.LOGOUT || reason === core["f" /* Strophe */].ErrorCondition.NO_AUTH_MECH || reason === "host-unknown" || reason === "remote-connection-failed") {
        return this.finishDisconnection();
      }

      converse_core_api.connection.reconnect();
    } else {
      return this.finishDisconnection();
    }
  }
  /**
   * Callback method called by Strophe as the Connection goes
   * through various states while establishing or tearing down a
   * connection.
   * @param { Number } status
   * @param { String } message
   */


  onConnectStatusChanged(status, message) {
    const {
      __
    } = converse_core_converse;
    headless_log.debug(`Status changed to: ${converse_core_converse.CONNECTION_STATUS[status]}`);

    if (status === core["f" /* Strophe */].Status.ATTACHFAIL) {
      var _this$worker_attach_p;

      this.setConnectionStatus(status);
      (_this$worker_attach_p = this.worker_attach_promise) === null || _this$worker_attach_p === void 0 ? void 0 : _this$worker_attach_p.resolve(false);
    } else if (status === core["f" /* Strophe */].Status.CONNECTED || status === core["f" /* Strophe */].Status.ATTACHED) {
      var _this$worker_attach_p2, _this$worker_attach_p3;

      if ((_this$worker_attach_p2 = this.worker_attach_promise) !== null && _this$worker_attach_p2 !== void 0 && _this$worker_attach_p2.isResolved && this.status === core["f" /* Strophe */].Status.ATTACHED) {
        // A different tab must have attached, so nothing to do for us here.
        return;
      }

      this.setConnectionStatus(status);
      (_this$worker_attach_p3 = this.worker_attach_promise) === null || _this$worker_attach_p3 === void 0 ? void 0 : _this$worker_attach_p3.resolve(true); // By default we always want to send out an initial presence stanza.

      converse_core_converse.send_initial_presence = true;
      this.setDisconnectionCause();

      if (this.reconnecting) {
        headless_log.debug(status === core["f" /* Strophe */].Status.CONNECTED ? 'Reconnected' : 'Reattached');
        this.onConnected(true);
      } else {
        headless_log.debug(status === core["f" /* Strophe */].Status.CONNECTED ? 'Connected' : 'Attached');

        if (this.restored) {
          // No need to send an initial presence stanza when
          // we're restoring an existing session.
          converse_core_converse.send_initial_presence = false;
        }

        this.onConnected();
      }
    } else if (status === core["f" /* Strophe */].Status.DISCONNECTED) {
      this.setDisconnectionCause(status, message);
      this.onDisconnected();
    } else if (status === core["f" /* Strophe */].Status.BINDREQUIRED) {
      this.bind();
    } else if (status === core["f" /* Strophe */].Status.ERROR) {
      this.setConnectionStatus(status, __('An error occurred while connecting to the chat server.'));
    } else if (status === core["f" /* Strophe */].Status.CONNECTING) {
      this.setConnectionStatus(status);
    } else if (status === core["f" /* Strophe */].Status.AUTHENTICATING) {
      this.setConnectionStatus(status);
    } else if (status === core["f" /* Strophe */].Status.AUTHFAIL) {
      if (!message) {
        message = __('Your XMPP address and/or password is incorrect. Please try again.');
      }

      this.setConnectionStatus(status, message);
      this.setDisconnectionCause(status, message, true);
      this.onDisconnected();
    } else if (status === core["f" /* Strophe */].Status.CONNFAIL) {
      var _Strophe$ErrorConditi;

      let feedback = message;

      if (message === "host-unknown" || message == "remote-connection-failed") {
        feedback = __("Sorry, we could not connect to the XMPP host with domain: %1$s", `\"${core["f" /* Strophe */].getDomainFromJid(this.jid)}\"`);
      } else if (message !== undefined && message === (core["f" /* Strophe */] === null || core["f" /* Strophe */] === void 0 ? void 0 : (_Strophe$ErrorConditi = core["f" /* Strophe */].ErrorCondition) === null || _Strophe$ErrorConditi === void 0 ? void 0 : _Strophe$ErrorConditi.NO_AUTH_MECH)) {
        feedback = __("The XMPP server did not offer a supported authentication mechanism");
      }

      this.setConnectionStatus(status, feedback);
      this.setDisconnectionCause(status, message);
    } else if (status === core["f" /* Strophe */].Status.DISCONNECTING) {
      this.setDisconnectionCause(status, message);
    }
  }

  isType(type) {
    if (type.toLowerCase() === 'websocket') {
      return this._proto instanceof core["f" /* Strophe */].Websocket;
    } else if (type.toLowerCase() === 'bosh') {
      return core["f" /* Strophe */].Bosh && this._proto instanceof core["f" /* Strophe */].Bosh;
    }
  }

  hasResumed() {
    var _api$settings$get;

    if ((_api$settings$get = converse_core_api.settings.get("connection_options")) !== null && _api$settings$get !== void 0 && _api$settings$get.worker || this.isType('bosh')) {
      return converse_core_converse.connfeedback.get('connection_status') === core["f" /* Strophe */].Status.ATTACHED;
    } else {
      // Not binding means that the session was resumed.
      return !this.do_bind;
    }
  }

  restoreWorkerSession() {
    this.attach(this.onConnectStatusChanged);
    this.worker_attach_promise = utils_core.getResolveablePromise();
    return this.worker_attach_promise;
  }

}
/**
 * The MockConnection class is used during testing, to mock an XMPP connection.
 * @class
 */

class connection_MockConnection extends connection_Connection {
  constructor(service, options) {
    super(service, options);
    this.sent_stanzas = [];
    this.IQ_stanzas = [];
    this.IQ_ids = [];
    this.features = core["f" /* Strophe */].xmlHtmlNode('<stream:features xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">' + '<ver xmlns="urn:xmpp:features:rosterver"/>' + '<csi xmlns="urn:xmpp:csi:0"/>' + '<this xmlns="http://jabber.org/protocol/caps" ver="UwBpfJpEt3IoLYfWma/o/p3FFRo=" hash="sha-1" node="http://prosody.im"/>' + '<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">' + '<required/>' + '</bind>' + `<sm xmlns='urn:xmpp:sm:3'/>` + '<session xmlns="urn:ietf:params:xml:ns:xmpp-session">' + '<optional/>' + '</session>' + '</stream:features>').firstChild;

    this._proto._processRequest = () => {};

    this._proto._disconnect = () => this._onDisconnectTimeout();

    this._proto._onDisconnectTimeout = () => {};

    this._proto._connect = () => {
      this.connected = true;
      this.mock = true;
      this.jid = 'romeo@montague.lit/orchard';

      this._changeConnectStatus(core["f" /* Strophe */].Status.BINDREQUIRED);
    };
  }

  _processRequest() {// eslint-disable-line class-methods-use-this
    // Don't attempt to send out stanzas
  }

  sendIQ(iq, callback, errback) {
    if (!Object(lodash["isElement"])(iq)) {
      iq = iq.nodeTree;
    }

    this.IQ_stanzas.push(iq);
    const id = super.sendIQ(iq, callback, errback);
    this.IQ_ids.push(id);
    return id;
  }

  send(stanza) {
    if (Object(lodash["isElement"])(stanza)) {
      this.sent_stanzas.push(stanza);
    } else {
      this.sent_stanzas.push(stanza.nodeTree);
    }

    return super.send(stanza);
  }

  async bind() {
    await converse_core_api.trigger('beforeResourceBinding', {
      'synchronous': true
    });
    this.authenticated = true;

    if (!converse_core_converse.no_connection_on_bind) {
      this._changeConnectStatus(core["f" /* Strophe */].Status.CONNECTED);
    }
  }

}
// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/history.js
//  Backbone.js 1.4.0
//  (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
//  Backbone may be freely distributed under the MIT license.



 // History
// -------
// Handles cross-browser history management, based on either
// [pushState](http://diveintohtml5.info/history.html) and real URLs, or
// [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
// and URL fragments. If the browser supports neither (old IE, natch),
// falls back to polling.

const history_History = function () {
  this.handlers = [];
  this.checkUrl = this.checkUrl.bind(this); // Ensure that `History` can be used outside of the browser.

  if (typeof window !== 'undefined') {
    this.location = window.location;
    this.history = window.history;
  }
};

history_History.extend = inherits; // Cached regex for stripping a leading hash/slash and trailing space.

const routeStripper = /^[#\/]|\s+$/g; // Cached regex for stripping leading and trailing slashes.

const rootStripper = /^\/+|\/+$/g; // Cached regex for stripping urls of hash.

const pathStripper = /#.*$/; // Has the history handling already been started?

history_History.started = false; // Set up all inheritable **History** properties and methods.

Object.assign(history_History.prototype, Events, {
  // The default interval to poll for hash changes, if necessary, is
  // twenty times a second.
  interval: 50,
  // Are we at the app root?
  atRoot: function () {
    const path = this.location.pathname.replace(/[^\/]$/, '$&/');
    return path === this.root && !this.getSearch();
  },
  // Does the pathname match the root?
  matchRoot: function () {
    const path = this.decodeFragment(this.location.pathname);
    const rootPath = path.slice(0, this.root.length - 1) + '/';
    return rootPath === this.root;
  },
  // Unicode characters in `location.pathname` are percent encoded so they're
  // decoded for comparison. `%25` should not be decoded since it may be part
  // of an encoded parameter.
  decodeFragment: function (fragment) {
    return decodeURI(fragment.replace(/%25/g, '%2525'));
  },
  // In IE6, the hash fragment and search params are incorrect if the
  // fragment contains `?`.
  getSearch: function () {
    const match = this.location.href.replace(/#.*/, '').match(/\?.+/);
    return match ? match[0] : '';
  },
  // Gets the true hash value. Cannot use location.hash directly due to bug
  // in Firefox where location.hash will always be decoded.
  getHash: function (window) {
    const match = (window || this).location.href.match(/#(.*)$/);
    return match ? match[1] : '';
  },
  // Get the pathname and search params, without the root.
  getPath: function () {
    const path = this.decodeFragment(this.location.pathname + this.getSearch()).slice(this.root.length - 1);
    return path.charAt(0) === '/' ? path.slice(1) : path;
  },
  // Get the cross-browser normalized URL fragment from the path or hash.
  getFragment: function (fragment) {
    if (fragment == null) {
      if (this._usePushState || !this._wantsHashChange) {
        fragment = this.getPath();
      } else {
        fragment = this.getHash();
      }
    }

    return fragment.replace(routeStripper, '');
  },
  // Start the hash change handling, returning `true` if the current URL matches
  // an existing route, and `false` otherwise.
  start: function (options) {
    if (history_History.started) throw new Error('history has already been started');
    history_History.started = true; // Figure out the initial configuration. Do we need an iframe?
    // Is pushState desired ... is it available?

    this.options = lodash_es_assignIn({
      root: '/'
    }, this.options, options);
    this.root = this.options.root;
    this._wantsHashChange = this.options.hashChange !== false;
    this._hasHashChange = 'onhashchange' in window && (document.documentMode === undefined || document.documentMode > 7);
    this._useHashChange = this._wantsHashChange && this._hasHashChange;
    this._wantsPushState = !!this.options.pushState;
    this._hasPushState = !!(this.history && this.history.pushState);
    this._usePushState = this._wantsPushState && this._hasPushState;
    this.fragment = this.getFragment(); // Normalize root to always include a leading and trailing slash.

    this.root = ('/' + this.root + '/').replace(rootStripper, '/'); // Transition from hashChange to pushState or vice versa if both are
    // requested.

    if (this._wantsHashChange && this._wantsPushState) {
      // If we've started off with a route from a `pushState`-enabled
      // browser, but we're currently in a browser that doesn't support it...
      if (!this._hasPushState && !this.atRoot()) {
        const rootPath = this.root.slice(0, -1) || '/';
        this.location.replace(rootPath + '#' + this.getPath()); // Return immediately as browser will do redirect to new url

        return true; // Or if we've started out with a hash-based route, but we're currently
        // in a browser where it could be `pushState`-based instead...
      } else if (this._hasPushState && this.atRoot()) {
        this.navigate(this.getHash(), {
          replace: true
        });
      }
    } // Proxy an iframe to handle location events if the browser doesn't
    // support the `hashchange` event, HTML5 history, or the user wants
    // `hashChange` but not `pushState`.


    if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
      this.iframe = document.createElement('iframe');
      this.iframe.src = 'javascript:0';
      this.iframe.style.display = 'none';
      this.iframe.tabIndex = -1;
      const body = document.body; // Using `appendChild` will throw on IE < 9 if the document is not ready.

      const iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;
      iWindow.document.open();
      iWindow.document.close();
      iWindow.location.hash = '#' + this.fragment;
    } // Depending on whether we're using pushState or hashes, and whether
    // 'onhashchange' is supported, determine how we check the URL state.


    if (this._usePushState) {
      addEventListener('popstate', this.checkUrl, false);
    } else if (this._useHashChange && !this.iframe) {
      addEventListener('hashchange', this.checkUrl, false);
    } else if (this._wantsHashChange) {
      this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
    }

    if (!this.options.silent) return this.loadUrl();
  },
  // Disable history, perhaps temporarily. Not useful in a real app,
  // but possibly useful for unit testing Routers.
  stop: function () {
    // Remove window listeners.
    if (this._usePushState) {
      removeEventListener('popstate', this.checkUrl, false);
    } else if (this._useHashChange && !this.iframe) {
      removeEventListener('hashchange', this.checkUrl, false);
    } // Clean up the iframe if necessary.


    if (this.iframe) {
      document.body.removeChild(this.iframe);
      this.iframe = null;
    } // Some environments will throw when clearing an undefined interval.


    if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
    history_History.started = false;
  },
  // Add a route to be tested when the fragment changes. Routes added later
  // may override previous routes.
  route: function (route, callback) {
    this.handlers.unshift({
      route: route,
      callback: callback
    });
  },
  // Checks the current URL to see if it has changed, and if it has,
  // calls `loadUrl`, normalizing across the hidden iframe.
  checkUrl: function (e) {
    let current = this.getFragment(); // If the user pressed the back button, the iframe's hash will have
    // changed and we should use that for comparison.

    if (current === this.fragment && this.iframe) {
      current = this.getHash(this.iframe.contentWindow);
    }

    if (current === this.fragment) return false;
    if (this.iframe) this.navigate(current);
    this.loadUrl();
  },
  // Attempt to load the current URL fragment. If a route succeeds with a
  // match, returns `true`. If no defined routes matches the fragment,
  // returns `false`.
  loadUrl: function (fragment) {
    // If the root doesn't match, no routes can match either.
    if (!this.matchRoot()) return false;
    fragment = this.fragment = this.getFragment(fragment);
    return lodash_es_some(this.handlers, function (handler) {
      if (handler.route.test(fragment)) {
        handler.callback(fragment);
        return true;
      }
    });
  },
  // Save a fragment into the hash history, or replace the URL state if the
  // 'replace' option is passed. You are responsible for properly URL-encoding
  // the fragment in advance.
  //
  // The options object can contain `trigger: true` if you wish to have the
  // route callback be fired (not usually desirable), or `replace: true`, if
  // you wish to modify the current URL without adding an entry to the history.
  navigate: function (fragment, options) {
    if (!history_History.started) return false;
    if (!options || options === true) options = {
      trigger: !!options
    }; // Normalize the fragment.

    fragment = this.getFragment(fragment || ''); // Don't include a trailing slash on the root.

    let rootPath = this.root;

    if (fragment === '' || fragment.charAt(0) === '?') {
      rootPath = rootPath.slice(0, -1) || '/';
    }

    const url = rootPath + fragment; // Strip the fragment of the query and hash for matching.

    fragment = fragment.replace(pathStripper, ''); // Decode for matching.

    const decodedFragment = this.decodeFragment(fragment);
    if (this.fragment === decodedFragment) return;
    this.fragment = decodedFragment; // If pushState is available, we use it to set the fragment as a real URL.

    if (this._usePushState) {
      this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); // If hash changes haven't been explicitly disabled, update the hash
      // fragment to store history.
    } else if (this._wantsHashChange) {
      this._updateHash(this.location, fragment, options.replace);

      if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) {
        const iWindow = this.iframe.contentWindow; // Opening and closing the iframe tricks IE7 and earlier to push a
        // history entry on hash-tag change.  When replace is true, we don't
        // want this.

        if (!options.replace) {
          iWindow.document.open();
          iWindow.document.close();
        }

        this._updateHash(iWindow.location, fragment, options.replace);
      } // If you've told us that you explicitly don't want fallback hashchange-
      // based history, then `navigate` becomes a page refresh.

    } else {
      return this.location.assign(url);
    }

    if (options.trigger) return this.loadUrl(fragment);
  },
  // Update the hash location, either replacing the current entry, or adding
  // a new one to the browser history.
  _updateHash: function (location, fragment, replace) {
    if (replace) {
      const href = location.href.replace(/(javascript:|#).*$/, '');
      location.replace(href + '#' + fragment);
    } else {
      // Some browsers require that `hash` contains a leading #.
      location.hash = '#' + fragment;
    }
  }
});
/* harmony default export */ var src_history = (history_History);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsRegExp.js


/** `Object#toString` result references. */

var _baseIsRegExp_regexpTag = '[object RegExp]';
/**
 * The base implementation of `_.isRegExp` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
 */

function baseIsRegExp(value) {
  return lodash_es_isObjectLike(value) && _baseGetTag(value) == _baseIsRegExp_regexpTag;
}

/* harmony default export */ var _baseIsRegExp = (baseIsRegExp);
// CONCATENATED MODULE: ./node_modules/lodash-es/isRegExp.js



/* Node.js helper references. */

var nodeIsRegExp = _nodeUtil["a" /* default */] && _nodeUtil["a" /* default */].isRegExp;
/**
 * Checks if `value` is classified as a `RegExp` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
 * @example
 *
 * _.isRegExp(/abc/);
 * // => true
 *
 * _.isRegExp('/abc/');
 * // => false
 */

var isRegExp = nodeIsRegExp ? _baseUnary(nodeIsRegExp) : _baseIsRegExp;
/* harmony default export */ var lodash_es_isRegExp = (isRegExp);
// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/router.js
//     Backbone.js 1.4.0
//     (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
//     Backbone may be freely distributed under the MIT license.
// Router
// ------







 // Routers map faux-URLs to actions, and fire events when routes are
// matched. Creating a new one sets its `routes` hash, if not set statically.

const Router = function (options = {}) {
  this.history = options.history || new src_history();
  this.preinitialize.apply(this, arguments);
  if (options.routes) this.routes = options.routes;

  this._bindRoutes();

  this.initialize.apply(this, arguments);
};
Router.extend = inherits; // Cached regular expressions for matching named param parts and splatted
// parts of route strings.

const optionalParam = /\((.*?)\)/g;
const namedParam = /(\(\?)?:\w+/g;
const splatParam = /\*\w+/g;
const escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; // Set up all inheritable **Router** properties and methods.

Object.assign(Router.prototype, Events, {
  // preinitialize is an empty function by default. You can override it with a function
  // or object.  preinitialize will run before any instantiation logic is run in the Router.
  preinitialize: function () {},
  // Initialize is an empty function by default. Override it with your own
  // initialization logic.
  initialize: function () {},
  // Manually bind a single named route to a callback. For example:
  //
  //     this.route('search/:query/p:num', 'search', function(query, num) {
  //       ...
  //     });
  //
  route: function (route, name, callback) {
    if (!lodash_es_isRegExp(route)) route = this._routeToRegExp(route);

    if (lodash_es_isFunction(name)) {
      callback = name;
      name = '';
    }

    if (!callback) callback = this[name];
    this.history.route(route, fragment => {
      const args = this._extractParameters(route, fragment);

      if (this.execute(callback, args, name) !== false) {
        this.trigger.apply(this, ['route:' + name].concat(args));
        this.trigger('route', name, args);
        this.history.trigger('route', this, name, args);
      }
    });
    return this;
  },
  // Execute a route handler with the provided parameters.  This is an
  // excellent place to do pre-route setup or post-route cleanup.
  execute: function (callback, args, name) {
    if (callback) callback.apply(this, args);
  },
  // Simple proxy to `history` to save a fragment into the history.
  navigate: function (fragment, options) {
    this.history.navigate(fragment, options);
    return this;
  },
  // Bind all defined routes to `history`. We have to reverse the
  // order of the routes here to support behavior where the most general
  // routes can be defined at the bottom of the route map.
  _bindRoutes: function () {
    if (!this.routes) return;
    this.routes = lodash_es_result(this, 'routes');
    let route;
    const routes = lodash_es_keys(this.routes);

    while ((route = routes.pop()) != null) {
      this.route(route, this.routes[route]);
    }
  },
  // Convert a route string into a regular expression, suitable for matching
  // against the current location hash.
  _routeToRegExp: function (route) {
    route = route.replace(escapeRegExp, '\\$&').replace(optionalParam, '(?:$1)?').replace(namedParam, function (match, optional) {
      return optional ? match : '([^/?]+)';
    }).replace(splatParam, '([^?]*?)');
    return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
  },
  // Given a route, and a URL fragment that it matches, return the array of
  // extracted decoded parameters. Empty or unmatched parameters will be
  // treated as `null` to normalize cross-browser behavior.
  _extractParameters: function (route, fragment) {
    const params = route.exec(fragment).slice(1);
    return params.map(function (param, i) {
      // Don't decode the search params.
      if (i === params.length - 1) return param || null;
      return param ? decodeURIComponent(param) : null;
    });
  }
});
// EXTERNAL MODULE: ./node_modules/strophe.js/src/strophe.js
var strophe = __webpack_require__(1);

// CONCATENATED MODULE: ./node_modules/lodash-es/now.js

/**
 * Gets the timestamp of the number of milliseconds that have elapsed since
 * the Unix epoch (1 January 1970 00:00:00 UTC).
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Date
 * @returns {number} Returns the timestamp.
 * @example
 *
 * _.defer(function(stamp) {
 *   console.log(_.now() - stamp);
 * }, _.now());
 * // => Logs the number of milliseconds it took for the deferred invocation.
 */

var now_now = function () {
  return _root["a" /* default */].Date.now();
};

/* harmony default export */ var lodash_es_now = (now_now);
// CONCATENATED MODULE: ./node_modules/lodash-es/debounce.js



/** Error message constants. */

var debounce_FUNC_ERROR_TEXT = 'Expected a function';
/* Built-in method references for those with the same name as other `lodash` methods. */

var debounce_nativeMax = Math.max,
    debounce_nativeMin = Math.min;
/**
 * Creates a debounced function that delays invoking `func` until after `wait`
 * milliseconds have elapsed since the last time the debounced function was
 * invoked. The debounced function comes with a `cancel` method to cancel
 * delayed `func` invocations and a `flush` method to immediately invoke them.
 * Provide `options` to indicate whether `func` should be invoked on the
 * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
 * with the last arguments provided to the debounced function. Subsequent
 * calls to the debounced function return the result of the last `func`
 * invocation.
 *
 * **Note:** If `leading` and `trailing` options are `true`, `func` is
 * invoked on the trailing edge of the timeout only if the debounced function
 * is invoked more than once during the `wait` timeout.
 *
 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
 *
 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
 * for details over the differences between `_.debounce` and `_.throttle`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to debounce.
 * @param {number} [wait=0] The number of milliseconds to delay.
 * @param {Object} [options={}] The options object.
 * @param {boolean} [options.leading=false]
 *  Specify invoking on the leading edge of the timeout.
 * @param {number} [options.maxWait]
 *  The maximum time `func` is allowed to be delayed before it's invoked.
 * @param {boolean} [options.trailing=true]
 *  Specify invoking on the trailing edge of the timeout.
 * @returns {Function} Returns the new debounced function.
 * @example
 *
 * // Avoid costly calculations while the window size is in flux.
 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
 *
 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
 * jQuery(element).on('click', _.debounce(sendMail, 300, {
 *   'leading': true,
 *   'trailing': false
 * }));
 *
 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
 * var source = new EventSource('/stream');
 * jQuery(source).on('message', debounced);
 *
 * // Cancel the trailing debounced invocation.
 * jQuery(window).on('popstate', debounced.cancel);
 */

function debounce(func, wait, options) {
  var lastArgs,
      lastThis,
      maxWait,
      result,
      timerId,
      lastCallTime,
      lastInvokeTime = 0,
      leading = false,
      maxing = false,
      trailing = true;

  if (typeof func != 'function') {
    throw new TypeError(debounce_FUNC_ERROR_TEXT);
  }

  wait = lodash_es_toNumber(wait) || 0;

  if (lodash_es_isObject(options)) {
    leading = !!options.leading;
    maxing = 'maxWait' in options;
    maxWait = maxing ? debounce_nativeMax(lodash_es_toNumber(options.maxWait) || 0, wait) : maxWait;
    trailing = 'trailing' in options ? !!options.trailing : trailing;
  }

  function invokeFunc(time) {
    var args = lastArgs,
        thisArg = lastThis;
    lastArgs = lastThis = undefined;
    lastInvokeTime = time;
    result = func.apply(thisArg, args);
    return result;
  }

  function leadingEdge(time) {
    // Reset any `maxWait` timer.
    lastInvokeTime = time; // Start the timer for the trailing edge.

    timerId = setTimeout(timerExpired, wait); // Invoke the leading edge.

    return leading ? invokeFunc(time) : result;
  }

  function remainingWait(time) {
    var timeSinceLastCall = time - lastCallTime,
        timeSinceLastInvoke = time - lastInvokeTime,
        timeWaiting = wait - timeSinceLastCall;
    return maxing ? debounce_nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
  }

  function shouldInvoke(time) {
    var timeSinceLastCall = time - lastCallTime,
        timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the
    // trailing edge, the system time has gone backwards and we're treating
    // it as the trailing edge, or we've hit the `maxWait` limit.

    return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
  }

  function timerExpired() {
    var time = lodash_es_now();

    if (shouldInvoke(time)) {
      return trailingEdge(time);
    } // Restart the timer.


    timerId = setTimeout(timerExpired, remainingWait(time));
  }

  function trailingEdge(time) {
    timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been
    // debounced at least once.

    if (trailing && lastArgs) {
      return invokeFunc(time);
    }

    lastArgs = lastThis = undefined;
    return result;
  }

  function cancel() {
    if (timerId !== undefined) {
      clearTimeout(timerId);
    }

    lastInvokeTime = 0;
    lastArgs = lastCallTime = lastThis = timerId = undefined;
  }

  function flush() {
    return timerId === undefined ? result : trailingEdge(lodash_es_now());
  }

  function debounced() {
    var time = lodash_es_now(),
        isInvoking = shouldInvoke(time);
    lastArgs = arguments;
    lastThis = this;
    lastCallTime = time;

    if (isInvoking) {
      if (timerId === undefined) {
        return leadingEdge(lastCallTime);
      }

      if (maxing) {
        // Handle invocations in a tight loop.
        clearTimeout(timerId);
        timerId = setTimeout(timerExpired, wait);
        return invokeFunc(lastCallTime);
      }
    }

    if (timerId === undefined) {
      timerId = setTimeout(timerExpired, wait);
    }

    return result;
  }

  debounced.cancel = cancel;
  debounced.flush = flush;
  return debounced;
}

/* harmony default export */ var lodash_es_debounce = (debounce);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseInvoke.js





/**
 * The base implementation of `_.invoke` without support for individual
 * method arguments.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the method to invoke.
 * @param {Array} args The arguments to invoke the method with.
 * @returns {*} Returns the result of the invoked method.
 */

function baseInvoke(object, path, args) {
  path = _castPath(path, object);
  object = _parent(object, path);
  var func = object == null ? object : object[_toKey(lodash_es_last(path))];
  return func == null ? undefined : _apply(func, object, args);
}

/* harmony default export */ var _baseInvoke = (baseInvoke);
// CONCATENATED MODULE: ./node_modules/lodash-es/invoke.js


/**
 * Invokes the method at `path` of `object`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the method to invoke.
 * @param {...*} [args] The arguments to invoke the method with.
 * @returns {*} Returns the result of the invoked method.
 * @example
 *
 * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
 *
 * _.invoke(object, 'a[0].b.c.slice', 1, 3);
 * // => [2, 3]
 */

var invoke = _baseRest(_baseInvoke);
/* harmony default export */ var lodash_es_invoke = (invoke);
// CONCATENATED MODULE: ./node_modules/lit-html/lib/dom.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */

/**
 * True if the custom elements polyfill is in use.
 */
const isCEPolyfill = typeof window !== 'undefined' && window.customElements != null && window.customElements.polyfillWrapFlushCallback !== undefined;
/**
 * Reparents nodes, starting from `start` (inclusive) to `end` (exclusive),
 * into another container (could be the same container), before `before`. If
 * `before` is null, it appends the nodes to the container.
 */

const reparentNodes = (container, start, end = null, before = null) => {
  while (start !== end) {
    const n = start.nextSibling;
    container.insertBefore(start, before);
    start = n;
  }
};
/**
 * Removes nodes, starting from `start` (inclusive) to `end` (exclusive), from
 * `container`.
 */

const removeNodes = (container, start, end = null) => {
  while (start !== end) {
    const n = start.nextSibling;
    container.removeChild(start);
    start = n;
  }
};
// CONCATENATED MODULE: ./node_modules/lit-html/lib/template.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */

/**
 * An expression marker with embedded unique key to avoid collision with
 * possible text in templates.
 */
const template_marker = `{{lit-${String(Math.random()).slice(2)}}}`;
/**
 * An expression marker used text-positions, multi-binding attributes, and
 * attributes with markup-like text values.
 */

const nodeMarker = `<!--${template_marker}-->`;
const markerRegex = new RegExp(`${template_marker}|${nodeMarker}`);
/**
 * Suffix appended to all bound attribute names.
 */

const boundAttributeSuffix = '$lit$';
/**
 * An updatable Template that tracks the location of dynamic parts.
 */

class Template {
  constructor(result, element) {
    this.parts = [];
    this.element = element;
    const nodesToRemove = [];
    const stack = []; // Edge needs all 4 parameters present; IE11 needs 3rd parameter to be null

    const walker = document.createTreeWalker(element.content, 133
    /* NodeFilter.SHOW_{ELEMENT|COMMENT|TEXT} */
    , null, false); // Keeps track of the last index associated with a part. We try to delete
    // unnecessary nodes, but we never want to associate two different parts
    // to the same index. They must have a constant node between.

    let lastPartIndex = 0;
    let index = -1;
    let partIndex = 0;
    const {
      strings,
      values: {
        length
      }
    } = result;

    while (partIndex < length) {
      const node = walker.nextNode();

      if (node === null) {
        // We've exhausted the content inside a nested template element.
        // Because we still have parts (the outer for-loop), we know:
        // - There is a template in the stack
        // - The walker will find a nextNode outside the template
        walker.currentNode = stack.pop();
        continue;
      }

      index++;

      if (node.nodeType === 1
      /* Node.ELEMENT_NODE */
      ) {
          if (node.hasAttributes()) {
            const attributes = node.attributes;
            const {
              length
            } = attributes; // Per
            // https://developer.mozilla.org/en-US/docs/Web/API/NamedNodeMap,
            // attributes are not guaranteed to be returned in document order.
            // In particular, Edge/IE can return them out of order, so we cannot
            // assume a correspondence between part index and attribute index.

            let count = 0;

            for (let i = 0; i < length; i++) {
              if (endsWith(attributes[i].name, boundAttributeSuffix)) {
                count++;
              }
            }

            while (count-- > 0) {
              // Get the template literal section leading up to the first
              // expression in this attribute
              const stringForPart = strings[partIndex]; // Find the attribute name

              const name = lastAttributeNameRegex.exec(stringForPart)[2]; // Find the corresponding attribute
              // All bound attributes have had a suffix added in
              // TemplateResult#getHTML to opt out of special attribute
              // handling. To look up the attribute value we also need to add
              // the suffix.

              const attributeLookupName = name.toLowerCase() + boundAttributeSuffix;
              const attributeValue = node.getAttribute(attributeLookupName);
              node.removeAttribute(attributeLookupName);
              const statics = attributeValue.split(markerRegex);
              this.parts.push({
                type: 'attribute',
                index,
                name,
                strings: statics
              });
              partIndex += statics.length - 1;
            }
          }

          if (node.tagName === 'TEMPLATE') {
            stack.push(node);
            walker.currentNode = node.content;
          }
        } else if (node.nodeType === 3
      /* Node.TEXT_NODE */
      ) {
          const data = node.data;

          if (data.indexOf(template_marker) >= 0) {
            const parent = node.parentNode;
            const strings = data.split(markerRegex);
            const lastIndex = strings.length - 1; // Generate a new text node for each literal section
            // These nodes are also used as the markers for node parts

            for (let i = 0; i < lastIndex; i++) {
              let insert;
              let s = strings[i];

              if (s === '') {
                insert = createMarker();
              } else {
                const match = lastAttributeNameRegex.exec(s);

                if (match !== null && endsWith(match[2], boundAttributeSuffix)) {
                  s = s.slice(0, match.index) + match[1] + match[2].slice(0, -boundAttributeSuffix.length) + match[3];
                }

                insert = document.createTextNode(s);
              }

              parent.insertBefore(insert, node);
              this.parts.push({
                type: 'node',
                index: ++index
              });
            } // If there's no text, we must insert a comment to mark our place.
            // Else, we can trust it will stick around after cloning.


            if (strings[lastIndex] === '') {
              parent.insertBefore(createMarker(), node);
              nodesToRemove.push(node);
            } else {
              node.data = strings[lastIndex];
            } // We have a part for each match found


            partIndex += lastIndex;
          }
        } else if (node.nodeType === 8
      /* Node.COMMENT_NODE */
      ) {
          if (node.data === template_marker) {
            const parent = node.parentNode; // Add a new marker node to be the startNode of the Part if any of
            // the following are true:
            //  * We don't have a previousSibling
            //  * The previousSibling is already the start of a previous part

            if (node.previousSibling === null || index === lastPartIndex) {
              index++;
              parent.insertBefore(createMarker(), node);
            }

            lastPartIndex = index;
            this.parts.push({
              type: 'node',
              index
            }); // If we don't have a nextSibling, keep this node so we have an end.
            // Else, we can remove it to save future costs.

            if (node.nextSibling === null) {
              node.data = '';
            } else {
              nodesToRemove.push(node);
              index--;
            }

            partIndex++;
          } else {
            let i = -1;

            while ((i = node.data.indexOf(template_marker, i + 1)) !== -1) {
              // Comment node has a binding marker inside, make an inactive part
              // The binding won't work, but subsequent bindings will
              // TODO (justinfagnani): consider whether it's even worth it to
              // make bindings in comments work
              this.parts.push({
                type: 'node',
                index: -1
              });
              partIndex++;
            }
          }
        }
    } // Remove text binding nodes after the walk to not disturb the TreeWalker


    for (const n of nodesToRemove) {
      n.parentNode.removeChild(n);
    }
  }

}

const endsWith = (str, suffix) => {
  const index = str.length - suffix.length;
  return index >= 0 && str.slice(index) === suffix;
};

const isTemplatePartActive = part => part.index !== -1; // Allows `document.createComment('')` to be renamed for a
// small manual size-savings.

const createMarker = () => document.createComment('');
/**
 * This regex extracts the attribute name preceding an attribute-position
 * expression. It does this by matching the syntax allowed for attributes
 * against the string literal directly preceding the expression, assuming that
 * the expression is in an attribute-value position.
 *
 * See attributes in the HTML spec:
 * https://www.w3.org/TR/html5/syntax.html#elements-attributes
 *
 * " \x09\x0a\x0c\x0d" are HTML space characters:
 * https://www.w3.org/TR/html5/infrastructure.html#space-characters
 *
 * "\0-\x1F\x7F-\x9F" are Unicode control characters, which includes every
 * space character except " ".
 *
 * So an attribute is:
 *  * The name: any character except a control character, space character, ('),
 *    ("), ">", "=", or "/"
 *  * Followed by zero or more space characters
 *  * Followed by "="
 *  * Followed by zero or more space characters
 *  * Followed by:
 *    * Any character except space, ('), ("), "<", ">", "=", (`), or
 *    * (") then any non-("), or
 *    * (') then any non-(')
 */

const lastAttributeNameRegex = // eslint-disable-next-line no-control-regex
/([ \x09\x0a\x0c\x0d])([^\0-\x1F\x7F-\x9F "'>=/]+)([ \x09\x0a\x0c\x0d]*=[ \x09\x0a\x0c\x0d]*(?:[^ \x09\x0a\x0c\x0d"'`<>=]*|"[^"]*|'[^']*))$/;
// CONCATENATED MODULE: ./node_modules/lit-html/lib/modify-template.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */

const walkerNodeFilter = 133
/* NodeFilter.SHOW_{ELEMENT|COMMENT|TEXT} */
;
/**
 * Removes the list of nodes from a Template safely. In addition to removing
 * nodes from the Template, the Template part indices are updated to match
 * the mutated Template DOM.
 *
 * As the template is walked the removal state is tracked and
 * part indices are adjusted as needed.
 *
 * div
 *   div#1 (remove) <-- start removing (removing node is div#1)
 *     div
 *       div#2 (remove)  <-- continue removing (removing node is still div#1)
 *         div
 * div <-- stop removing since previous sibling is the removing node (div#1,
 * removed 4 nodes)
 */

function removeNodesFromTemplate(template, nodesToRemove) {
  const {
    element: {
      content
    },
    parts
  } = template;
  const walker = document.createTreeWalker(content, walkerNodeFilter, null, false);
  let partIndex = nextActiveIndexInTemplateParts(parts);
  let part = parts[partIndex];
  let nodeIndex = -1;
  let removeCount = 0;
  const nodesToRemoveInTemplate = [];
  let currentRemovingNode = null;

  while (walker.nextNode()) {
    nodeIndex++;
    const node = walker.currentNode; // End removal if stepped past the removing node

    if (node.previousSibling === currentRemovingNode) {
      currentRemovingNode = null;
    } // A node to remove was found in the template


    if (nodesToRemove.has(node)) {
      nodesToRemoveInTemplate.push(node); // Track node we're removing

      if (currentRemovingNode === null) {
        currentRemovingNode = node;
      }
    } // When removing, increment count by which to adjust subsequent part indices


    if (currentRemovingNode !== null) {
      removeCount++;
    }

    while (part !== undefined && part.index === nodeIndex) {
      // If part is in a removed node deactivate it by setting index to -1 or
      // adjust the index as needed.
      part.index = currentRemovingNode !== null ? -1 : part.index - removeCount; // go to the next active part.

      partIndex = nextActiveIndexInTemplateParts(parts, partIndex);
      part = parts[partIndex];
    }
  }

  nodesToRemoveInTemplate.forEach(n => n.parentNode.removeChild(n));
}

const countNodes = node => {
  let count = node.nodeType === 11
  /* Node.DOCUMENT_FRAGMENT_NODE */
  ? 0 : 1;
  const walker = document.createTreeWalker(node, walkerNodeFilter, null, false);

  while (walker.nextNode()) {
    count++;
  }

  return count;
};

const nextActiveIndexInTemplateParts = (parts, startIndex = -1) => {
  for (let i = startIndex + 1; i < parts.length; i++) {
    const part = parts[i];

    if (isTemplatePartActive(part)) {
      return i;
    }
  }

  return -1;
};
/**
 * Inserts the given node into the Template, optionally before the given
 * refNode. In addition to inserting the node into the Template, the Template
 * part indices are updated to match the mutated Template DOM.
 */


function insertNodeIntoTemplate(template, node, refNode = null) {
  const {
    element: {
      content
    },
    parts
  } = template; // If there's no refNode, then put node at end of template.
  // No part indices need to be shifted in this case.

  if (refNode === null || refNode === undefined) {
    content.appendChild(node);
    return;
  }

  const walker = document.createTreeWalker(content, walkerNodeFilter, null, false);
  let partIndex = nextActiveIndexInTemplateParts(parts);
  let insertCount = 0;
  let walkerIndex = -1;

  while (walker.nextNode()) {
    walkerIndex++;
    const walkerNode = walker.currentNode;

    if (walkerNode === refNode) {
      insertCount = countNodes(node);
      refNode.parentNode.insertBefore(node, refNode);
    }

    while (partIndex !== -1 && parts[partIndex].index === walkerIndex) {
      // If we've inserted the node, simply adjust all subsequent parts
      if (insertCount > 0) {
        while (partIndex !== -1) {
          parts[partIndex].index += insertCount;
          partIndex = nextActiveIndexInTemplateParts(parts, partIndex);
        }

        return;
      }

      partIndex = nextActiveIndexInTemplateParts(parts, partIndex);
    }
  }
}
// CONCATENATED MODULE: ./node_modules/lit-html/lib/directive.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */
const directives = new WeakMap();
/**
 * Brands a function as a directive factory function so that lit-html will call
 * the function during template rendering, rather than passing as a value.
 *
 * A _directive_ is a function that takes a Part as an argument. It has the
 * signature: `(part: Part) => void`.
 *
 * A directive _factory_ is a function that takes arguments for data and
 * configuration and returns a directive. Users of directive usually refer to
 * the directive factory as the directive. For example, "The repeat directive".
 *
 * Usually a template author will invoke a directive factory in their template
 * with relevant arguments, which will then return a directive function.
 *
 * Here's an example of using the `repeat()` directive factory that takes an
 * array and a function to render an item:
 *
 * ```js
 * html`<ul><${repeat(items, (item) => html`<li>${item}</li>`)}</ul>`
 * ```
 *
 * When `repeat` is invoked, it returns a directive function that closes over
 * `items` and the template function. When the outer template is rendered, the
 * return directive function is called with the Part for the expression.
 * `repeat` then performs it's custom logic to render multiple items.
 *
 * @param f The directive factory function. Must be a function that returns a
 * function of the signature `(part: Part) => void`. The returned function will
 * be called with the part object.
 *
 * @example
 *
 * import {directive, html} from 'lit-html';
 *
 * const immutable = directive((v) => (part) => {
 *   if (part.value !== v) {
 *     part.setValue(v)
 *   }
 * });
 */

const directive_directive = f => (...args) => {
  const d = f(...args);
  directives.set(d, true);
  return d;
};
const isDirective = o => {
  return typeof o === 'function' && directives.has(o);
};
// CONCATENATED MODULE: ./node_modules/lit-html/lib/part.js
/**
 * @license
 * Copyright (c) 2018 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */

/**
 * A sentinel value that signals that a value was handled by a directive and
 * should not be written to the DOM.
 */
const noChange = {};
/**
 * A sentinel value that signals a NodePart to fully clear its content.
 */

const nothing = {};
// CONCATENATED MODULE: ./node_modules/lit-html/lib/template-instance.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */


/**
 * An instance of a `Template` that can be attached to the DOM and updated
 * with new values.
 */

class template_instance_TemplateInstance {
  constructor(template, processor, options) {
    this.__parts = [];
    this.template = template;
    this.processor = processor;
    this.options = options;
  }

  update(values) {
    let i = 0;

    for (const part of this.__parts) {
      if (part !== undefined) {
        part.setValue(values[i]);
      }

      i++;
    }

    for (const part of this.__parts) {
      if (part !== undefined) {
        part.commit();
      }
    }
  }

  _clone() {
    // There are a number of steps in the lifecycle of a template instance's
    // DOM fragment:
    //  1. Clone - create the instance fragment
    //  2. Adopt - adopt into the main document
    //  3. Process - find part markers and create parts
    //  4. Upgrade - upgrade custom elements
    //  5. Update - set node, attribute, property, etc., values
    //  6. Connect - connect to the document. Optional and outside of this
    //     method.
    //
    // We have a few constraints on the ordering of these steps:
    //  * We need to upgrade before updating, so that property values will pass
    //    through any property setters.
    //  * We would like to process before upgrading so that we're sure that the
    //    cloned fragment is inert and not disturbed by self-modifying DOM.
    //  * We want custom elements to upgrade even in disconnected fragments.
    //
    // Given these constraints, with full custom elements support we would
    // prefer the order: Clone, Process, Adopt, Upgrade, Update, Connect
    //
    // But Safari does not implement CustomElementRegistry#upgrade, so we
    // can not implement that order and still have upgrade-before-update and
    // upgrade disconnected fragments. So we instead sacrifice the
    // process-before-upgrade constraint, since in Custom Elements v1 elements
    // must not modify their light DOM in the constructor. We still have issues
    // when co-existing with CEv0 elements like Polymer 1, and with polyfills
    // that don't strictly adhere to the no-modification rule because shadow
    // DOM, which may be created in the constructor, is emulated by being placed
    // in the light DOM.
    //
    // The resulting order is on native is: Clone, Adopt, Upgrade, Process,
    // Update, Connect. document.importNode() performs Clone, Adopt, and Upgrade
    // in one step.
    //
    // The Custom Elements v1 polyfill supports upgrade(), so the order when
    // polyfilled is the more ideal: Clone, Process, Adopt, Upgrade, Update,
    // Connect.
    const fragment = isCEPolyfill ? this.template.element.content.cloneNode(true) : document.importNode(this.template.element.content, true);
    const stack = [];
    const parts = this.template.parts; // Edge needs all 4 parameters present; IE11 needs 3rd parameter to be null

    const walker = document.createTreeWalker(fragment, 133
    /* NodeFilter.SHOW_{ELEMENT|COMMENT|TEXT} */
    , null, false);
    let partIndex = 0;
    let nodeIndex = 0;
    let part;
    let node = walker.nextNode(); // Loop through all the nodes and parts of a template

    while (partIndex < parts.length) {
      part = parts[partIndex];

      if (!isTemplatePartActive(part)) {
        this.__parts.push(undefined);

        partIndex++;
        continue;
      } // Progress the tree walker until we find our next part's node.
      // Note that multiple parts may share the same node (attribute parts
      // on a single element), so this loop may not run at all.


      while (nodeIndex < part.index) {
        nodeIndex++;

        if (node.nodeName === 'TEMPLATE') {
          stack.push(node);
          walker.currentNode = node.content;
        }

        if ((node = walker.nextNode()) === null) {
          // We've exhausted the content inside a nested template element.
          // Because we still have parts (the outer for-loop), we know:
          // - There is a template in the stack
          // - The walker will find a nextNode outside the template
          walker.currentNode = stack.pop();
          node = walker.nextNode();
        }
      } // We've arrived at our part's node.


      if (part.type === 'node') {
        const part = this.processor.handleTextExpression(this.options);
        part.insertAfterNode(node.previousSibling);

        this.__parts.push(part);
      } else {
        this.__parts.push(...this.processor.handleAttributeExpressions(node, part.name, part.strings, this.options));
      }

      partIndex++;
    }

    if (isCEPolyfill) {
      document.adoptNode(fragment);
      customElements.upgrade(fragment);
    }

    return fragment;
  }

}
// CONCATENATED MODULE: ./node_modules/lit-html/lib/template-result.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */

/**
 * @module lit-html
 */


/**
 * Our TrustedTypePolicy for HTML which is declared using the html template
 * tag function.
 *
 * That HTML is a developer-authored constant, and is parsed with innerHTML
 * before any untrusted expressions have been mixed in. Therefor it is
 * considered safe by construction.
 */

const policy = window.trustedTypes && trustedTypes.createPolicy('lit-html', {
  createHTML: s => s
});
const commentMarker = ` ${template_marker} `;
/**
 * The return type of `html`, which holds a Template and the values from
 * interpolated expressions.
 */

class template_result_TemplateResult {
  constructor(strings, values, type, processor) {
    this.strings = strings;
    this.values = values;
    this.type = type;
    this.processor = processor;
  }
  /**
   * Returns a string of HTML used to create a `<template>` element.
   */


  getHTML() {
    const l = this.strings.length - 1;
    let html = '';
    let isCommentBinding = false;

    for (let i = 0; i < l; i++) {
      const s = this.strings[i]; // For each binding we want to determine the kind of marker to insert
      // into the template source before it's parsed by the browser's HTML
      // parser. The marker type is based on whether the expression is in an
      // attribute, text, or comment position.
      //   * For node-position bindings we insert a comment with the marker
      //     sentinel as its text content, like <!--{{lit-guid}}-->.
      //   * For attribute bindings we insert just the marker sentinel for the
      //     first binding, so that we support unquoted attribute bindings.
      //     Subsequent bindings can use a comment marker because multi-binding
      //     attributes must be quoted.
      //   * For comment bindings we insert just the marker sentinel so we don't
      //     close the comment.
      //
      // The following code scans the template source, but is *not* an HTML
      // parser. We don't need to track the tree structure of the HTML, only
      // whether a binding is inside a comment, and if not, if it appears to be
      // the first binding in an attribute.

      const commentOpen = s.lastIndexOf('<!--'); // We're in comment position if we have a comment open with no following
      // comment close. Because <-- can appear in an attribute value there can
      // be false positives.

      isCommentBinding = (commentOpen > -1 || isCommentBinding) && s.indexOf('-->', commentOpen + 1) === -1; // Check to see if we have an attribute-like sequence preceding the
      // expression. This can match "name=value" like structures in text,
      // comments, and attribute values, so there can be false-positives.

      const attributeMatch = lastAttributeNameRegex.exec(s);

      if (attributeMatch === null) {
        // We're only in this branch if we don't have a attribute-like
        // preceding sequence. For comments, this guards against unusual
        // attribute values like <div foo="<!--${'bar'}">. Cases like
        // <!-- foo=${'bar'}--> are handled correctly in the attribute branch
        // below.
        html += s + (isCommentBinding ? commentMarker : nodeMarker);
      } else {
        // For attributes we use just a marker sentinel, and also append a
        // $lit$ suffix to the name to opt-out of attribute-specific parsing
        // that IE and Edge do for style and certain SVG attributes.
        html += s.substr(0, attributeMatch.index) + attributeMatch[1] + attributeMatch[2] + boundAttributeSuffix + attributeMatch[3] + template_marker;
      }
    }

    html += this.strings[l];
    return html;
  }

  getTemplateElement() {
    const template = document.createElement('template');
    let value = this.getHTML();

    if (policy !== undefined) {
      // this is secure because `this.strings` is a TemplateStringsArray.
      // TODO: validate this when
      // https://github.com/tc39/proposal-array-is-template-object is
      // implemented.
      value = policy.createHTML(value);
    }

    template.innerHTML = value;
    return template;
  }

}
/**
 * A TemplateResult for SVG fragments.
 *
 * This class wraps HTML in an `<svg>` tag in order to parse its contents in the
 * SVG namespace, then modifies the template to remove the `<svg>` tag so that
 * clones only container the original fragment.
 */

class template_result_SVGTemplateResult extends template_result_TemplateResult {
  getHTML() {
    return `<svg>${super.getHTML()}</svg>`;
  }

  getTemplateElement() {
    const template = super.getTemplateElement();
    const content = template.content;
    const svgElement = content.firstChild;
    content.removeChild(svgElement);
    reparentNodes(content, svgElement.firstChild);
    return template;
  }

}
// CONCATENATED MODULE: ./node_modules/lit-html/lib/parts.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */






const isPrimitive = value => {
  return value === null || !(typeof value === 'object' || typeof value === 'function');
};
const isIterable = value => {
  return Array.isArray(value) || // eslint-disable-next-line @typescript-eslint/no-explicit-any
  !!(value && value[Symbol.iterator]);
};
/**
 * Writes attribute values to the DOM for a group of AttributeParts bound to a
 * single attribute. The value is only set once even if there are multiple parts
 * for an attribute.
 */

class AttributeCommitter {
  constructor(element, name, strings) {
    this.dirty = true;
    this.element = element;
    this.name = name;
    this.strings = strings;
    this.parts = [];

    for (let i = 0; i < strings.length - 1; i++) {
      this.parts[i] = this._createPart();
    }
  }
  /**
   * Creates a single part. Override this to create a differnt type of part.
   */


  _createPart() {
    return new parts_AttributePart(this);
  }

  _getValue() {
    const strings = this.strings;
    const l = strings.length - 1;
    const parts = this.parts; // If we're assigning an attribute via syntax like:
    //    attr="${foo}"  or  attr=${foo}
    // but not
    //    attr="${foo} ${bar}" or attr="${foo} baz"
    // then we don't want to coerce the attribute value into one long
    // string. Instead we want to just return the value itself directly,
    // so that sanitizeDOMValue can get the actual value rather than
    // String(value)
    // The exception is if v is an array, in which case we do want to smash
    // it together into a string without calling String() on the array.
    //
    // This also allows trusted values (when using TrustedTypes) being
    // assigned to DOM sinks without being stringified in the process.

    if (l === 1 && strings[0] === '' && strings[1] === '') {
      const v = parts[0].value;

      if (typeof v === 'symbol') {
        return String(v);
      }

      if (typeof v === 'string' || !isIterable(v)) {
        return v;
      }
    }

    let text = '';

    for (let i = 0; i < l; i++) {
      text += strings[i];
      const part = parts[i];

      if (part !== undefined) {
        const v = part.value;

        if (isPrimitive(v) || !isIterable(v)) {
          text += typeof v === 'string' ? v : String(v);
        } else {
          for (const t of v) {
            text += typeof t === 'string' ? t : String(t);
          }
        }
      }
    }

    text += strings[l];
    return text;
  }

  commit() {
    if (this.dirty) {
      this.dirty = false;
      this.element.setAttribute(this.name, this._getValue());
    }
  }

}
/**
 * A Part that controls all or part of an attribute value.
 */

class parts_AttributePart {
  constructor(committer) {
    this.value = undefined;
    this.committer = committer;
  }

  setValue(value) {
    if (value !== noChange && (!isPrimitive(value) || value !== this.value)) {
      this.value = value; // If the value is a not a directive, dirty the committer so that it'll
      // call setAttribute. If the value is a directive, it'll dirty the
      // committer if it calls setValue().

      if (!isDirective(value)) {
        this.committer.dirty = true;
      }
    }
  }

  commit() {
    while (isDirective(this.value)) {
      const directive = this.value;
      this.value = noChange;
      directive(this);
    }

    if (this.value === noChange) {
      return;
    }

    this.committer.commit();
  }

}
/**
 * A Part that controls a location within a Node tree. Like a Range, NodePart
 * has start and end locations and can set and update the Nodes between those
 * locations.
 *
 * NodeParts support several value types: primitives, Nodes, TemplateResults,
 * as well as arrays and iterables of those types.
 */

class parts_NodePart {
  constructor(options) {
    this.value = undefined;
    this.__pendingValue = undefined;
    this.options = options;
  }
  /**
   * Appends this part into a container.
   *
   * This part must be empty, as its contents are not automatically moved.
   */


  appendInto(container) {
    this.startNode = container.appendChild(createMarker());
    this.endNode = container.appendChild(createMarker());
  }
  /**
   * Inserts this part after the `ref` node (between `ref` and `ref`'s next
   * sibling). Both `ref` and its next sibling must be static, unchanging nodes
   * such as those that appear in a literal section of a template.
   *
   * This part must be empty, as its contents are not automatically moved.
   */


  insertAfterNode(ref) {
    this.startNode = ref;
    this.endNode = ref.nextSibling;
  }
  /**
   * Appends this part into a parent part.
   *
   * This part must be empty, as its contents are not automatically moved.
   */


  appendIntoPart(part) {
    part.__insert(this.startNode = createMarker());

    part.__insert(this.endNode = createMarker());
  }
  /**
   * Inserts this part after the `ref` part.
   *
   * This part must be empty, as its contents are not automatically moved.
   */


  insertAfterPart(ref) {
    ref.__insert(this.startNode = createMarker());

    this.endNode = ref.endNode;
    ref.endNode = this.startNode;
  }

  setValue(value) {
    this.__pendingValue = value;
  }

  commit() {
    if (this.startNode.parentNode === null) {
      return;
    }

    while (isDirective(this.__pendingValue)) {
      const directive = this.__pendingValue;
      this.__pendingValue = noChange;
      directive(this);
    }

    const value = this.__pendingValue;

    if (value === noChange) {
      return;
    }

    if (isPrimitive(value)) {
      if (value !== this.value) {
        this.__commitText(value);
      }
    } else if (value instanceof template_result_TemplateResult) {
      this.__commitTemplateResult(value);
    } else if (value instanceof Node) {
      this.__commitNode(value);
    } else if (isIterable(value)) {
      this.__commitIterable(value);
    } else if (value === nothing) {
      this.value = nothing;
      this.clear();
    } else {
      // Fallback, will render the string representation
      this.__commitText(value);
    }
  }

  __insert(node) {
    this.endNode.parentNode.insertBefore(node, this.endNode);
  }

  __commitNode(value) {
    if (this.value === value) {
      return;
    }

    this.clear();

    this.__insert(value);

    this.value = value;
  }

  __commitText(value) {
    const node = this.startNode.nextSibling;
    value = value == null ? '' : value; // If `value` isn't already a string, we explicitly convert it here in case
    // it can't be implicitly converted - i.e. it's a symbol.

    const valueAsString = typeof value === 'string' ? value : String(value);

    if (node === this.endNode.previousSibling && node.nodeType === 3
    /* Node.TEXT_NODE */
    ) {
        // If we only have a single text node between the markers, we can just
        // set its value, rather than replacing it.
        // TODO(justinfagnani): Can we just check if this.value is primitive?
        node.data = valueAsString;
      } else {
      this.__commitNode(document.createTextNode(valueAsString));
    }

    this.value = value;
  }

  __commitTemplateResult(value) {
    const template = this.options.templateFactory(value);

    if (this.value instanceof template_instance_TemplateInstance && this.value.template === template) {
      this.value.update(value.values);
    } else {
      // Make sure we propagate the template processor from the TemplateResult
      // so that we use its syntax extension, etc. The template factory comes
      // from the render function options so that it can control template
      // caching and preprocessing.
      const instance = new template_instance_TemplateInstance(template, value.processor, this.options);

      const fragment = instance._clone();

      instance.update(value.values);

      this.__commitNode(fragment);

      this.value = instance;
    }
  }

  __commitIterable(value) {
    // For an Iterable, we create a new InstancePart per item, then set its
    // value to the item. This is a little bit of overhead for every item in
    // an Iterable, but it lets us recurse easily and efficiently update Arrays
    // of TemplateResults that will be commonly returned from expressions like:
    // array.map((i) => html`${i}`), by reusing existing TemplateInstances.
    // If _value is an array, then the previous render was of an
    // iterable and _value will contain the NodeParts from the previous
    // render. If _value is not an array, clear this part and make a new
    // array for NodeParts.
    if (!Array.isArray(this.value)) {
      this.value = [];
      this.clear();
    } // Lets us keep track of how many items we stamped so we can clear leftover
    // items from a previous render


    const itemParts = this.value;
    let partIndex = 0;
    let itemPart;

    for (const item of value) {
      // Try to reuse an existing part
      itemPart = itemParts[partIndex]; // If no existing part, create a new one

      if (itemPart === undefined) {
        itemPart = new parts_NodePart(this.options);
        itemParts.push(itemPart);

        if (partIndex === 0) {
          itemPart.appendIntoPart(this);
        } else {
          itemPart.insertAfterPart(itemParts[partIndex - 1]);
        }
      }

      itemPart.setValue(item);
      itemPart.commit();
      partIndex++;
    }

    if (partIndex < itemParts.length) {
      // Truncate the parts array so _value reflects the current state
      itemParts.length = partIndex;
      this.clear(itemPart && itemPart.endNode);
    }
  }

  clear(startNode = this.startNode) {
    removeNodes(this.startNode.parentNode, startNode.nextSibling, this.endNode);
  }

}
/**
 * Implements a boolean attribute, roughly as defined in the HTML
 * specification.
 *
 * If the value is truthy, then the attribute is present with a value of
 * ''. If the value is falsey, the attribute is removed.
 */

class parts_BooleanAttributePart {
  constructor(element, name, strings) {
    this.value = undefined;
    this.__pendingValue = undefined;

    if (strings.length !== 2 || strings[0] !== '' || strings[1] !== '') {
      throw new Error('Boolean attributes can only contain a single expression');
    }

    this.element = element;
    this.name = name;
    this.strings = strings;
  }

  setValue(value) {
    this.__pendingValue = value;
  }

  commit() {
    while (isDirective(this.__pendingValue)) {
      const directive = this.__pendingValue;
      this.__pendingValue = noChange;
      directive(this);
    }

    if (this.__pendingValue === noChange) {
      return;
    }

    const value = !!this.__pendingValue;

    if (this.value !== value) {
      if (value) {
        this.element.setAttribute(this.name, '');
      } else {
        this.element.removeAttribute(this.name);
      }

      this.value = value;
    }

    this.__pendingValue = noChange;
  }

}
/**
 * Sets attribute values for PropertyParts, so that the value is only set once
 * even if there are multiple parts for a property.
 *
 * If an expression controls the whole property value, then the value is simply
 * assigned to the property under control. If there are string literals or
 * multiple expressions, then the strings are expressions are interpolated into
 * a string first.
 */

class PropertyCommitter extends AttributeCommitter {
  constructor(element, name, strings) {
    super(element, name, strings);
    this.single = strings.length === 2 && strings[0] === '' && strings[1] === '';
  }

  _createPart() {
    return new PropertyPart(this);
  }

  _getValue() {
    if (this.single) {
      return this.parts[0].value;
    }

    return super._getValue();
  }

  commit() {
    if (this.dirty) {
      this.dirty = false; // eslint-disable-next-line @typescript-eslint/no-explicit-any

      this.element[this.name] = this._getValue();
    }
  }

}
class PropertyPart extends parts_AttributePart {} // Detect event listener options support. If the `capture` property is read
// from the options object, then options are supported. If not, then the third
// argument to add/removeEventListener is interpreted as the boolean capture
// value so we should only pass the `capture` property.

let eventOptionsSupported = false; // Wrap into an IIFE because MS Edge <= v41 does not support having try/catch
// blocks right into the body of a module

(() => {
  try {
    const options = {
      get capture() {
        eventOptionsSupported = true;
        return false;
      }

    }; // eslint-disable-next-line @typescript-eslint/no-explicit-any

    window.addEventListener('test', options, options); // eslint-disable-next-line @typescript-eslint/no-explicit-any

    window.removeEventListener('test', options, options);
  } catch (_e) {// event options not supported
  }
})();

class parts_EventPart {
  constructor(element, eventName, eventContext) {
    this.value = undefined;
    this.__pendingValue = undefined;
    this.element = element;
    this.eventName = eventName;
    this.eventContext = eventContext;

    this.__boundHandleEvent = e => this.handleEvent(e);
  }

  setValue(value) {
    this.__pendingValue = value;
  }

  commit() {
    while (isDirective(this.__pendingValue)) {
      const directive = this.__pendingValue;
      this.__pendingValue = noChange;
      directive(this);
    }

    if (this.__pendingValue === noChange) {
      return;
    }

    const newListener = this.__pendingValue;
    const oldListener = this.value;
    const shouldRemoveListener = newListener == null || oldListener != null && (newListener.capture !== oldListener.capture || newListener.once !== oldListener.once || newListener.passive !== oldListener.passive);
    const shouldAddListener = newListener != null && (oldListener == null || shouldRemoveListener);

    if (shouldRemoveListener) {
      this.element.removeEventListener(this.eventName, this.__boundHandleEvent, this.__options);
    }

    if (shouldAddListener) {
      this.__options = getOptions(newListener);
      this.element.addEventListener(this.eventName, this.__boundHandleEvent, this.__options);
    }

    this.value = newListener;
    this.__pendingValue = noChange;
  }

  handleEvent(event) {
    if (typeof this.value === 'function') {
      this.value.call(this.eventContext || this.element, event);
    } else {
      this.value.handleEvent(event);
    }
  }

} // We copy options because of the inconsistent behavior of browsers when reading
// the third argument of add/removeEventListener. IE11 doesn't support options
// at all. Chrome 41 only reads `capture` if the argument is an object.

const getOptions = o => o && (eventOptionsSupported ? {
  capture: o.capture,
  passive: o.passive,
  once: o.once
} : o.capture);
// CONCATENATED MODULE: ./node_modules/lit-html/lib/template-factory.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */

/**
 * The default TemplateFactory which caches Templates keyed on
 * result.type and result.strings.
 */

function templateFactory(result) {
  let templateCache = templateCaches.get(result.type);

  if (templateCache === undefined) {
    templateCache = {
      stringsArray: new WeakMap(),
      keyString: new Map()
    };
    templateCaches.set(result.type, templateCache);
  }

  let template = templateCache.stringsArray.get(result.strings);

  if (template !== undefined) {
    return template;
  } // If the TemplateStringsArray is new, generate a key from the strings
  // This key is shared between all templates with identical content


  const key = result.strings.join(template_marker); // Check if we already have a Template for this key

  template = templateCache.keyString.get(key);

  if (template === undefined) {
    // If we have not seen this key before, create a new Template
    template = new Template(result, result.getTemplateElement()); // Cache the Template for this key

    templateCache.keyString.set(key, template);
  } // Cache all future queries for this TemplateStringsArray


  templateCache.stringsArray.set(result.strings, template);
  return template;
}
const templateCaches = new Map();
// CONCATENATED MODULE: ./node_modules/lit-html/lib/render.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */



const render_parts = new WeakMap();
/**
 * Renders a template result or other value to a container.
 *
 * To update a container with new values, reevaluate the template literal and
 * call `render` with the new result.
 *
 * @param result Any value renderable by NodePart - typically a TemplateResult
 *     created by evaluating a template tag like `html` or `svg`.
 * @param container A DOM parent to render to. The entire contents are either
 *     replaced, or efficiently updated if the same result type was previous
 *     rendered there.
 * @param options RenderOptions for the entire render tree rendered to this
 *     container. Render options must *not* change between renders to the same
 *     container, as those changes will not effect previously rendered DOM.
 */

const render_render = (result, container, options) => {
  let part = render_parts.get(container);

  if (part === undefined) {
    removeNodes(container, container.firstChild);
    render_parts.set(container, part = new parts_NodePart(Object.assign({
      templateFactory: templateFactory
    }, options)));
    part.appendInto(container);
  }

  part.setValue(result);
  part.commit();
};
// CONCATENATED MODULE: ./node_modules/lit-html/lib/default-template-processor.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */

/**
 * Creates Parts when a template is instantiated.
 */

class default_template_processor_DefaultTemplateProcessor {
  /**
   * Create parts for an attribute-position binding, given the event, attribute
   * name, and string literals.
   *
   * @param element The element containing the binding
   * @param name  The attribute name
   * @param strings The string literals. There are always at least two strings,
   *   event for fully-controlled bindings with a single expression.
   */
  handleAttributeExpressions(element, name, strings, options) {
    const prefix = name[0];

    if (prefix === '.') {
      const committer = new PropertyCommitter(element, name.slice(1), strings);
      return committer.parts;
    }

    if (prefix === '@') {
      return [new parts_EventPart(element, name.slice(1), options.eventContext)];
    }

    if (prefix === '?') {
      return [new parts_BooleanAttributePart(element, name.slice(1), strings)];
    }

    const committer = new AttributeCommitter(element, name, strings);
    return committer.parts;
  }
  /**
   * Create parts for a text-position binding.
   * @param templateFactory
   */


  handleTextExpression(options) {
    return new parts_NodePart(options);
  }

}
const defaultTemplateProcessor = new default_template_processor_DefaultTemplateProcessor();
// CONCATENATED MODULE: ./node_modules/lit-html/lit-html.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */

/**
 *
 * Main lit-html module.
 *
 * Main exports:
 *
 * -  [[html]]
 * -  [[svg]]
 * -  [[render]]
 *
 * @packageDocumentation
 */

/**
 * Do not remove this comment; it keeps typedoc from misplacing the module
 * docs.
 */



 // TODO(justinfagnani): remove line when we get NodePart moving methods








 // IMPORTANT: do not change the property name or the assignment expression.
// This line will be used in regexes to search for lit-html usage.
// TODO(justinfagnani): inject version number at build time

if (typeof window !== 'undefined') {
  (window['litHtmlVersions'] || (window['litHtmlVersions'] = [])).push('1.3.0');
}
/**
 * Interprets a template literal as an HTML template that can efficiently
 * render to and update a container.
 */


const lit_html_html = (strings, ...values) => new template_result_TemplateResult(strings, values, 'html', defaultTemplateProcessor);
/**
 * Interprets a template literal as an SVG template that can efficiently
 * render to and update a container.
 */

const svg = (strings, ...values) => new template_result_SVGTemplateResult(strings, values, 'svg', defaultTemplateProcessor);
// CONCATENATED MODULE: ./node_modules/lit-html/lib/shady-render.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */

/**
 * Module to add shady DOM/shady CSS polyfill support to lit-html template
 * rendering. See the [[render]] method for details.
 *
 * @packageDocumentation
 */

/**
 * Do not remove this comment; it keeps typedoc from misplacing the module
 * docs.
 */






 // Get a key to lookup in `templateCaches`.

const getTemplateCacheKey = (type, scopeName) => `${type}--${scopeName}`;

let compatibleShadyCSSVersion = true;

if (typeof window.ShadyCSS === 'undefined') {
  compatibleShadyCSSVersion = false;
} else if (typeof window.ShadyCSS.prepareTemplateDom === 'undefined') {
  console.warn(`Incompatible ShadyCSS version detected. ` + `Please update to at least @webcomponents/webcomponentsjs@2.0.2 and ` + `@webcomponents/shadycss@1.3.1.`);
  compatibleShadyCSSVersion = false;
}
/**
 * Template factory which scopes template DOM using ShadyCSS.
 * @param scopeName {string}
 */


const shadyTemplateFactory = scopeName => result => {
  const cacheKey = getTemplateCacheKey(result.type, scopeName);
  let templateCache = templateCaches.get(cacheKey);

  if (templateCache === undefined) {
    templateCache = {
      stringsArray: new WeakMap(),
      keyString: new Map()
    };
    templateCaches.set(cacheKey, templateCache);
  }

  let template = templateCache.stringsArray.get(result.strings);

  if (template !== undefined) {
    return template;
  }

  const key = result.strings.join(template_marker);
  template = templateCache.keyString.get(key);

  if (template === undefined) {
    const element = result.getTemplateElement();

    if (compatibleShadyCSSVersion) {
      window.ShadyCSS.prepareTemplateDom(element, scopeName);
    }

    template = new Template(result, element);
    templateCache.keyString.set(key, template);
  }

  templateCache.stringsArray.set(result.strings, template);
  return template;
};
const TEMPLATE_TYPES = ['html', 'svg'];
/**
 * Removes all style elements from Templates for the given scopeName.
 */

const removeStylesFromLitTemplates = scopeName => {
  TEMPLATE_TYPES.forEach(type => {
    const templates = templateCaches.get(getTemplateCacheKey(type, scopeName));

    if (templates !== undefined) {
      templates.keyString.forEach(template => {
        const {
          element: {
            content
          }
        } = template; // IE 11 doesn't support the iterable param Set constructor

        const styles = new Set();
        Array.from(content.querySelectorAll('style')).forEach(s => {
          styles.add(s);
        });
        removeNodesFromTemplate(template, styles);
      });
    }
  });
};

const shadyRenderSet = new Set();
/**
 * For the given scope name, ensures that ShadyCSS style scoping is performed.
 * This is done just once per scope name so the fragment and template cannot
 * be modified.
 * (1) extracts styles from the rendered fragment and hands them to ShadyCSS
 * to be scoped and appended to the document
 * (2) removes style elements from all lit-html Templates for this scope name.
 *
 * Note, <style> elements can only be placed into templates for the
 * initial rendering of the scope. If <style> elements are included in templates
 * dynamically rendered to the scope (after the first scope render), they will
 * not be scoped and the <style> will be left in the template and rendered
 * output.
 */

const prepareTemplateStyles = (scopeName, renderedDOM, template) => {
  shadyRenderSet.add(scopeName); // If `renderedDOM` is stamped from a Template, then we need to edit that
  // Template's underlying template element. Otherwise, we create one here
  // to give to ShadyCSS, which still requires one while scoping.

  const templateElement = !!template ? template.element : document.createElement('template'); // Move styles out of rendered DOM and store.

  const styles = renderedDOM.querySelectorAll('style');
  const {
    length
  } = styles; // If there are no styles, skip unnecessary work

  if (length === 0) {
    // Ensure prepareTemplateStyles is called to support adding
    // styles via `prepareAdoptedCssText` since that requires that
    // `prepareTemplateStyles` is called.
    //
    // ShadyCSS will only update styles containing @apply in the template
    // given to `prepareTemplateStyles`. If no lit Template was given,
    // ShadyCSS will not be able to update uses of @apply in any relevant
    // template. However, this is not a problem because we only create the
    // template for the purpose of supporting `prepareAdoptedCssText`,
    // which doesn't support @apply at all.
    window.ShadyCSS.prepareTemplateStyles(templateElement, scopeName);
    return;
  }

  const condensedStyle = document.createElement('style'); // Collect styles into a single style. This helps us make sure ShadyCSS
  // manipulations will not prevent us from being able to fix up template
  // part indices.
  // NOTE: collecting styles is inefficient for browsers but ShadyCSS
  // currently does this anyway. When it does not, this should be changed.

  for (let i = 0; i < length; i++) {
    const style = styles[i];
    style.parentNode.removeChild(style);
    condensedStyle.textContent += style.textContent;
  } // Remove styles from nested templates in this scope.


  removeStylesFromLitTemplates(scopeName); // And then put the condensed style into the "root" template passed in as
  // `template`.

  const content = templateElement.content;

  if (!!template) {
    insertNodeIntoTemplate(template, condensedStyle, content.firstChild);
  } else {
    content.insertBefore(condensedStyle, content.firstChild);
  } // Note, it's important that ShadyCSS gets the template that `lit-html`
  // will actually render so that it can update the style inside when
  // needed (e.g. @apply native Shadow DOM case).


  window.ShadyCSS.prepareTemplateStyles(templateElement, scopeName);
  const style = content.querySelector('style');

  if (window.ShadyCSS.nativeShadow && style !== null) {
    // When in native Shadow DOM, ensure the style created by ShadyCSS is
    // included in initially rendered output (`renderedDOM`).
    renderedDOM.insertBefore(style.cloneNode(true), renderedDOM.firstChild);
  } else if (!!template) {
    // When no style is left in the template, parts will be broken as a
    // result. To fix this, we put back the style node ShadyCSS removed
    // and then tell lit to remove that node from the template.
    // There can be no style in the template in 2 cases (1) when Shady DOM
    // is in use, ShadyCSS removes all styles, (2) when native Shadow DOM
    // is in use ShadyCSS removes the style if it contains no content.
    // NOTE, ShadyCSS creates its own style so we can safely add/remove
    // `condensedStyle` here.
    content.insertBefore(condensedStyle, content.firstChild);
    const removes = new Set();
    removes.add(condensedStyle);
    removeNodesFromTemplate(template, removes);
  }
};
/**
 * Extension to the standard `render` method which supports rendering
 * to ShadowRoots when the ShadyDOM (https://github.com/webcomponents/shadydom)
 * and ShadyCSS (https://github.com/webcomponents/shadycss) polyfills are used
 * or when the webcomponentsjs
 * (https://github.com/webcomponents/webcomponentsjs) polyfill is used.
 *
 * Adds a `scopeName` option which is used to scope element DOM and stylesheets
 * when native ShadowDOM is unavailable. The `scopeName` will be added to
 * the class attribute of all rendered DOM. In addition, any style elements will
 * be automatically re-written with this `scopeName` selector and moved out
 * of the rendered DOM and into the document `<head>`.
 *
 * It is common to use this render method in conjunction with a custom element
 * which renders a shadowRoot. When this is done, typically the element's
 * `localName` should be used as the `scopeName`.
 *
 * In addition to DOM scoping, ShadyCSS also supports a basic shim for css
 * custom properties (needed only on older browsers like IE11) and a shim for
 * a deprecated feature called `@apply` that supports applying a set of css
 * custom properties to a given location.
 *
 * Usage considerations:
 *
 * * Part values in `<style>` elements are only applied the first time a given
 * `scopeName` renders. Subsequent changes to parts in style elements will have
 * no effect. Because of this, parts in style elements should only be used for
 * values that will never change, for example parts that set scope-wide theme
 * values or parts which render shared style elements.
 *
 * * Note, due to a limitation of the ShadyDOM polyfill, rendering in a
 * custom element's `constructor` is not supported. Instead rendering should
 * either done asynchronously, for example at microtask timing (for example
 * `Promise.resolve()`), or be deferred until the first time the element's
 * `connectedCallback` runs.
 *
 * Usage considerations when using shimmed custom properties or `@apply`:
 *
 * * Whenever any dynamic changes are made which affect
 * css custom properties, `ShadyCSS.styleElement(element)` must be called
 * to update the element. There are two cases when this is needed:
 * (1) the element is connected to a new parent, (2) a class is added to the
 * element that causes it to match different custom properties.
 * To address the first case when rendering a custom element, `styleElement`
 * should be called in the element's `connectedCallback`.
 *
 * * Shimmed custom properties may only be defined either for an entire
 * shadowRoot (for example, in a `:host` rule) or via a rule that directly
 * matches an element with a shadowRoot. In other words, instead of flowing from
 * parent to child as do native css custom properties, shimmed custom properties
 * flow only from shadowRoots to nested shadowRoots.
 *
 * * When using `@apply` mixing css shorthand property names with
 * non-shorthand names (for example `border` and `border-width`) is not
 * supported.
 */


const shady_render_render = (result, container, options) => {
  if (!options || typeof options !== 'object' || !options.scopeName) {
    throw new Error('The `scopeName` option is required.');
  }

  const scopeName = options.scopeName;
  const hasRendered = render_parts.has(container);
  const needsScoping = compatibleShadyCSSVersion && container.nodeType === 11
  /* Node.DOCUMENT_FRAGMENT_NODE */
  && !!container.host; // Handle first render to a scope specially...

  const firstScopeRender = needsScoping && !shadyRenderSet.has(scopeName); // On first scope render, render into a fragment; this cannot be a single
  // fragment that is reused since nested renders can occur synchronously.

  const renderContainer = firstScopeRender ? document.createDocumentFragment() : container;
  render_render(result, renderContainer, Object.assign({
    templateFactory: shadyTemplateFactory(scopeName)
  }, options)); // When performing first scope render,
  // (1) We've rendered into a fragment so that there's a chance to
  // `prepareTemplateStyles` before sub-elements hit the DOM
  // (which might cause them to render based on a common pattern of
  // rendering in a custom element's `connectedCallback`);
  // (2) Scope the template with ShadyCSS one time only for this scope.
  // (3) Render the fragment into the container and make sure the
  // container knows its `part` is the one we just rendered. This ensures
  // DOM will be re-used on subsequent renders.

  if (firstScopeRender) {
    const part = render_parts.get(renderContainer);
    render_parts.delete(renderContainer); // ShadyCSS might have style sheets (e.g. from `prepareAdoptedCssText`)
    // that should apply to `renderContainer` even if the rendered value is
    // not a TemplateInstance. However, it will only insert scoped styles
    // into the document if `prepareTemplateStyles` has already been called
    // for the given scope name.

    const template = part.value instanceof template_instance_TemplateInstance ? part.value.template : undefined;
    prepareTemplateStyles(scopeName, renderContainer, template);
    removeNodes(container, container.firstChild);
    container.appendChild(renderContainer);
    render_parts.set(container, part);
  } // After elements have hit the DOM, update styling if this is the
  // initial render to this container.
  // This is needed whenever dynamic changes are made so it would be
  // safest to do every render; however, this would regress performance
  // so we leave it up to the user to call `ShadyCSS.styleElement`
  // for dynamic changes.


  if (!hasRendered && needsScoping) {
    window.ShadyCSS.styleElement(container.host);
  }
};
// CONCATENATED MODULE: ./node_modules/lit-element/lib/updating-element.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */
var _a;
/**
 * Use this module if you want to create your own base class extending
 * [[UpdatingElement]].
 * @packageDocumentation
 */

/*
 * When using Closure Compiler, JSCompiler_renameProperty(property, object) is
 * replaced at compile time by the munged name for object[property]. We cannot
 * alias this function, so we have to use a small shim that has the same
 * behavior when not compiling.
 */


window.JSCompiler_renameProperty = (prop, _obj) => prop;

const defaultConverter = {
  toAttribute(value, type) {
    switch (type) {
      case Boolean:
        return value ? '' : null;

      case Object:
      case Array:
        // if the value is `null` or `undefined` pass this through
        // to allow removing/no change behavior.
        return value == null ? value : JSON.stringify(value);
    }

    return value;
  },

  fromAttribute(value, type) {
    switch (type) {
      case Boolean:
        return value !== null;

      case Number:
        return value === null ? null : Number(value);

      case Object:
      case Array:
        return JSON.parse(value);
    }

    return value;
  }

};
/**
 * Change function that returns true if `value` is different from `oldValue`.
 * This method is used as the default for a property's `hasChanged` function.
 */

const notEqual = (value, old) => {
  // This ensures (old==NaN, value==NaN) always returns false
  return old !== value && (old === old || value === value);
};
const defaultPropertyDeclaration = {
  attribute: true,
  type: String,
  converter: defaultConverter,
  reflect: false,
  hasChanged: notEqual
};
const STATE_HAS_UPDATED = 1;
const STATE_UPDATE_REQUESTED = 1 << 2;
const STATE_IS_REFLECTING_TO_ATTRIBUTE = 1 << 3;
const STATE_IS_REFLECTING_TO_PROPERTY = 1 << 4;
/**
 * The Closure JS Compiler doesn't currently have good support for static
 * property semantics where "this" is dynamic (e.g.
 * https://github.com/google/closure-compiler/issues/3177 and others) so we use
 * this hack to bypass any rewriting by the compiler.
 */

const finalized = 'finalized';
/**
 * Base element class which manages element properties and attributes. When
 * properties change, the `update` method is asynchronously called. This method
 * should be supplied by subclassers to render updates as desired.
 * @noInheritDoc
 */

class UpdatingElement extends HTMLElement {
  constructor() {
    super();
    this.initialize();
  }
  /**
   * Returns a list of attributes corresponding to the registered properties.
   * @nocollapse
   */


  static get observedAttributes() {
    // note: piggy backing on this to ensure we're finalized.
    this.finalize();
    const attributes = []; // Use forEach so this works even if for/of loops are compiled to for loops
    // expecting arrays

    this._classProperties.forEach((v, p) => {
      const attr = this._attributeNameForProperty(p, v);

      if (attr !== undefined) {
        this._attributeToPropertyMap.set(attr, p);

        attributes.push(attr);
      }
    });

    return attributes;
  }
  /**
   * Ensures the private `_classProperties` property metadata is created.
   * In addition to `finalize` this is also called in `createProperty` to
   * ensure the `@property` decorator can add property metadata.
   */

  /** @nocollapse */


  static _ensureClassProperties() {
    // ensure private storage for property declarations.
    if (!this.hasOwnProperty(JSCompiler_renameProperty('_classProperties', this))) {
      this._classProperties = new Map(); // NOTE: Workaround IE11 not supporting Map constructor argument.

      const superProperties = Object.getPrototypeOf(this)._classProperties;

      if (superProperties !== undefined) {
        superProperties.forEach((v, k) => this._classProperties.set(k, v));
      }
    }
  }
  /**
   * Creates a property accessor on the element prototype if one does not exist
   * and stores a PropertyDeclaration for the property with the given options.
   * The property setter calls the property's `hasChanged` property option
   * or uses a strict identity check to determine whether or not to request
   * an update.
   *
   * This method may be overridden to customize properties; however,
   * when doing so, it's important to call `super.createProperty` to ensure
   * the property is setup correctly. This method calls
   * `getPropertyDescriptor` internally to get a descriptor to install.
   * To customize what properties do when they are get or set, override
   * `getPropertyDescriptor`. To customize the options for a property,
   * implement `createProperty` like this:
   *
   * static createProperty(name, options) {
   *   options = Object.assign(options, {myOption: true});
   *   super.createProperty(name, options);
   * }
   *
   * @nocollapse
   */


  static createProperty(name, options = defaultPropertyDeclaration) {
    // Note, since this can be called by the `@property` decorator which
    // is called before `finalize`, we ensure storage exists for property
    // metadata.
    this._ensureClassProperties();

    this._classProperties.set(name, options); // Do not generate an accessor if the prototype already has one, since
    // it would be lost otherwise and that would never be the user's intention;
    // Instead, we expect users to call `requestUpdate` themselves from
    // user-defined accessors. Note that if the super has an accessor we will
    // still overwrite it


    if (options.noAccessor || this.prototype.hasOwnProperty(name)) {
      return;
    }

    const key = typeof name === 'symbol' ? Symbol() : `__${name}`;
    const descriptor = this.getPropertyDescriptor(name, key, options);

    if (descriptor !== undefined) {
      Object.defineProperty(this.prototype, name, descriptor);
    }
  }
  /**
   * Returns a property descriptor to be defined on the given named property.
   * If no descriptor is returned, the property will not become an accessor.
   * For example,
   *
   *   class MyElement extends LitElement {
   *     static getPropertyDescriptor(name, key, options) {
   *       const defaultDescriptor =
   *           super.getPropertyDescriptor(name, key, options);
   *       const setter = defaultDescriptor.set;
   *       return {
   *         get: defaultDescriptor.get,
   *         set(value) {
   *           setter.call(this, value);
   *           // custom action.
   *         },
   *         configurable: true,
   *         enumerable: true
   *       }
   *     }
   *   }
   *
   * @nocollapse
   */


  static getPropertyDescriptor(name, key, options) {
    return {
      // tslint:disable-next-line:no-any no symbol in index
      get() {
        return this[key];
      },

      set(value) {
        const oldValue = this[name];
        this[key] = value;
        this.requestUpdateInternal(name, oldValue, options);
      },

      configurable: true,
      enumerable: true
    };
  }
  /**
   * Returns the property options associated with the given property.
   * These options are defined with a PropertyDeclaration via the `properties`
   * object or the `@property` decorator and are registered in
   * `createProperty(...)`.
   *
   * Note, this method should be considered "final" and not overridden. To
   * customize the options for a given property, override `createProperty`.
   *
   * @nocollapse
   * @final
   */


  static getPropertyOptions(name) {
    return this._classProperties && this._classProperties.get(name) || defaultPropertyDeclaration;
  }
  /**
   * Creates property accessors for registered properties and ensures
   * any superclasses are also finalized.
   * @nocollapse
   */


  static finalize() {
    // finalize any superclasses
    const superCtor = Object.getPrototypeOf(this);

    if (!superCtor.hasOwnProperty(finalized)) {
      superCtor.finalize();
    }

    this[finalized] = true;

    this._ensureClassProperties(); // initialize Map populated in observedAttributes


    this._attributeToPropertyMap = new Map(); // make any properties
    // Note, only process "own" properties since this element will inherit
    // any properties defined on the superClass, and finalization ensures
    // the entire prototype chain is finalized.

    if (this.hasOwnProperty(JSCompiler_renameProperty('properties', this))) {
      const props = this.properties; // support symbols in properties (IE11 does not support this)

      const propKeys = [...Object.getOwnPropertyNames(props), ...(typeof Object.getOwnPropertySymbols === 'function' ? Object.getOwnPropertySymbols(props) : [])]; // This for/of is ok because propKeys is an array

      for (const p of propKeys) {
        // note, use of `any` is due to TypeSript lack of support for symbol in
        // index types
        // tslint:disable-next-line:no-any no symbol in index
        this.createProperty(p, props[p]);
      }
    }
  }
  /**
   * Returns the property name for the given attribute `name`.
   * @nocollapse
   */


  static _attributeNameForProperty(name, options) {
    const attribute = options.attribute;
    return attribute === false ? undefined : typeof attribute === 'string' ? attribute : typeof name === 'string' ? name.toLowerCase() : undefined;
  }
  /**
   * Returns true if a property should request an update.
   * Called when a property value is set and uses the `hasChanged`
   * option for the property if present or a strict identity check.
   * @nocollapse
   */


  static _valueHasChanged(value, old, hasChanged = notEqual) {
    return hasChanged(value, old);
  }
  /**
   * Returns the property value for the given attribute value.
   * Called via the `attributeChangedCallback` and uses the property's
   * `converter` or `converter.fromAttribute` property option.
   * @nocollapse
   */


  static _propertyValueFromAttribute(value, options) {
    const type = options.type;
    const converter = options.converter || defaultConverter;
    const fromAttribute = typeof converter === 'function' ? converter : converter.fromAttribute;
    return fromAttribute ? fromAttribute(value, type) : value;
  }
  /**
   * Returns the attribute value for the given property value. If this
   * returns undefined, the property will *not* be reflected to an attribute.
   * If this returns null, the attribute will be removed, otherwise the
   * attribute will be set to the value.
   * This uses the property's `reflect` and `type.toAttribute` property options.
   * @nocollapse
   */


  static _propertyValueToAttribute(value, options) {
    if (options.reflect === undefined) {
      return;
    }

    const type = options.type;
    const converter = options.converter;
    const toAttribute = converter && converter.toAttribute || defaultConverter.toAttribute;
    return toAttribute(value, type);
  }
  /**
   * Performs element initialization. By default captures any pre-set values for
   * registered properties.
   */


  initialize() {
    this._updateState = 0;
    this._updatePromise = new Promise(res => this._enableUpdatingResolver = res);
    this._changedProperties = new Map();

    this._saveInstanceProperties(); // ensures first update will be caught by an early access of
    // `updateComplete`


    this.requestUpdateInternal();
  }
  /**
   * Fixes any properties set on the instance before upgrade time.
   * Otherwise these would shadow the accessor and break these properties.
   * The properties are stored in a Map which is played back after the
   * constructor runs. Note, on very old versions of Safari (<=9) or Chrome
   * (<=41), properties created for native platform properties like (`id` or
   * `name`) may not have default values set in the element constructor. On
   * these browsers native properties appear on instances and therefore their
   * default value will overwrite any element default (e.g. if the element sets
   * this.id = 'id' in the constructor, the 'id' will become '' since this is
   * the native platform default).
   */


  _saveInstanceProperties() {
    // Use forEach so this works even if for/of loops are compiled to for loops
    // expecting arrays
    this.constructor._classProperties.forEach((_v, p) => {
      if (this.hasOwnProperty(p)) {
        const value = this[p];
        delete this[p];

        if (!this._instanceProperties) {
          this._instanceProperties = new Map();
        }

        this._instanceProperties.set(p, value);
      }
    });
  }
  /**
   * Applies previously saved instance properties.
   */


  _applyInstanceProperties() {
    // Use forEach so this works even if for/of loops are compiled to for loops
    // expecting arrays
    // tslint:disable-next-line:no-any
    this._instanceProperties.forEach((v, p) => this[p] = v);

    this._instanceProperties = undefined;
  }

  connectedCallback() {
    // Ensure first connection completes an update. Updates cannot complete
    // before connection.
    this.enableUpdating();
  }

  enableUpdating() {
    if (this._enableUpdatingResolver !== undefined) {
      this._enableUpdatingResolver();

      this._enableUpdatingResolver = undefined;
    }
  }
  /**
   * Allows for `super.disconnectedCallback()` in extensions while
   * reserving the possibility of making non-breaking feature additions
   * when disconnecting at some point in the future.
   */


  disconnectedCallback() {}
  /**
   * Synchronizes property values when attributes change.
   */


  attributeChangedCallback(name, old, value) {
    if (old !== value) {
      this._attributeToProperty(name, value);
    }
  }

  _propertyToAttribute(name, value, options = defaultPropertyDeclaration) {
    const ctor = this.constructor;

    const attr = ctor._attributeNameForProperty(name, options);

    if (attr !== undefined) {
      const attrValue = ctor._propertyValueToAttribute(value, options); // an undefined value does not change the attribute.


      if (attrValue === undefined) {
        return;
      } // Track if the property is being reflected to avoid
      // setting the property again via `attributeChangedCallback`. Note:
      // 1. this takes advantage of the fact that the callback is synchronous.
      // 2. will behave incorrectly if multiple attributes are in the reaction
      // stack at time of calling. However, since we process attributes
      // in `update` this should not be possible (or an extreme corner case
      // that we'd like to discover).
      // mark state reflecting


      this._updateState = this._updateState | STATE_IS_REFLECTING_TO_ATTRIBUTE;

      if (attrValue == null) {
        this.removeAttribute(attr);
      } else {
        this.setAttribute(attr, attrValue);
      } // mark state not reflecting


      this._updateState = this._updateState & ~STATE_IS_REFLECTING_TO_ATTRIBUTE;
    }
  }

  _attributeToProperty(name, value) {
    // Use tracking info to avoid deserializing attribute value if it was
    // just set from a property setter.
    if (this._updateState & STATE_IS_REFLECTING_TO_ATTRIBUTE) {
      return;
    }

    const ctor = this.constructor; // Note, hint this as an `AttributeMap` so closure clearly understands
    // the type; it has issues with tracking types through statics
    // tslint:disable-next-line:no-unnecessary-type-assertion

    const propName = ctor._attributeToPropertyMap.get(name);

    if (propName !== undefined) {
      const options = ctor.getPropertyOptions(propName); // mark state reflecting

      this._updateState = this._updateState | STATE_IS_REFLECTING_TO_PROPERTY;
      this[propName] = // tslint:disable-next-line:no-any
      ctor._propertyValueFromAttribute(value, options); // mark state not reflecting

      this._updateState = this._updateState & ~STATE_IS_REFLECTING_TO_PROPERTY;
    }
  }
  /**
   * This protected version of `requestUpdate` does not access or return the
   * `updateComplete` promise. This promise can be overridden and is therefore
   * not free to access.
   */


  requestUpdateInternal(name, oldValue, options) {
    let shouldRequestUpdate = true; // If we have a property key, perform property update steps.

    if (name !== undefined) {
      const ctor = this.constructor;
      options = options || ctor.getPropertyOptions(name);

      if (ctor._valueHasChanged(this[name], oldValue, options.hasChanged)) {
        if (!this._changedProperties.has(name)) {
          this._changedProperties.set(name, oldValue);
        } // Add to reflecting properties set.
        // Note, it's important that every change has a chance to add the
        // property to `_reflectingProperties`. This ensures setting
        // attribute + property reflects correctly.


        if (options.reflect === true && !(this._updateState & STATE_IS_REFLECTING_TO_PROPERTY)) {
          if (this._reflectingProperties === undefined) {
            this._reflectingProperties = new Map();
          }

          this._reflectingProperties.set(name, options);
        }
      } else {
        // Abort the request if the property should not be considered changed.
        shouldRequestUpdate = false;
      }
    }

    if (!this._hasRequestedUpdate && shouldRequestUpdate) {
      this._updatePromise = this._enqueueUpdate();
    }
  }
  /**
   * Requests an update which is processed asynchronously. This should
   * be called when an element should update based on some state not triggered
   * by setting a property. In this case, pass no arguments. It should also be
   * called when manually implementing a property setter. In this case, pass the
   * property `name` and `oldValue` to ensure that any configured property
   * options are honored. Returns the `updateComplete` Promise which is resolved
   * when the update completes.
   *
   * @param name {PropertyKey} (optional) name of requesting property
   * @param oldValue {any} (optional) old value of requesting property
   * @returns {Promise} A Promise that is resolved when the update completes.
   */


  requestUpdate(name, oldValue) {
    this.requestUpdateInternal(name, oldValue);
    return this.updateComplete;
  }
  /**
   * Sets up the element to asynchronously update.
   */


  async _enqueueUpdate() {
    this._updateState = this._updateState | STATE_UPDATE_REQUESTED;

    try {
      // Ensure any previous update has resolved before updating.
      // This `await` also ensures that property changes are batched.
      await this._updatePromise;
    } catch (e) {// Ignore any previous errors. We only care that the previous cycle is
      // done. Any error should have been handled in the previous update.
    }

    const result = this.performUpdate(); // If `performUpdate` returns a Promise, we await it. This is done to
    // enable coordinating updates with a scheduler. Note, the result is
    // checked to avoid delaying an additional microtask unless we need to.

    if (result != null) {
      await result;
    }

    return !this._hasRequestedUpdate;
  }

  get _hasRequestedUpdate() {
    return this._updateState & STATE_UPDATE_REQUESTED;
  }

  get hasUpdated() {
    return this._updateState & STATE_HAS_UPDATED;
  }
  /**
   * Performs an element update. Note, if an exception is thrown during the
   * update, `firstUpdated` and `updated` will not be called.
   *
   * You can override this method to change the timing of updates. If this
   * method is overridden, `super.performUpdate()` must be called.
   *
   * For instance, to schedule updates to occur just before the next frame:
   *
   * ```
   * protected async performUpdate(): Promise<unknown> {
   *   await new Promise((resolve) => requestAnimationFrame(() => resolve()));
   *   super.performUpdate();
   * }
   * ```
   */


  performUpdate() {
    // Abort any update if one is not pending when this is called.
    // This can happen if `performUpdate` is called early to "flush"
    // the update.
    if (!this._hasRequestedUpdate) {
      return;
    } // Mixin instance properties once, if they exist.


    if (this._instanceProperties) {
      this._applyInstanceProperties();
    }

    let shouldUpdate = false;
    const changedProperties = this._changedProperties;

    try {
      shouldUpdate = this.shouldUpdate(changedProperties);

      if (shouldUpdate) {
        this.update(changedProperties);
      } else {
        this._markUpdated();
      }
    } catch (e) {
      // Prevent `firstUpdated` and `updated` from running when there's an
      // update exception.
      shouldUpdate = false; // Ensure element can accept additional updates after an exception.

      this._markUpdated();

      throw e;
    }

    if (shouldUpdate) {
      if (!(this._updateState & STATE_HAS_UPDATED)) {
        this._updateState = this._updateState | STATE_HAS_UPDATED;
        this.firstUpdated(changedProperties);
      }

      this.updated(changedProperties);
    }
  }

  _markUpdated() {
    this._changedProperties = new Map();
    this._updateState = this._updateState & ~STATE_UPDATE_REQUESTED;
  }
  /**
   * Returns a Promise that resolves when the element has completed updating.
   * The Promise value is a boolean that is `true` if the element completed the
   * update without triggering another update. The Promise result is `false` if
   * a property was set inside `updated()`. If the Promise is rejected, an
   * exception was thrown during the update.
   *
   * To await additional asynchronous work, override the `_getUpdateComplete`
   * method. For example, it is sometimes useful to await a rendered element
   * before fulfilling this Promise. To do this, first await
   * `super._getUpdateComplete()`, then any subsequent state.
   *
   * @returns {Promise} The Promise returns a boolean that indicates if the
   * update resolved without triggering another update.
   */


  get updateComplete() {
    return this._getUpdateComplete();
  }
  /**
   * Override point for the `updateComplete` promise.
   *
   * It is not safe to override the `updateComplete` getter directly due to a
   * limitation in TypeScript which means it is not possible to call a
   * superclass getter (e.g. `super.updateComplete.then(...)`) when the target
   * language is ES5 (https://github.com/microsoft/TypeScript/issues/338).
   * This method should be overridden instead. For example:
   *
   *   class MyElement extends LitElement {
   *     async _getUpdateComplete() {
   *       await super._getUpdateComplete();
   *       await this._myChild.updateComplete;
   *     }
   *   }
   */


  _getUpdateComplete() {
    return this._updatePromise;
  }
  /**
   * Controls whether or not `update` should be called when the element requests
   * an update. By default, this method always returns `true`, but this can be
   * customized to control when to update.
   *
   * @param _changedProperties Map of changed properties with old values
   */


  shouldUpdate(_changedProperties) {
    return true;
  }
  /**
   * Updates the element. This method reflects property values to attributes.
   * It can be overridden to render and keep updated element DOM.
   * Setting properties inside this method will *not* trigger
   * another update.
   *
   * @param _changedProperties Map of changed properties with old values
   */


  update(_changedProperties) {
    if (this._reflectingProperties !== undefined && this._reflectingProperties.size > 0) {
      // Use forEach so this works even if for/of loops are compiled to for
      // loops expecting arrays
      this._reflectingProperties.forEach((v, k) => this._propertyToAttribute(k, this[k], v));

      this._reflectingProperties = undefined;
    }

    this._markUpdated();
  }
  /**
   * Invoked whenever the element is updated. Implement to perform
   * post-updating tasks via DOM APIs, for example, focusing an element.
   *
   * Setting properties inside this method will trigger the element to update
   * again after this update cycle completes.
   *
   * @param _changedProperties Map of changed properties with old values
   */


  updated(_changedProperties) {}
  /**
   * Invoked when the element is first updated. Implement to perform one time
   * work on the element after update.
   *
   * Setting properties inside this method will trigger the element to update
   * again after this update cycle completes.
   *
   * @param _changedProperties Map of changed properties with old values
   */


  firstUpdated(_changedProperties) {}

}
_a = finalized;
/**
 * Marks class as having finished creating properties.
 */

UpdatingElement[_a] = true;
// CONCATENATED MODULE: ./node_modules/lit-element/lib/decorators.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */
const legacyCustomElement = (tagName, clazz) => {
  window.customElements.define(tagName, clazz); // Cast as any because TS doesn't recognize the return type as being a
  // subtype of the decorated class when clazz is typed as
  // `Constructor<HTMLElement>` for some reason.
  // `Constructor<HTMLElement>` is helpful to make sure the decorator is
  // applied to elements however.
  // tslint:disable-next-line:no-any

  return clazz;
};

const standardCustomElement = (tagName, descriptor) => {
  const {
    kind,
    elements
  } = descriptor;
  return {
    kind,
    elements,

    // This callback is called once the class is otherwise fully defined
    finisher(clazz) {
      window.customElements.define(tagName, clazz);
    }

  };
};
/**
 * Class decorator factory that defines the decorated class as a custom element.
 *
 * ```
 * @customElement('my-element')
 * class MyElement {
 *   render() {
 *     return html``;
 *   }
 * }
 * ```
 * @category Decorator
 * @param tagName The name of the custom element to define.
 */


const customElement = tagName => classOrDescriptor => typeof classOrDescriptor === 'function' ? legacyCustomElement(tagName, classOrDescriptor) : standardCustomElement(tagName, classOrDescriptor);

const standardProperty = (options, element) => {
  // When decorating an accessor, pass it through and add property metadata.
  // Note, the `hasOwnProperty` check in `createProperty` ensures we don't
  // stomp over the user's accessor.
  if (element.kind === 'method' && element.descriptor && !('value' in element.descriptor)) {
    return Object.assign(Object.assign({}, element), {
      finisher(clazz) {
        clazz.createProperty(element.key, options);
      }

    });
  } else {
    // createProperty() takes care of defining the property, but we still
    // must return some kind of descriptor, so return a descriptor for an
    // unused prototype field. The finisher calls createProperty().
    return {
      kind: 'field',
      key: Symbol(),
      placement: 'own',
      descriptor: {},

      // When @babel/plugin-proposal-decorators implements initializers,
      // do this instead of the initializer below. See:
      // https://github.com/babel/babel/issues/9260 extras: [
      //   {
      //     kind: 'initializer',
      //     placement: 'own',
      //     initializer: descriptor.initializer,
      //   }
      // ],
      initializer() {
        if (typeof element.initializer === 'function') {
          this[element.key] = element.initializer.call(this);
        }
      },

      finisher(clazz) {
        clazz.createProperty(element.key, options);
      }

    };
  }
};

const legacyProperty = (options, proto, name) => {
  proto.constructor.createProperty(name, options);
};
/**
 * A property decorator which creates a LitElement property which reflects a
 * corresponding attribute value. A [[`PropertyDeclaration`]] may optionally be
 * supplied to configure property features.
 *
 * This decorator should only be used for public fields. Private or protected
 * fields should use the [[`internalProperty`]] decorator.
 *
 * @example
 * ```ts
 * class MyElement {
 *   @property({ type: Boolean })
 *   clicked = false;
 * }
 * ```
 * @category Decorator
 * @ExportDecoratedItems
 */


function decorators_property(options) {
  // tslint:disable-next-line:no-any decorator
  return (protoOrDescriptor, name) => name !== undefined ? legacyProperty(options, protoOrDescriptor, name) : standardProperty(options, protoOrDescriptor);
}
/**
 * Declares a private or protected property that still triggers updates to the
 * element when it changes.
 *
 * Properties declared this way must not be used from HTML or HTML templating
 * systems, they're solely for properties internal to the element. These
 * properties may be renamed by optimization tools like closure compiler.
 * @category Decorator
 */

function internalProperty(options) {
  return decorators_property({
    attribute: false,
    hasChanged: options === null || options === void 0 ? void 0 : options.hasChanged
  });
}
/**
 * A property decorator that converts a class property into a getter that
 * executes a querySelector on the element's renderRoot.
 *
 * @param selector A DOMString containing one or more selectors to match.
 * @param cache An optional boolean which when true performs the DOM query only
 * once and caches the result.
 *
 * See: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
 *
 * @example
 *
 * ```ts
 * class MyElement {
 *   @query('#first')
 *   first;
 *
 *   render() {
 *     return html`
 *       <div id="first"></div>
 *       <div id="second"></div>
 *     `;
 *   }
 * }
 * ```
 * @category Decorator
 */

function decorators_query(selector, cache) {
  return (protoOrDescriptor, // tslint:disable-next-line:no-any decorator
  name) => {
    const descriptor = {
      get() {
        return this.renderRoot.querySelector(selector);
      },

      enumerable: true,
      configurable: true
    };

    if (cache) {
      const key = typeof name === 'symbol' ? Symbol() : `__${name}`;

      descriptor.get = function () {
        if (this[key] === undefined) {
          this[key] = this.renderRoot.querySelector(selector);
        }

        return this[key];
      };
    }

    return name !== undefined ? legacyQuery(descriptor, protoOrDescriptor, name) : standardQuery(descriptor, protoOrDescriptor);
  };
} // Note, in the future, we may extend this decorator to support the use case
// where the queried element may need to do work to become ready to interact
// with (e.g. load some implementation code). If so, we might elect to
// add a second argument defining a function that can be run to make the
// queried element loaded/updated/ready.

/**
 * A property decorator that converts a class property into a getter that
 * returns a promise that resolves to the result of a querySelector on the
 * element's renderRoot done after the element's `updateComplete` promise
 * resolves. When the queried property may change with element state, this
 * decorator can be used instead of requiring users to await the
 * `updateComplete` before accessing the property.
 *
 * @param selector A DOMString containing one or more selectors to match.
 *
 * See: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
 *
 * @example
 * ```ts
 * class MyElement {
 *   @queryAsync('#first')
 *   first;
 *
 *   render() {
 *     return html`
 *       <div id="first"></div>
 *       <div id="second"></div>
 *     `;
 *   }
 * }
 *
 * // external usage
 * async doSomethingWithFirst() {
 *  (await aMyElement.first).doSomething();
 * }
 * ```
 * @category Decorator
 */

function queryAsync(selector) {
  return (protoOrDescriptor, // tslint:disable-next-line:no-any decorator
  name) => {
    const descriptor = {
      async get() {
        await this.updateComplete;
        return this.renderRoot.querySelector(selector);
      },

      enumerable: true,
      configurable: true
    };
    return name !== undefined ? legacyQuery(descriptor, protoOrDescriptor, name) : standardQuery(descriptor, protoOrDescriptor);
  };
}
/**
 * A property decorator that converts a class property into a getter
 * that executes a querySelectorAll on the element's renderRoot.
 *
 * @param selector A DOMString containing one or more selectors to match.
 *
 * See:
 * https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
 *
 * @example
 * ```ts
 * class MyElement {
 *   @queryAll('div')
 *   divs;
 *
 *   render() {
 *     return html`
 *       <div id="first"></div>
 *       <div id="second"></div>
 *     `;
 *   }
 * }
 * ```
 * @category Decorator
 */

function queryAll(selector) {
  return (protoOrDescriptor, // tslint:disable-next-line:no-any decorator
  name) => {
    const descriptor = {
      get() {
        return this.renderRoot.querySelectorAll(selector);
      },

      enumerable: true,
      configurable: true
    };
    return name !== undefined ? legacyQuery(descriptor, protoOrDescriptor, name) : standardQuery(descriptor, protoOrDescriptor);
  };
}

const legacyQuery = (descriptor, proto, name) => {
  Object.defineProperty(proto, name, descriptor);
};

const standardQuery = (descriptor, element) => ({
  kind: 'method',
  placement: 'prototype',
  key: element.key,
  descriptor
});

const standardEventOptions = (options, element) => {
  return Object.assign(Object.assign({}, element), {
    finisher(clazz) {
      Object.assign(clazz.prototype[element.key], options);
    }

  });
};

const legacyEventOptions = // tslint:disable-next-line:no-any legacy decorator
(options, proto, name) => {
  Object.assign(proto[name], options);
};
/**
 * Adds event listener options to a method used as an event listener in a
 * lit-html template.
 *
 * @param options An object that specifies event listener options as accepted by
 * `EventTarget#addEventListener` and `EventTarget#removeEventListener`.
 *
 * Current browsers support the `capture`, `passive`, and `once` options. See:
 * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters
 *
 * @example
 * ```ts
 * class MyElement {
 *   clicked = false;
 *
 *   render() {
 *     return html`
 *       <div @click=${this._onClick}`>
 *         <button></button>
 *       </div>
 *     `;
 *   }
 *
 *   @eventOptions({capture: true})
 *   _onClick(e) {
 *     this.clicked = true;
 *   }
 * }
 * ```
 * @category Decorator
 */


function eventOptions(options) {
  // Return value typed as any to prevent TypeScript from complaining that
  // standard decorator function signature does not match TypeScript decorator
  // signature
  // TODO(kschaaf): unclear why it was only failing on this decorator and not
  // the others
  return (protoOrDescriptor, name) => name !== undefined ? legacyEventOptions(options, protoOrDescriptor, name) : standardEventOptions(options, protoOrDescriptor);
} // x-browser support for matches
// tslint:disable-next-line:no-any

const ElementProto = Element.prototype;
const legacyMatches = ElementProto.msMatchesSelector || ElementProto.webkitMatchesSelector;
/**
 * A property decorator that converts a class property into a getter that
 * returns the `assignedNodes` of the given named `slot`. Note, the type of
 * this property should be annotated as `NodeListOf<HTMLElement>`.
 *
 * @param slotName A string name of the slot.
 * @param flatten A boolean which when true flattens the assigned nodes,
 * meaning any assigned nodes that are slot elements are replaced with their
 * assigned nodes.
 * @param selector A string which filters the results to elements that match
 * the given css selector.
 *
 * * @example
 * ```ts
 * class MyElement {
 *   @queryAssignedNodes('list', true, '.item')
 *   listItems;
 *
 *   render() {
 *     return html`
 *       <slot name="list"></slot>
 *     `;
 *   }
 * }
 * ```
 * @category Decorator
 */

function queryAssignedNodes(slotName = '', flatten = false, selector = '') {
  return (protoOrDescriptor, // tslint:disable-next-line:no-any decorator
  name) => {
    const descriptor = {
      get() {
        const slotSelector = `slot${slotName ? `[name=${slotName}]` : ':not([name])'}`;
        const slot = this.renderRoot.querySelector(slotSelector);
        let nodes = slot && slot.assignedNodes({
          flatten
        });

        if (nodes && selector) {
          nodes = nodes.filter(node => node.nodeType === Node.ELEMENT_NODE && node.matches ? node.matches(selector) : legacyMatches.call(node, selector));
        }

        return nodes;
      },

      enumerable: true,
      configurable: true
    };
    return name !== undefined ? legacyQuery(descriptor, protoOrDescriptor, name) : standardQuery(descriptor, protoOrDescriptor);
  };
}
// CONCATENATED MODULE: ./node_modules/lit-element/lib/css-tag.js
/**
@license
Copyright (c) 2019 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at
http://polymer.github.io/LICENSE.txt The complete set of authors may be found at
http://polymer.github.io/AUTHORS.txt The complete set of contributors may be
found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as
part of the polymer project is also subject to an additional IP rights grant
found at http://polymer.github.io/PATENTS.txt
*/

/**
 * Whether the current browser supports `adoptedStyleSheets`.
 */
const supportsAdoptingStyleSheets = window.ShadowRoot && (window.ShadyCSS === undefined || window.ShadyCSS.nativeShadow) && 'adoptedStyleSheets' in Document.prototype && 'replace' in CSSStyleSheet.prototype;
const constructionToken = Symbol();
class CSSResult {
  constructor(cssText, safeToken) {
    if (safeToken !== constructionToken) {
      throw new Error('CSSResult is not constructable. Use `unsafeCSS` or `css` instead.');
    }

    this.cssText = cssText;
  } // Note, this is a getter so that it's lazy. In practice, this means
  // stylesheets are not created until the first element instance is made.


  get styleSheet() {
    if (this._styleSheet === undefined) {
      // Note, if `supportsAdoptingStyleSheets` is true then we assume
      // CSSStyleSheet is constructable.
      if (supportsAdoptingStyleSheets) {
        this._styleSheet = new CSSStyleSheet();

        this._styleSheet.replaceSync(this.cssText);
      } else {
        this._styleSheet = null;
      }
    }

    return this._styleSheet;
  }

  toString() {
    return this.cssText;
  }

}
/**
 * Wrap a value for interpolation in a [[`css`]] tagged template literal.
 *
 * This is unsafe because untrusted CSS text can be used to phone home
 * or exfiltrate data to an attacker controlled site. Take care to only use
 * this with trusted input.
 */

const unsafeCSS = value => {
  return new CSSResult(String(value), constructionToken);
};

const textFromCSSResult = value => {
  if (value instanceof CSSResult) {
    return value.cssText;
  } else if (typeof value === 'number') {
    return value;
  } else {
    throw new Error(`Value passed to 'css' function must be a 'css' function result: ${value}. Use 'unsafeCSS' to pass non-literal values, but
            take care to ensure page security.`);
  }
};
/**
 * Template tag which which can be used with LitElement's [[LitElement.styles |
 * `styles`]] property to set element styles. For security reasons, only literal
 * string values may be used. To incorporate non-literal values [[`unsafeCSS`]]
 * may be used inside a template string part.
 */


const css = (strings, ...values) => {
  const cssText = values.reduce((acc, v, idx) => acc + textFromCSSResult(v) + strings[idx + 1], strings[0]);
  return new CSSResult(cssText, constructionToken);
};
// CONCATENATED MODULE: ./node_modules/lit-element/lit-element.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */

/**
 * The main LitElement module, which defines the [[`LitElement`]] base class and
 * related APIs.
 *
 *  LitElement components can define a template and a set of observed
 * properties. Changing an observed property triggers a re-render of the
 * element.
 *
 *  Import [[`LitElement`]] and [[`html`]] from this module to create a
 * component:
 *
 *  ```js
 * import {LitElement, html} from 'lit-element';
 *
 * class MyElement extends LitElement {
 *
 *   // Declare observed properties
 *   static get properties() {
 *     return {
 *       adjective: {}
 *     }
 *   }
 *
 *   constructor() {
 *     this.adjective = 'awesome';
 *   }
 *
 *   // Define the element's template
 *   render() {
 *     return html`<p>your ${adjective} template here</p>`;
 *   }
 * }
 *
 * customElements.define('my-element', MyElement);
 * ```
 *
 * `LitElement` extends [[`UpdatingElement`]] and adds lit-html templating.
 * The `UpdatingElement` class is provided for users that want to build
 * their own custom element base classes that don't use lit-html.
 *
 * @packageDocumentation
 */






 // IMPORTANT: do not change the property name or the assignment expression.
// This line will be used in regexes to search for LitElement usage.
// TODO(justinfagnani): inject version number at build time

(window['litElementVersions'] || (window['litElementVersions'] = [])).push('2.4.0');
/**
 * Sentinal value used to avoid calling lit-html's render function when
 * subclasses do not implement `render`
 */

const renderNotImplemented = {};
/**
 * Base element class that manages element properties and attributes, and
 * renders a lit-html template.
 *
 * To define a component, subclass `LitElement` and implement a
 * `render` method to provide the component's template. Define properties
 * using the [[`properties`]] property or the [[`property`]] decorator.
 */

class lit_element_LitElement extends UpdatingElement {
  /**
   * Return the array of styles to apply to the element.
   * Override this method to integrate into a style management system.
   *
   * @nocollapse
   */
  static getStyles() {
    return this.styles;
  }
  /** @nocollapse */


  static _getUniqueStyles() {
    // Only gather styles once per class
    if (this.hasOwnProperty(JSCompiler_renameProperty('_styles', this))) {
      return;
    } // Take care not to call `this.getStyles()` multiple times since this
    // generates new CSSResults each time.
    // TODO(sorvell): Since we do not cache CSSResults by input, any
    // shared styles will generate new stylesheet objects, which is wasteful.
    // This should be addressed when a browser ships constructable
    // stylesheets.


    const userStyles = this.getStyles();

    if (Array.isArray(userStyles)) {
      // De-duplicate styles preserving the _last_ instance in the set.
      // This is a performance optimization to avoid duplicated styles that can
      // occur especially when composing via subclassing.
      // The last item is kept to try to preserve the cascade order with the
      // assumption that it's most important that last added styles override
      // previous styles.
      const addStyles = (styles, set) => styles.reduceRight((set, s) => // Note: On IE set.add() does not return the set
      Array.isArray(s) ? addStyles(s, set) : (set.add(s), set), set); // Array.from does not work on Set in IE, otherwise return
      // Array.from(addStyles(userStyles, new Set<CSSResult>())).reverse()


      const set = addStyles(userStyles, new Set());
      const styles = [];
      set.forEach(v => styles.unshift(v));
      this._styles = styles;
    } else {
      this._styles = userStyles === undefined ? [] : [userStyles];
    } // Ensure that there are no invalid CSSStyleSheet instances here. They are
    // invalid in two conditions.
    // (1) the sheet is non-constructible (`sheet` of a HTMLStyleElement), but
    //     this is impossible to check except via .replaceSync or use
    // (2) the ShadyCSS polyfill is enabled (:. supportsAdoptingStyleSheets is
    //     false)


    this._styles = this._styles.map(s => {
      if (s instanceof CSSStyleSheet && !supportsAdoptingStyleSheets) {
        // Flatten the cssText from the passed constructible stylesheet (or
        // undetectable non-constructible stylesheet). The user might have
        // expected to update their stylesheets over time, but the alternative
        // is a crash.
        const cssText = Array.prototype.slice.call(s.cssRules).reduce((css, rule) => css + rule.cssText, '');
        return unsafeCSS(cssText);
      }

      return s;
    });
  }
  /**
   * Performs element initialization. By default this calls
   * [[`createRenderRoot`]] to create the element [[`renderRoot`]] node and
   * captures any pre-set values for registered properties.
   */


  initialize() {
    super.initialize();

    this.constructor._getUniqueStyles();

    this.renderRoot = this.createRenderRoot(); // Note, if renderRoot is not a shadowRoot, styles would/could apply to the
    // element's getRootNode(). While this could be done, we're choosing not to
    // support this now since it would require different logic around de-duping.

    if (window.ShadowRoot && this.renderRoot instanceof window.ShadowRoot) {
      this.adoptStyles();
    }
  }
  /**
   * Returns the node into which the element should render and by default
   * creates and returns an open shadowRoot. Implement to customize where the
   * element's DOM is rendered. For example, to render into the element's
   * childNodes, return `this`.
   * @returns {Element|DocumentFragment} Returns a node into which to render.
   */


  createRenderRoot() {
    return this.attachShadow({
      mode: 'open'
    });
  }
  /**
   * Applies styling to the element shadowRoot using the [[`styles`]]
   * property. Styling will apply using `shadowRoot.adoptedStyleSheets` where
   * available and will fallback otherwise. When Shadow DOM is polyfilled,
   * ShadyCSS scopes styles and adds them to the document. When Shadow DOM
   * is available but `adoptedStyleSheets` is not, styles are appended to the
   * end of the `shadowRoot` to [mimic spec
   * behavior](https://wicg.github.io/construct-stylesheets/#using-constructed-stylesheets).
   */


  adoptStyles() {
    const styles = this.constructor._styles;

    if (styles.length === 0) {
      return;
    } // There are three separate cases here based on Shadow DOM support.
    // (1) shadowRoot polyfilled: use ShadyCSS
    // (2) shadowRoot.adoptedStyleSheets available: use it
    // (3) shadowRoot.adoptedStyleSheets polyfilled: append styles after
    // rendering


    if (window.ShadyCSS !== undefined && !window.ShadyCSS.nativeShadow) {
      window.ShadyCSS.ScopingShim.prepareAdoptedCssText(styles.map(s => s.cssText), this.localName);
    } else if (supportsAdoptingStyleSheets) {
      this.renderRoot.adoptedStyleSheets = styles.map(s => s instanceof CSSStyleSheet ? s : s.styleSheet);
    } else {
      // This must be done after rendering so the actual style insertion is done
      // in `update`.
      this._needsShimAdoptedStyleSheets = true;
    }
  }

  connectedCallback() {
    super.connectedCallback(); // Note, first update/render handles styleElement so we only call this if
    // connected after first update.

    if (this.hasUpdated && window.ShadyCSS !== undefined) {
      window.ShadyCSS.styleElement(this);
    }
  }
  /**
   * Updates the element. This method reflects property values to attributes
   * and calls `render` to render DOM via lit-html. Setting properties inside
   * this method will *not* trigger another update.
   * @param _changedProperties Map of changed properties with old values
   */


  update(changedProperties) {
    // Setting properties in `render` should not trigger an update. Since
    // updates are allowed after super.update, it's important to call `render`
    // before that.
    const templateResult = this.render();
    super.update(changedProperties); // If render is not implemented by the component, don't call lit-html render

    if (templateResult !== renderNotImplemented) {
      this.constructor.render(templateResult, this.renderRoot, {
        scopeName: this.localName,
        eventContext: this
      });
    } // When native Shadow DOM is used but adoptedStyles are not supported,
    // insert styling after rendering to ensure adoptedStyles have highest
    // priority.


    if (this._needsShimAdoptedStyleSheets) {
      this._needsShimAdoptedStyleSheets = false;

      this.constructor._styles.forEach(s => {
        const style = document.createElement('style');
        style.textContent = s.cssText;
        this.renderRoot.appendChild(style);
      });
    }
  }
  /**
   * Invoked on each update to perform rendering tasks. This method may return
   * any value renderable by lit-html's `NodePart` - typically a
   * `TemplateResult`. Setting properties inside this method will *not* trigger
   * the element to update.
   */


  render() {
    return renderNotImplemented;
  }

}
/**
 * Ensure this class is marked as `finalized` as an optimization ensuring
 * it will not needlessly try to `finalize`.
 *
 * Note this property name is a string to prevent breaking Closure JS Compiler
 * optimizations. See updating-element.ts for more information.
 */

lit_element_LitElement['finalized'] = true;
/**
 * Reference to the underlying library method used to render the element's
 * DOM. By default, points to the `render` method from lit-html's shady-render
 * module.
 *
 * **Most users will never need to touch this property.**
 *
 * This  property should not be confused with the `render` instance method,
 * which should be overridden to define a template for the element.
 *
 * Advanced users creating a new base class based on LitElement can override
 * this property to point to a custom render method with a signature that
 * matches [shady-render's `render`
 * method](https://lit-html.polymer-project.org/api/modules/shady_render.html#render).
 *
 * @nocollapse
 */

lit_element_LitElement.render = shady_render_render;
// EXTERNAL MODULE: ./node_modules/sprintf-js/src/sprintf.js
var sprintf = __webpack_require__(91);

// CONCATENATED MODULE: ./src/headless/converse-core.js
/**
 * @module converse-core
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */





















dayjs_min_default.a.extend(advancedFormat_default.a); // Add Strophe Namespaces

strophe["e" /* Strophe */].addNamespace('CARBONS', 'urn:xmpp:carbons:2');
strophe["e" /* Strophe */].addNamespace('CHATSTATES', 'http://jabber.org/protocol/chatstates');
strophe["e" /* Strophe */].addNamespace('CSI', 'urn:xmpp:csi:0');
strophe["e" /* Strophe */].addNamespace('DELAY', 'urn:xmpp:delay');
strophe["e" /* Strophe */].addNamespace('FASTEN', 'urn:xmpp:fasten:0');
strophe["e" /* Strophe */].addNamespace('FORWARD', 'urn:xmpp:forward:0');
strophe["e" /* Strophe */].addNamespace('HINTS', 'urn:xmpp:hints');
strophe["e" /* Strophe */].addNamespace('HTTPUPLOAD', 'urn:xmpp:http:upload:0');
strophe["e" /* Strophe */].addNamespace('IDLE', 'urn:xmpp:idle:1');
strophe["e" /* Strophe */].addNamespace('MAM', 'urn:xmpp:mam:2');
strophe["e" /* Strophe */].addNamespace('MODERATE', 'urn:xmpp:message-moderate:0');
strophe["e" /* Strophe */].addNamespace('NICK', 'http://jabber.org/protocol/nick');
strophe["e" /* Strophe */].addNamespace('OMEMO', 'eu.siacs.conversations.axolotl');
strophe["e" /* Strophe */].addNamespace('OUTOFBAND', 'jabber:x:oob');
strophe["e" /* Strophe */].addNamespace('PUBSUB', 'http://jabber.org/protocol/pubsub');
strophe["e" /* Strophe */].addNamespace('REGISTER', 'jabber:iq:register');
strophe["e" /* Strophe */].addNamespace('RETRACT', 'urn:xmpp:message-retract:0');
strophe["e" /* Strophe */].addNamespace('ROSTERX', 'http://jabber.org/protocol/rosterx');
strophe["e" /* Strophe */].addNamespace('RSM', 'http://jabber.org/protocol/rsm');
strophe["e" /* Strophe */].addNamespace('SID', 'urn:xmpp:sid:0');
strophe["e" /* Strophe */].addNamespace('SPOILER', 'urn:xmpp:spoiler:0');
strophe["e" /* Strophe */].addNamespace('STANZAS', 'urn:ietf:params:xml:ns:xmpp-stanzas');
strophe["e" /* Strophe */].addNamespace('VCARD', 'vcard-temp');
strophe["e" /* Strophe */].addNamespace('VCARDUPDATE', 'vcard-temp:x:update');
strophe["e" /* Strophe */].addNamespace('XFORM', 'jabber:x:data');
/**
 * Custom error for indicating timeouts
 * @namespace _converse
 */

class TimeoutError extends Error {} // Core plugins are whitelisted automatically
// These are just the @converse/headless plugins, for the full converse,
// the other plugins are whitelisted in src/converse.js


const CORE_PLUGINS = ['converse-adhoc', 'converse-bookmarks', 'converse-bosh', 'converse-caps', 'converse-carbons', 'converse-chat', 'converse-chatboxes', 'converse-disco', 'converse-emoji', 'converse-headlines', 'converse-mam', 'converse-muc', 'converse-ping', 'converse-pubsub', 'converse-roster', 'converse-smacks', 'converse-status', 'converse-vcard']; // Default configuration values
// ----------------------------

const DEFAULT_SETTINGS = {
  allow_non_roster_messaging: false,
  assets_path: '/dist',
  authentication: 'login',
  // Available values are "login", "prebind", "anonymous" and "external".
  auto_login: false,
  // Currently only used in connection with anonymous login
  auto_reconnect: true,
  blacklisted_plugins: [],
  clear_cache_on_logout: false,
  connection_options: {},
  credentials_url: null,
  // URL from where login credentials can be fetched
  discover_connection_methods: true,
  geouri_regex: /https\:\/\/www.openstreetmap.org\/.*#map=[0-9]+\/([\-0-9.]+)\/([\-0-9.]+)\S*/g,
  geouri_replacement: 'https://www.openstreetmap.org/?mlat=$1&mlon=$2#map=18/$1/$2',
  i18n: undefined,
  idle_presence_timeout: 300,
  // Seconds after which an idle presence is sent
  jid: undefined,
  keepalive: true,
  loglevel: 'info',
  locales: ['af', 'ar', 'bg', 'ca', 'cs', 'de', 'eo', 'es', 'eu', 'en', 'fi', 'fr', 'gl', 'he', 'hi', 'hu', 'id', 'it', 'ja', 'nb', 'nl', 'mr', 'oc', 'pl', 'pt', 'pt_BR', 'ro', 'ru', 'tr', 'uk', 'vi', 'zh_CN', 'zh_TW'],
  nickname: undefined,
  password: undefined,
  persistent_store: 'localStorage',
  rid: undefined,
  root: window.document,
  sid: undefined,
  singleton: false,
  strict_plugin_dependencies: false,
  view_mode: 'overlayed',
  // Choices are 'overlayed', 'fullscreen', 'mobile'
  websocket_url: undefined,
  whitelisted_plugins: []
};
const CONNECTION_STATUS = {};
CONNECTION_STATUS[strophe["e" /* Strophe */].Status.ATTACHED] = 'ATTACHED';
CONNECTION_STATUS[strophe["e" /* Strophe */].Status.AUTHENTICATING] = 'AUTHENTICATING';
CONNECTION_STATUS[strophe["e" /* Strophe */].Status.AUTHFAIL] = 'AUTHFAIL';
CONNECTION_STATUS[strophe["e" /* Strophe */].Status.CONNECTED] = 'CONNECTED';
CONNECTION_STATUS[strophe["e" /* Strophe */].Status.CONNECTING] = 'CONNECTING';
CONNECTION_STATUS[strophe["e" /* Strophe */].Status.CONNFAIL] = 'CONNFAIL';
CONNECTION_STATUS[strophe["e" /* Strophe */].Status.DISCONNECTED] = 'DISCONNECTED';
CONNECTION_STATUS[strophe["e" /* Strophe */].Status.DISCONNECTING] = 'DISCONNECTING';
CONNECTION_STATUS[strophe["e" /* Strophe */].Status.ERROR] = 'ERROR';
CONNECTION_STATUS[strophe["e" /* Strophe */].Status.RECONNECTING] = 'RECONNECTING';
CONNECTION_STATUS[strophe["e" /* Strophe */].Status.REDIRECT] = 'REDIRECT';
/**
 * @namespace i18n
 */

const i18n = {
  initialize() {},

  /**
   * Overridable string wrapper method which can be used to provide i18n
   * support.
   *
   * The default implementation in @converse/headless simply calls sprintf
   * with the passed in arguments.
   *
   * If you install the full version of Converse, then this method gets
   * overwritten in src/i18n/index.js to return a translated string.
   * @method __
   * @private
   * @memberOf i18n
   * @param { String } str
   */
  __(...args) {
    return Object(sprintf["sprintf"])(...args);
  }

};
/**
 * A private, closured object containing the private api (via {@link _converse.api})
 * as well as private methods and internal data-structures.
 * @global
 * @namespace _converse
 */

const converse_core_converse = {
  log: headless_log,
  CONNECTION_STATUS,
  templates: {},
  promises: {
    'initialized': utils_core.getResolveablePromise()
  },
  STATUS_WEIGHTS: {
    'offline': 6,
    'unavailable': 5,
    'xa': 4,
    'away': 3,
    'dnd': 2,
    'chat': 1,
    // We currently don't differentiate between "chat" and "online"
    'online': 1
  },
  ANONYMOUS: 'anonymous',
  CLOSED: 'closed',
  EXTERNAL: 'external',
  LOGIN: 'login',
  LOGOUT: 'logout',
  OPENED: 'opened',
  PREBIND: 'prebind',

  /**
   * @constant
   * @type { integer }
   */
  STANZA_TIMEOUT: 10000,
  SUCCESS: 'success',
  FAILURE: 'failure',
  // Generated from css/images/user.svg
  DEFAULT_IMAGE_TYPE: 'image/svg+xml',
  DEFAULT_IMAGE: "PD94bWwgdmVyc2lvbj0iMS4wIj8+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiA8cmVjdCB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCIgZmlsbD0iIzU1NSIvPgogPGNpcmNsZSBjeD0iNjQiIGN5PSI0MSIgcj0iMjQiIGZpbGw9IiNmZmYiLz4KIDxwYXRoIGQ9Im0yOC41IDExMiB2LTEyIGMwLTEyIDEwLTI0IDI0LTI0IGgyMyBjMTQgMCAyNCAxMiAyNCAyNCB2MTIiIGZpbGw9IiNmZmYiLz4KPC9zdmc+Cg==",
  TIMEOUTS: {
    // Set as module attr so that we can override in tests.
    PAUSED: 10000,
    INACTIVE: 90000
  },
  // XEP-0085 Chat states
  // https://xmpp.org/extensions/xep-0085.html
  INACTIVE: 'inactive',
  ACTIVE: 'active',
  COMPOSING: 'composing',
  PAUSED: 'paused',
  GONE: 'gone',
  // Chat types
  PRIVATE_CHAT_TYPE: 'chatbox',
  CHATROOMS_TYPE: 'chatroom',
  HEADLINES_TYPE: 'headline',
  CONTROLBOX_TYPE: 'controlbox',
  default_connection_options: {
    'explicitResourceBinding': true
  },
  router: new Router(),
  TimeoutError: TimeoutError,
  isTestEnv: () => {
    return initialization_settings.bosh_service_url === 'montague.lit/http-bind';
  },

  /**
   * Translate the given string based on the current locale.
   * @method __
   * @private
   * @memberOf _converse
   * @param { String } str
   */
  '__': (...args) => i18n.__(...args),

  /**
   * A no-op method which is used to signal to gettext that the passed in string
   * should be included in the pot translation file.
   *
   * In contrast to the double-underscore method, the triple underscore method
   * doesn't actually translate the strings.
   *
   * One reason for this method might be because we're using strings we cannot
   * send to the translation function because they require variable interpolation
   * and we don't yet have the variables at scan time.
   *
   * @method ___
   * @private
   * @memberOf _converse
   * @param { String } str
   */
  '___': str => str
};
converse_core_converse.VERSION_NAME = "v7.0.6";
Object.assign(converse_core_converse, Events); // Make converse pluggable

pluggable.enable(converse_core_converse, '_converse', 'pluggable');
let converse_core_user_settings; // User settings, populated via api.users.settings

let initialization_settings = {}; // Container for settings passed in via converse.initialize

function initSettings(settings) {
  converse_core_converse.settings = {};
  initialization_settings = settings; // Allow only whitelisted settings to be overwritten via converse.initialize

  const allowed_settings = lodash_es_pick(settings, Object.keys(DEFAULT_SETTINGS));
  lodash_es_assignIn(converse_core_converse.settings, DEFAULT_SETTINGS, allowed_settings);
  lodash_es_assignIn(converse_core_converse, DEFAULT_SETTINGS, allowed_settings); // FIXME: remove
}

function initUserSettings() {
  var _user_settings;

  if (!converse_core_converse.bare_jid) {
    const msg = "No JID to fetch user settings for";
    headless_log.error(msg);
    throw Error(msg);
  }

  if (!((_user_settings = converse_core_user_settings) !== null && _user_settings !== void 0 && _user_settings.fetched)) {
    const id = `converse.user-settings.${converse_core_converse.bare_jid}`;
    converse_core_user_settings = new model_Model({
      id
    });
    converse_core_user_settings.browserStorage = createStore(id);
    converse_core_user_settings.fetched = converse_core_user_settings.fetch({
      'promise': true
    });
  }

  return converse_core_user_settings.fetched;
}
/**
 * ### The private API
 *
 * The private API methods are only accessible via the closured {@link _converse}
 * object, which is only available to plugins.
 *
 * These methods are kept private (i.e. not global) because they may return
 * sensitive data which should be kept off-limits to other 3rd-party scripts
 * that might be running in the page.
 *
 * @namespace _converse.api
 * @memberOf _converse
 */


const converse_core_api = converse_core_converse.api = {
  /**
   * This grouping collects API functions related to the XMPP connection.
   *
   * @namespace _converse.api.connection
   * @memberOf _converse.api
   */
  connection: {
    /**
     * @method _converse.api.connection.connected
     * @memberOf _converse.api.connection
     * @returns {boolean} Whether there is an established connection or not.
     */
    connected() {
      var _converse$connection;

      return (converse_core_converse === null || converse_core_converse === void 0 ? void 0 : (_converse$connection = converse_core_converse.connection) === null || _converse$connection === void 0 ? void 0 : _converse$connection.connected) && true;
    },

    /**
     * Terminates the connection.
     *
     * @method _converse.api.connection.disconnectkjjjkk
     * @memberOf _converse.api.connection
     */
    disconnect() {
      if (converse_core_converse.connection) {
        converse_core_converse.connection.disconnect();
      }
    },

    /**
     * Can be called once the XMPP connection has dropped and we want
     * to attempt reconnection.
     * Only needs to be called once, if reconnect fails Converse will
     * attempt to reconnect every two seconds, alternating between BOSH and
     * Websocket if URLs for both were provided.
     * @method reconnect
     * @memberOf _converse.api.connection
     */
    async reconnect() {
      const conn_status = converse_core_converse.connfeedback.get('connection_status');

      if (converse_core_api.settings.get("authentication") === converse_core_converse.ANONYMOUS) {
        await tearDown();
        await clearSession();
      }

      if (conn_status === strophe["e" /* Strophe */].Status.CONNFAIL) {
        // When reconnecting with a new transport, we call setUserJID
        // so that a new resource is generated, to avoid multiple
        // server-side sessions with the same resource.
        //
        // We also call `_proto._doDisconnect` so that connection event handlers
        // for the old transport are removed.
        if (converse_core_api.connection.isType('websocket') && converse_core_api.settings.get('bosh_service_url')) {
          await converse_core_converse.setUserJID(converse_core_converse.bare_jid);

          converse_core_converse.connection._proto._doDisconnect();

          converse_core_converse.connection._proto = new strophe["e" /* Strophe */].Bosh(converse_core_converse.connection);
          converse_core_converse.connection.service = converse_core_api.settings.get('bosh_service_url');
        } else if (converse_core_api.connection.isType('bosh') && converse_core_api.settings.get("websocket_url")) {
          if (converse_core_api.settings.get("authentication") === converse_core_converse.ANONYMOUS) {
            // When reconnecting anonymously, we need to connect with only
            // the domain, not the full JID that we had in our previous
            // (now failed) session.
            await converse_core_converse.setUserJID(converse_core_api.settings.get("jid"));
          } else {
            await converse_core_converse.setUserJID(converse_core_converse.bare_jid);
          }

          converse_core_converse.connection._proto._doDisconnect();

          converse_core_converse.connection._proto = new strophe["e" /* Strophe */].Websocket(converse_core_converse.connection);
          converse_core_converse.connection.service = converse_core_api.settings.get("websocket_url");
        }
      } else if (conn_status === strophe["e" /* Strophe */].Status.AUTHFAIL && converse_core_api.settings.get("authentication") === converse_core_converse.ANONYMOUS) {
        // When reconnecting anonymously, we need to connect with only
        // the domain, not the full JID that we had in our previous
        // (now failed) session.
        await converse_core_converse.setUserJID(converse_core_api.settings.get("jid"));
      }

      if (converse_core_converse.connection.reconnecting) {
        converse_core_converse.connection.debouncedReconnect();
      } else {
        return converse_core_converse.connection.reconnect();
      }
    },

    /**
     * Utility method to determine the type of connection we have
     * @method isType
     * @memberOf _converse.api.connection
     * @returns {boolean}
     */
    isType(type) {
      return converse_core_converse.connection.isType(type);
    }

  },

  /**
   * Lets you trigger events, which can be listened to via
   * {@link _converse.api.listen.on} or {@link _converse.api.listen.once}
   * (see [_converse.api.listen](http://localhost:8000/docs/html/api/-_converse.api.listen.html)).
   *
   * Some events also double as promises and can be waited on via {@link _converse.api.waitUntil}.
   *
   * @method _converse.api.trigger
   * @param {string} name - The event name
   * @param {...any} [argument] - Argument to be passed to the event handler
   * @param {object} [options]
   * @param {boolean} [options.synchronous] - Whether the event is synchronous or not.
   *  When a synchronous event is fired, a promise will be returned
   *  by {@link _converse.api.trigger} which resolves once all the
   *  event handlers' promises have been resolved.
   */
  async trigger(name) {
    if (!converse_core_converse._events) {
      return;
    }

    const args = Array.from(arguments);
    const options = args.pop();

    if (options && options.synchronous) {
      const events = converse_core_converse._events[name] || [];
      await Promise.all(events.map(e => e.callback.apply(e.ctx, args.splice(1))));
    } else {
      converse_core_converse.trigger.apply(converse_core_converse, arguments);
    }

    const promise = converse_core_converse.promises[name];

    if (promise !== undefined) {
      promise.resolve();
    }
  },

  /**
   * Triggers a hook which can be intercepted by registered listeners via
   * {@link _converse.api.listen.on} or {@link _converse.api.listen.once}.
   * (see [_converse.api.listen](http://localhost:8000/docs/html/api/-_converse.api.listen.html)).
   * A hook is a special kind of event which allows you to intercept a data
   * structure in order to modify it, before passing it back.
   * @async
   * @param {string} name - The hook name
   * @param {...any} context - The context to which the hook applies (could be for example, a {@link _converse.ChatBox)).
   * @param {...any} data - The data structure to be intercepted and modified by the hook listeners.
   * @returns {Promise<any>} - A promise that resolves with the modified data structure.
   */
  hook(name, context, data) {
    const events = converse_core_converse._events[name] || [];

    if (events.length) {
      // Create a chain of promises, with each one feeding its output to
      // the next. The first input is a promise with the original data
      // sent to this hook.
      const o = events.reduce((o, e) => o.then(d => e.callback(context, d)), Promise.resolve(data));
      o.catch(e => {
        headless_log.error(e);
        throw e;
      });
      return o;
    } else {
      return data;
    }
  },

  /**
   * This grouping collects API functions related to the current logged in user.
   *
   * @namespace _converse.api.user
   * @memberOf _converse.api
   */
  user: {
    /**
     * @method _converse.api.user.jid
     * @returns {string} The current user's full JID (Jabber ID)
     * @example _converse.api.user.jid())
     */
    jid() {
      return converse_core_converse.connection.jid;
    },

    /**
     * Logs the user in.
     *
     * If called without any parameters, Converse will try
     * to log the user in by calling the `prebind_url` or `credentials_url` depending
     * on whether prebinding is used or not.
     *
     * @method _converse.api.user.login
     * @param {string} [jid]
     * @param {string} [password]
     * @param {boolean} [automatic=false] - An internally used flag that indicates whether
     *  this method was called automatically once the connection has been
     *  initialized. It's used together with the `auto_login` configuration flag
     *  to determine whether Converse should try to log the user in if it
     *  fails to restore a previous auth'd session.
     *  @returns  {void}
     */
    async login(jid, password, automatic = false) {
      var _converse$connection2, _api$settings$get;

      jid = jid || converse_core_converse.jid;

      if (!((_converse$connection2 = converse_core_converse.connection) !== null && _converse$connection2 !== void 0 && _converse$connection2.jid) || jid && !utils_core.isSameDomain(converse_core_converse.connection.jid, jid)) {
        await converse_core_converse.initConnection();
      }

      if ((_api$settings$get = converse_core_api.settings.get("connection_options")) !== null && _api$settings$get !== void 0 && _api$settings$get.worker && (await converse_core_converse.connection.restoreWorkerSession())) {
        return;
      }

      if (jid) {
        jid = await converse_core_converse.setUserJID(jid);
      } // See whether there is a BOSH session to re-attach to


      const bosh_plugin = converse_core_converse.pluggable.plugins['converse-bosh'];

      if (bosh_plugin && bosh_plugin.enabled()) {
        if (await converse_core_converse.restoreBOSHSession()) {
          return;
        } else if (converse_core_api.settings.get("authentication") === converse_core_converse.PREBIND && (!automatic || converse_core_api.settings.get("auto_login"))) {
          return converse_core_converse.startNewPreboundBOSHSession();
        }
      }

      password = password || converse_core_api.settings.get("password");
      const credentials = jid && password ? {
        jid,
        password
      } : null;
      attemptNonPreboundSession(credentials, automatic);
    },

    /**
     * Logs the user out of the current XMPP session.
     * @method _converse.api.user.logout
     * @example _converse.api.user.logout();
     */
    logout() {
      const promise = utils_core.getResolveablePromise();

      const complete = () => {
        // Recreate all the promises
        Object.keys(converse_core_converse.promises).forEach(replacePromise);
        delete converse_core_converse.jid;
        /**
         * Triggered once the user has logged out.
         * @event _converse#logout
         */

        converse_core_api.trigger('logout');
        promise.resolve();
      };

      converse_core_converse.connection.setDisconnectionCause(converse_core_converse.LOGOUT, undefined, true);

      if (converse_core_converse.connection !== undefined) {
        converse_core_api.listen.once('disconnected', () => complete());

        converse_core_converse.connection.disconnect();
      } else {
        complete();
      }

      return promise;
    },

    /**
     * API for accessing and setting user settings. User settings are
     * different from the application settings from {@link _converse.api.settings}
     * because they are per-user and set via user action.
     * @namespace _converse.api.user.settings
     * @memberOf _converse.api.user
     */
    settings: {
      /**
       * Returns the user settings model. Useful when you want to listen for change events.
       * @method _converse.api.user.settings.getModel
       * @returns {Promise<Model>}
       * @example const settings = await _converse.api.user.settings.getModel();
       */
      async getModel() {
        await initUserSettings();
        return converse_core_user_settings;
      },

      /**
       * Get the value of a particular user setting.
       * @method _converse.api.user.settings.get
       * @param {String} key - The setting name
       * @param {*} fallback - An optional fallback value if the user setting is undefined
       * @returns {Promise} Promise which resolves with the value of the particular configuration setting.
       * @example _converse.api.user.settings.get("foo");
       */
      async get(key, fallback) {
        await initUserSettings();
        return converse_core_user_settings.get(key) === undefined ? fallback : converse_core_user_settings.get(key);
      },

      /**
       * Set one or many user settings.
       * @async
       * @method _converse.api.user.settings.set
       * @param {Object} [settings] An object containing configuration settings.
       * @param {string} [key] Alternatively to passing in an object, you can pass in a key and a value.
       * @param {string} [value]
       * @example _converse.api.user.settings.set("foo", "bar");
       * @example
       * _converse.api.user.settings.set({
       *     "foo": "bar",
       *     "baz": "buz"
       * });
       */
      async set(key, val) {
        await initUserSettings();

        if (lodash_es_isObject(key)) {
          return converse_core_user_settings.save(key, {
            'promise': true
          });
        } else {
          const o = {};
          o[key] = val;
          return converse_core_user_settings.save(o, {
            'promise': true
          });
        }
      },

      /**
       * Clears all the user settings
       * @method _converse.api.user.settings.clear
       */
      async clear() {
        await initUserSettings();
        converse_core_user_settings.clear();
      }

    }
  },

  /**
   * This grouping allows access to the
   * [configuration settings](/docs/html/configuration.html#configuration-settings)
   * of Converse.
   *
   * @namespace _converse.api.settings
   * @memberOf _converse.api
   */
  settings: {
    /**
     * Allows new configuration settings to be specified, or new default values for
     * existing configuration settings to be specified.
     *
     * Note, calling this method *after* converse.initialize has been
     * called will *not* change the initialization settings provided via
     * `converse.initialize`.
     *
     * @method _converse.api.settings.extend
     * @param {object} settings The configuration settings
     * @example
     * _converse.api.settings.extend({
     *    'enable_foo': true
     * });
     *
     * // The user can then override the default value of the configuration setting when
     * // calling `converse.initialize`.
     * converse.initialize({
     *     'enable_foo': false
     * });
     */
    extend(settings) {
      utils_core.merge(DEFAULT_SETTINGS, settings); // When updating the settings, we need to avoid overwriting the
      // initialization_settings (i.e. the settings passed in via converse.initialize).

      const allowed_keys = Object.keys(lodash_es_pick(settings, Object.keys(DEFAULT_SETTINGS)));
      const allowed_site_settings = lodash_es_pick(initialization_settings, allowed_keys);
      const updated_settings = lodash_es_assignIn(lodash_es_pick(settings, allowed_keys), allowed_site_settings);
      utils_core.merge(converse_core_converse.settings, updated_settings);
      utils_core.merge(converse_core_converse, updated_settings); // FIXME: remove
    },

    update(settings) {
      headless_log.warn("The api.settings.update method has been deprecated and will be removed. " + "Please use api.settings.extend instead.");
      return this.extend(settings);
    },

    /**
     * @method _converse.api.settings.get
     * @returns {*} Value of the particular configuration setting.
     * @example _converse.api.settings.get("play_sounds");
     */
    get(key) {
      if (Object.keys(DEFAULT_SETTINGS).includes(key)) {
        return converse_core_converse[key];
      }
    },

    /**
     * Set one or many configuration settings.
     *
     * Note, this is not an alternative to calling {@link converse.initialize}, which still needs
     * to be called. Generally, you'd use this method after Converse is already
     * running and you want to change the configuration on-the-fly.
     *
     * @method _converse.api.settings.set
     * @param {Object} [settings] An object containing configuration settings.
     * @param {string} [key] Alternatively to passing in an object, you can pass in a key and a value.
     * @param {string} [value]
     * @example _converse.api.settings.set("play_sounds", true);
     * @example
     * _converse.api.settings.set({
     *     "play_sounds": true,
     *     "hide_offline_users": true
     * });
     */
    set(key, val) {
      const o = {};

      if (lodash_es_isObject(key)) {
        lodash_es_assignIn(converse_core_converse, lodash_es_pick(key, Object.keys(DEFAULT_SETTINGS)));
        lodash_es_assignIn(converse_core_converse.settings, lodash_es_pick(key, Object.keys(DEFAULT_SETTINGS)));
      } else if (typeof key === 'string') {
        o[key] = val;
        lodash_es_assignIn(converse_core_converse, lodash_es_pick(o, Object.keys(DEFAULT_SETTINGS)));
        lodash_es_assignIn(converse_core_converse.settings, lodash_es_pick(o, Object.keys(DEFAULT_SETTINGS)));
      }
    }

  },

  /**
   * Converse and its plugins trigger various events which you can listen to via the
   * {@link _converse.api.listen} namespace.
   *
   * Some of these events are also available as [ES2015 Promises](http://es6-features.org/#PromiseUsage)
   * although not all of them could logically act as promises, since some events
   * might be fired multpile times whereas promises are to be resolved (or
   * rejected) only once.
   *
   * Events which are also promises include:
   *
   * * [cachedRoster](/docs/html/events.html#cachedroster)
   * * [chatBoxesFetched](/docs/html/events.html#chatBoxesFetched)
   * * [pluginsInitialized](/docs/html/events.html#pluginsInitialized)
   * * [roster](/docs/html/events.html#roster)
   * * [rosterContactsFetched](/docs/html/events.html#rosterContactsFetched)
   * * [rosterGroupsFetched](/docs/html/events.html#rosterGroupsFetched)
   * * [rosterInitialized](/docs/html/events.html#rosterInitialized)
   * * [roomsPanelRendered](/docs/html/events.html#roomsPanelRendered)
   *
   * The various plugins might also provide promises, and they do this by using the
   * `promises.add` api method.
   *
   * @namespace _converse.api.promises
   * @memberOf _converse.api
   */
  promises: {
    /**
     * By calling `promises.add`, a new [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
     * is made available for other code or plugins to depend on via the
     * {@link _converse.api.waitUntil} method.
     *
     * Generally, it's the responsibility of the plugin which adds the promise to
     * also resolve it.
     *
     * This is done by calling {@link _converse.api.trigger}, which not only resolves the
     * promise, but also emits an event with the same name (which can be listened to
     * via {@link _converse.api.listen}).
     *
     * @method _converse.api.promises.add
     * @param {string|array} [name|names] The name or an array of names for the promise(s) to be added
     * @param {boolean} [replace=true] Whether this promise should be replaced with a new one when the user logs out.
     * @example _converse.api.promises.add('foo-completed');
     */
    add(promises, replace = true) {
      promises = Array.isArray(promises) ? promises : [promises];
      promises.forEach(name => {
        const promise = utils_core.getResolveablePromise();
        promise.replace = replace;
        converse_core_converse.promises[name] = promise;
      });
    }

  },

  /**
   * Converse emits events to which you can subscribe to.
   *
   * The `listen` namespace exposes methods for creating event listeners
   * (aka handlers) for these events.
   *
   * @namespace _converse.api.listen
   * @memberOf _converse
   */
  listen: {
    /**
     * Lets you listen to an event exactly once.
     * @method _converse.api.listen.once
     * @param {string} name The event's name
     * @param {function} callback The callback method to be called when the event is emitted.
     * @param {object} [context] The value of the `this` parameter for the callback.
     * @example _converse.api.listen.once('message', function (messageXML) { ... });
     */
    once: converse_core_converse.once.bind(converse_core_converse),

    /**
     * Lets you subscribe to an event.
     * Every time the event fires, the callback method specified by `callback` will be called.
     * @method _converse.api.listen.on
     * @param {string} name The event's name
     * @param {function} callback The callback method to be called when the event is emitted.
     * @param {object} [context] The value of the `this` parameter for the callback.
     * @example _converse.api.listen.on('message', function (messageXML) { ... });
     */
    on: converse_core_converse.on.bind(converse_core_converse),

    /**
     * To stop listening to an event, you can use the `not` method.
     * @method _converse.api.listen.not
     * @param {string} name The event's name
     * @param {function} callback The callback method that is to no longer be called when the event fires
     * @example _converse.api.listen.not('message', function (messageXML);
     */
    not: converse_core_converse.off.bind(converse_core_converse),

    /**
     * Subscribe to an incoming stanza
     * Every a matched stanza is received, the callback method specified by
     * `callback` will be called.
     * @method _converse.api.listen.stanza
     * @param {string} name The stanza's name
     * @param {object} options Matching options (e.g. 'ns' for namespace, 'type' for stanza type, also 'id' and 'from');
     * @param {function} handler The callback method to be called when the stanza appears
     */
    stanza(name, options, handler) {
      if (lodash_es_isFunction(options)) {
        handler = options;
        options = {};
      } else {
        options = options || {};
      }

      converse_core_converse.connection.addHandler(handler, options.ns, name, options.type, options.id, options.from, options);
    }

  },

  /**
   * Wait until a promise is resolved or until the passed in function returns
   * a truthy value.
   * @method _converse.api.waitUntil
   * @param {string|function} condition - The name of the promise to wait for,
   * or a function which should eventually return a truthy value.
   * @returns {Promise}
   */
  waitUntil(condition) {
    if (lodash_es_isFunction(condition)) {
      return utils_core.waitUntil(condition);
    } else {
      const promise = converse_core_converse.promises[condition];

      if (promise === undefined) {
        return null;
      }

      return promise;
    }
  },

  /**
   * Allows you to send XML stanzas.
   * @method _converse.api.send
   * @param {XMLElement} stanza
   * @return {void}
   * @example
   * const msg = converse.env.$msg({
   *     'from': 'juliet@example.com/balcony',
   *     'to': 'romeo@example.net',
   *     'type':'chat'
   * });
   * _converse.api.send(msg);
   */
  send(stanza) {
    if (!converse_core_api.connection.connected()) {
      headless_log.warn("Not sending stanza because we're not connected!");
      headless_log.warn(strophe["e" /* Strophe */].serialize(stanza));
      return;
    }

    if (typeof stanza === 'string') {
      stanza = utils_core.toStanza(stanza);
    }

    if (stanza.tagName === 'iq') {
      return converse_core_api.sendIQ(stanza);
    } else {
      converse_core_converse.connection.send(stanza);

      converse_core_api.trigger('send', stanza);
    }
  },

  /**
   * Send an IQ stanza
   * @method _converse.api.sendIQ
   * @param {XMLElement} stanza
   * @param {Integer} [timeout=_converse.STANZA_TIMEOUT]
   * @param {Boolean} [reject=true] - Whether an error IQ should cause the promise
   *  to be rejected. If `false`, the promise will resolve instead of being rejected.
   * @returns {Promise} A promise which resolves (or potentially rejected) once we
   *  receive a `result` or `error` stanza or once a timeout is reached.
   *  If the IQ stanza being sent is of type `result` or `error`, there's
   *  nothing to wait for, so an already resolved promise is returned.
   */
  sendIQ(stanza, timeout = converse_core_converse.STANZA_TIMEOUT, reject = true) {
    var _stanza$nodeTree, _stanza;

    let promise;
    stanza = (_stanza$nodeTree = (_stanza = stanza) === null || _stanza === void 0 ? void 0 : _stanza.nodeTree) !== null && _stanza$nodeTree !== void 0 ? _stanza$nodeTree : stanza;

    if (['get', 'set'].includes(stanza.getAttribute('type'))) {
      timeout = timeout || converse_core_converse.STANZA_TIMEOUT;

      if (reject) {
        promise = new Promise((resolve, reject) => converse_core_converse.connection.sendIQ(stanza, resolve, reject, timeout));
        promise.catch(e => {
          if (e === null) {
            throw new TimeoutError(`Timeout error after ${timeout}ms for the following IQ stanza: ${strophe["e" /* Strophe */].serialize(stanza)}`);
          }
        });
      } else {
        promise = new Promise(resolve => converse_core_converse.connection.sendIQ(stanza, resolve, resolve, timeout));
      }
    } else {
      converse_core_converse.connection.sendIQ(stanza);

      promise = Promise.resolve();
    }

    converse_core_api.trigger('send', stanza);
    return promise;
  }

};

function replacePromise(name) {
  const existing_promise = converse_core_converse.promises[name];

  if (!existing_promise) {
    throw new Error(`Tried to replace non-existing promise: ${name}`);
  }

  if (existing_promise.replace) {
    const promise = utils_core.getResolveablePromise();
    promise.replace = existing_promise.replace;
    converse_core_converse.promises[name] = promise;
  } else {
    headless_log.debug(`Not replacing promise "${name}"`);
  }
}

converse_core_converse.isUniView = function () {
  /* We distinguish between UniView and MultiView instances.
   *
   * UniView means that only one chat is visible, even though there might be multiple ongoing chats.
   * MultiView means that multiple chats may be visible simultaneously.
   */
  return ['mobile', 'fullscreen', 'embedded'].includes(converse_core_api.settings.get("view_mode"));
};

async function initSessionStorage() {
  await src_storage.sessionStorageInitialized;
  converse_core_converse.storage = {
    'session': src_storage.localForage.createInstance({
      'name': converse_core_converse.isTestEnv() ? 'converse-test-session' : 'converse-session',
      'description': 'sessionStorage instance',
      'driver': ['sessionStorageWrapper']
    })
  };
}

function initPersistentStorage() {
  if (converse_core_api.settings.get('persistent_store') === 'sessionStorage') {
    return;
  } else if (converse_core_converse.api.settings.get("persistent_store") === 'BrowserExtLocal') {
    src_storage.localForage.defineDriver(local_default.a).then(() => src_storage.localForage.setDriver('webExtensionLocalStorage'));
    converse_core_converse.storage['persistent'] = src_storage.localForage;
    return;
  } else if (converse_core_converse.api.settings.get("persistent_store") === 'BrowserExtSync') {
    src_storage.localForage.defineDriver(sync_default.a).then(() => src_storage.localForage.setDriver('webExtensionSyncStorage'));
    converse_core_converse.storage['persistent'] = src_storage.localForage;
    return;
  }

  const config = {
    'name': converse_core_converse.isTestEnv() ? 'converse-test-persistent' : 'converse-persistent',
    'storeName': converse_core_converse.bare_jid
  };

  if (converse_core_converse.api.settings.get("persistent_store") === 'localStorage') {
    config['description'] = 'localStorage instance';
    config['driver'] = [src_storage.localForage.LOCALSTORAGE];
  } else if (converse_core_converse.api.settings.get("persistent_store") === 'IndexedDB') {
    config['description'] = 'indexedDB instance';
    config['driver'] = [src_storage.localForage.INDEXEDDB];
  }

  converse_core_converse.storage['persistent'] = src_storage.localForage.createInstance(config);
}

converse_core_converse.getDefaultStore = function () {
  if (converse_core_converse.config.get('trusted')) {
    const is_non_persistent = converse_core_api.settings.get('persistent_store') === 'sessionStorage';
    return is_non_persistent ? 'session' : 'persistent';
  } else {
    return 'session';
  }
};

function createStore(id, storage) {
  const s = converse_core_converse.storage[storage || converse_core_converse.getDefaultStore()];

  return new src_storage(id, s);
}

converse_core_converse.createStore = createStore;

function initPlugins() {
  // If initialize gets called a second time (e.g. during tests), then we
  // need to re-apply all plugins (for a new converse instance), and we
  // therefore need to clear this array that prevents plugins from being
  // initialized twice.
  // If initialize is called for the first time, then this array is empty
  // in any case.
  converse_core_converse.pluggable.initialized_plugins = [];
  const whitelist = CORE_PLUGINS.concat(converse_core_converse.api.settings.get("whitelisted_plugins"));

  if (converse_core_converse.api.settings.get("singleton")) {
    ['converse-bookmarks', 'converse-controlbox', 'converse-headline', 'converse-register'].forEach(name => converse_core_converse.api.settings.get("blacklisted_plugins").push(name));
  }

  converse_core_converse.pluggable.initializePlugins({
    '_converse': converse_core_converse
  }, whitelist, converse_core_converse.api.settings.get("blacklisted_plugins"));
  /**
   * Triggered once all plugins have been initialized. This is a useful event if you want to
   * register event handlers but would like your own handlers to be overridable by
   * plugins. In that case, you need to first wait until all plugins have been
   * initialized, so that their overrides are active. One example where this is used
   * is in [converse-notifications.js](https://github.com/jcbrand/converse.js/blob/master/src/converse-notification.js)`.
   *
   * Also available as an [ES2015 Promise](http://es6-features.org/#PromiseUsage)
   * which can be listened to with `_converse.api.waitUntil`.
   *
   * @event _converse#pluginsInitialized
   * @memberOf _converse
   * @example _converse.api.listen.on('pluginsInitialized', () => { ... });
   */


  converse_core_converse.api.trigger('pluginsInitialized');
}

async function initClientConfig() {
  /* The client config refers to configuration of the client which is
   * independent of any particular user.
   * What this means is that config values need to persist across
   * user sessions.
   */
  const id = 'converse.client-config';
  converse_core_converse.config = new model_Model({
    id,
    'trusted': true
  });
  converse_core_converse.config.browserStorage = createStore(id, "session");
  await new Promise(r => converse_core_converse.config.fetch({
    'success': r,
    'error': r
  }));
  /**
   * Triggered once the XMPP-client configuration has been initialized.
   * The client configuration is independent of any particular and its values
   * persist across user sessions.
   *
   * @event _converse#clientConfigInitialized
   * @example
   * _converse.api.listen.on('clientConfigInitialized', () => { ... });
   */

  converse_core_converse.api.trigger('clientConfigInitialized');
}

async function tearDown() {
  await converse_core_converse.api.trigger('beforeTearDown', {
    'synchronous': true
  });
  window.removeEventListener('click', converse_core_converse.onUserActivity);
  window.removeEventListener('focus', converse_core_converse.onUserActivity);
  window.removeEventListener('keypress', converse_core_converse.onUserActivity);
  window.removeEventListener('mousemove', converse_core_converse.onUserActivity);
  window.removeEventListener(converse_core_converse.unloadevent, converse_core_converse.onUserActivity);
  window.clearInterval(converse_core_converse.everySecondTrigger);

  converse_core_converse.api.trigger('afterTearDown');

  return converse_core_converse;
}

async function attemptNonPreboundSession(credentials, automatic) {
  const {
    api
  } = converse_core_converse;

  if (api.settings.get("authentication") === converse_core_converse.LOGIN) {
    // XXX: If EITHER ``keepalive`` or ``auto_login`` is ``true`` and
    // ``authentication`` is set to ``login``, then Converse will try to log the user in,
    // since we don't have a way to distinguish between wether we're
    // restoring a previous session (``keepalive``) or whether we're
    // automatically setting up a new session (``auto_login``).
    // So we can't do the check (!automatic || _converse.api.settings.get("auto_login")) here.
    if (credentials) {
      connect(credentials);
    } else if (converse_core_converse.api.settings.get("credentials_url")) {
      // We give credentials_url preference, because
      // _converse.connection.pass might be an expired token.
      connect(await getLoginCredentials());
    } else if (converse_core_converse.jid && (converse_core_converse.api.settings.get("password") || converse_core_converse.connection.pass)) {
      connect();
    } else if (!converse_core_converse.isTestEnv() && 'credentials' in navigator) {
      connect(await getLoginCredentialsFromBrowser());
    } else {
      !converse_core_converse.isTestEnv() && headless_log.warn("attemptNonPreboundSession: Couldn't find credentials to log in with");
    }
  } else if ([converse_core_converse.ANONYMOUS, converse_core_converse.EXTERNAL].includes(converse_core_converse.api.settings.get("authentication")) && (!automatic || converse_core_converse.api.settings.get("auto_login"))) {
    connect();
  }
}

function connect(credentials) {
  if ([converse_core_converse.ANONYMOUS, converse_core_converse.EXTERNAL].includes(converse_core_converse.api.settings.get("authentication"))) {
    if (!converse_core_converse.jid) {
      throw new Error("Config Error: when using anonymous login " + "you need to provide the server's domain via the 'jid' option. " + "Either when calling converse.initialize, or when calling " + "_converse.api.user.login.");
    }

    if (!converse_core_converse.connection.reconnecting) {
      converse_core_converse.connection.reset();
    }

    converse_core_converse.connection.connect(converse_core_converse.jid.toLowerCase());
  } else if (converse_core_converse.api.settings.get("authentication") === converse_core_converse.LOGIN) {
    var _converse$connection3;

    const password = credentials ? credentials.password : ((_converse$connection3 = converse_core_converse.connection) === null || _converse$connection3 === void 0 ? void 0 : _converse$connection3.pass) || converse_core_converse.api.settings.get("password");

    if (!password) {
      if (converse_core_converse.api.settings.get("auto_login")) {
        throw new Error("autoLogin: If you use auto_login and " + "authentication='login' then you also need to provide a password.");
      }

      converse_core_converse.connection.setDisconnectionCause(strophe["e" /* Strophe */].Status.AUTHFAIL, undefined, true);

      converse_core_converse.api.connection.disconnect();

      return;
    }

    if (!converse_core_converse.connection.reconnecting) {
      converse_core_converse.connection.reset();
    }

    converse_core_converse.connection.connect(converse_core_converse.jid, password);
  }
}

converse_core_converse.shouldClearCache = () => !converse_core_converse.config.get('trusted') || converse_core_api.settings.get('clear_cache_on_logout') || converse_core_converse.isTestEnv();

function clearSession() {
  var _converse$session;

  (_converse$session = converse_core_converse.session) === null || _converse$session === void 0 ? void 0 : _converse$session.destroy();
  delete converse_core_converse.session;
  converse_core_converse.shouldClearCache() && converse_core_converse.api.user.settings.clear();
  /**
   * Synchronouse event triggered once the user session has been cleared,
   * for example when the user has logged out or when Converse has
   * disconnected for some other reason.
   * @event _converse#clearSession
   */

  return converse_core_converse.api.trigger('clearSession', {
    'synchronous': true
  });
}

converse_core_converse.initConnection = function () {
  const api = converse_core_converse.api;

  if (!api.settings.get('bosh_service_url')) {
    if (api.settings.get("authentication") === converse_core_converse.PREBIND) {
      throw new Error("authentication is set to 'prebind' but we don't have a BOSH connection");
    }

    if (!api.settings.get("websocket_url")) {
      throw new Error("initConnection: you must supply a value for either the bosh_service_url or websocket_url or both.");
    }
  }

  const XMPPConnection = converse_core_converse.isTestEnv() ? connection_MockConnection : connection_Connection;

  if (('WebSocket' in window || 'MozWebSocket' in window) && api.settings.get("websocket_url")) {
    converse_core_converse.connection = new XMPPConnection(api.settings.get("websocket_url"), Object.assign(converse_core_converse.default_connection_options, api.settings.get("connection_options")));
  } else if (api.settings.get('bosh_service_url')) {
    converse_core_converse.connection = new XMPPConnection(api.settings.get('bosh_service_url'), Object.assign(converse_core_converse.default_connection_options, api.settings.get("connection_options"), {
      'keepalive': api.settings.get("keepalive")
    }));
  } else {
    throw new Error("initConnection: this browser does not support " + "websockets and bosh_service_url wasn't specified.");
  }

  setUpXMLLogging();
  /**
   * Triggered once the `Connection` constructor has been initialized, which
   * will be responsible for managing the connection to the XMPP server.
   *
   * @event _converse#connectionInitialized
   */

  api.trigger('connectionInitialized');
};

async function initSession(jid) {
  var _converse$session2;

  const is_shared_session = converse_core_api.settings.get('connection_options').worker;
  const bare_jid = strophe["e" /* Strophe */].getBareJidFromJid(jid).toLowerCase();
  const id = `converse.session-${bare_jid}`;

  if (((_converse$session2 = converse_core_converse.session) === null || _converse$session2 === void 0 ? void 0 : _converse$session2.get('id')) !== id) {
    converse_core_converse.session = new model_Model({
      id
    });
    converse_core_converse.session.browserStorage = createStore(id, is_shared_session ? "persistent" : "session");
    await new Promise(r => converse_core_converse.session.fetch({
      'success': r,
      'error': r
    }));

    if (!is_shared_session && converse_core_converse.session.get('active')) {
      // If the `active` flag is set, it means this tab was cloned from
      // another (e.g. via middle-click), and its session data was copied over.
      converse_core_converse.session.clear();

      converse_core_converse.session.save({
        id
      });
    }

    saveJIDtoSession(jid);
    initPersistentStorage();
    /**
     * Triggered once the user's session has been initialized. The session is a
     * cache which stores information about the user's current session.
     * @event _converse#userSessionInitialized
     * @memberOf _converse
     */

    converse_core_converse.api.trigger('userSessionInitialized');
  } else {
    saveJIDtoSession(jid);
  }
}

function saveJIDtoSession(jid) {
  jid = converse_core_converse.session.get('jid') || jid;

  if (converse_core_converse.api.settings.get("authentication") !== converse_core_converse.ANONYMOUS && !strophe["e" /* Strophe */].getResourceFromJid(jid)) {
    jid = jid.toLowerCase() + connection_Connection.generateResource();
  }

  converse_core_converse.jid = jid;
  converse_core_converse.bare_jid = strophe["e" /* Strophe */].getBareJidFromJid(jid);
  converse_core_converse.resource = strophe["e" /* Strophe */].getResourceFromJid(jid);
  converse_core_converse.domain = strophe["e" /* Strophe */].getDomainFromJid(jid);

  converse_core_converse.session.save({
    'jid': jid,
    'bare_jid': converse_core_converse.bare_jid,
    'resource': converse_core_converse.resource,
    'domain': converse_core_converse.domain,
    // We use the `active` flag to determine whether we should use the values from sessionStorage.
    // When "cloning" a tab (e.g. via middle-click), the `active` flag will be set and we'll create
    // a new empty user session, otherwise it'll be false and we can re-use the user session.
    'active': true
  }); // Set JID on the connection object so that when we call `connection.bind`
  // the new resource is found by Strophe.js and sent to the XMPP server.


  converse_core_converse.connection.jid = jid;
}
/**
 * Stores the passed in JID for the current user, potentially creating a
 * resource if the JID is bare.
 *
 * Given that we can only create an XMPP connection if we know the domain of
 * the server connect to and we only know this once we know the JID, we also
 * call {@link _converse.initConnection } (if necessary) to make sure that the
 * connection is set up.
 *
 * @method _converse#setUserJID
 * @emits _converse#setUserJID
 * @params { String } jid
 */


converse_core_converse.setUserJID = async function (jid) {
  await initSession(jid);
  /**
   * Triggered whenever the user's JID has been updated
   * @event _converse#setUserJID
   */

  converse_core_converse.api.trigger('setUserJID');

  return jid;
};

function setUpXMLLogging() {
  const lmap = {};
  lmap[strophe["e" /* Strophe */].LogLevel.DEBUG] = 'debug';
  lmap[strophe["e" /* Strophe */].LogLevel.INFO] = 'info';
  lmap[strophe["e" /* Strophe */].LogLevel.WARN] = 'warn';
  lmap[strophe["e" /* Strophe */].LogLevel.ERROR] = 'error';
  lmap[strophe["e" /* Strophe */].LogLevel.FATAL] = 'fatal';

  strophe["e" /* Strophe */].log = (level, msg) => headless_log.log(msg, lmap[level]);

  strophe["e" /* Strophe */].error = msg => headless_log.error(msg);

  converse_core_converse.connection.xmlInput = body => headless_log.debug(body.outerHTML, 'color: darkgoldenrod');

  converse_core_converse.connection.xmlOutput = body => headless_log.debug(body.outerHTML, 'color: darkcyan');
}

async function getLoginCredentials() {
  let credentials;
  let wait = 0;

  while (!credentials) {
    try {
      credentials = await fetchLoginCredentials(wait); // eslint-disable-line no-await-in-loop
    } catch (e) {
      headless_log.error('Could not fetch login credentials');
      headless_log.error(e);
    } // If unsuccessful, we wait 2 seconds between subsequent attempts to
    // fetch the credentials.


    wait = 2000;
  }

  return credentials;
}

async function getLoginCredentialsFromBrowser() {
  try {
    const creds = await navigator.credentials.get({
      'password': true
    });

    if (creds && creds.type == 'password' && utils_core.isValidJID(creds.id)) {
      await converse_core_converse.setUserJID(creds.id);
      return {
        'jid': creds.id,
        'password': creds.password
      };
    }
  } catch (e) {
    headless_log.error(e);
  }
} // Make sure everything is reset in case this is a subsequent call to
// converse.initialize (happens during tests).


async function cleanup() {
  var _converse$connection4;

  await converse_core_api.trigger('cleanup', {
    'synchronous': true
  });

  converse_core_converse.router.history.stop();

  converse_core_unregisterGlobalEventHandlers();
  (_converse$connection4 = converse_core_converse.connection) === null || _converse$connection4 === void 0 ? void 0 : _converse$connection4.reset();

  converse_core_converse.stopListening();

  converse_core_converse.off();

  if (converse_core_converse.promises['initialized'].isResolved) {
    converse_core_api.promises.add('initialized');
  }
}

function fetchLoginCredentials(wait = 0) {
  return new Promise(lodash_es_debounce((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', converse_core_api.settings.get("credentials_url"), true);
    xhr.setRequestHeader('Accept', 'application/json, text/javascript');

    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status < 400) {
        const data = JSON.parse(xhr.responseText);

        converse_core_converse.setUserJID(data.jid).then(() => {
          resolve({
            jid: data.jid,
            password: data.password
          });
        });
      } else {
        reject(new Error(`${xhr.status}: ${xhr.responseText}`));
      }
    };

    xhr.onerror = reject;
    xhr.send();
  }, wait));
}

converse_core_converse.saveWindowState = function (ev) {
  // XXX: eventually we should be able to just use
  // document.visibilityState (when we drop support for older
  // browsers).
  let state;
  const event_map = {
    'focus': "visible",
    'focusin': "visible",
    'pageshow': "visible",
    'blur': "hidden",
    'focusout': "hidden",
    'pagehide': "hidden"
  };
  ev = ev || document.createEvent('Events');

  if (ev.type in event_map) {
    state = event_map[ev.type];
  } else {
    state = document.hidden ? "hidden" : "visible";
  }

  converse_core_converse.windowState = state;
  /**
      * Triggered when window state has changed.
      * Used to determine when a user left the page and when came back.
      * @event _converse#windowStateChanged
      * @type { object }
      * @property{ string } state - Either "hidden" or "visible"
      * @example _converse.api.listen.on('windowStateChanged', obj => { ... });
      */

  converse_core_api.trigger('windowStateChanged', {
    state
  });
};

function converse_core_registerGlobalEventHandlers() {
  document.addEventListener("visibilitychange", converse_core_converse.saveWindowState);

  converse_core_converse.saveWindowState({
    'type': document.hidden ? "blur" : "focus"
  }); // Set initial state

  /**
   * Called once Converse has registered its global event handlers
   * (for events such as window resize or unload).
   * Plugins can listen to this event as cue to register their own
   * global event handlers.
   * @event _converse#registeredGlobalEventHandlers
   * @example _converse.api.listen.on('registeredGlobalEventHandlers', () => { ... });
   */


  converse_core_api.trigger('registeredGlobalEventHandlers');
}

function converse_core_unregisterGlobalEventHandlers() {
  document.removeEventListener("visibilitychange", converse_core_converse.saveWindowState);
  converse_core_api.trigger('unregisteredGlobalEventHandlers');
}

converse_core_converse.ConnectionFeedback = model_Model.extend({
  defaults: {
    'connection_status': strophe["e" /* Strophe */].Status.DISCONNECTED,
    'message': ''
  },

  initialize() {
    this.on('change', () => converse_core_api.trigger('connfeedback', converse_core_converse.connfeedback));
  }

});

function setUnloadEvent() {
  if ('onpagehide' in window) {
    // Pagehide gets thrown in more cases than unload. Specifically it
    // gets thrown when the page is cached and not just
    // closed/destroyed. It's the only viable event on mobile Safari.
    // https://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/
    converse_core_converse.unloadevent = 'pagehide';
  } else if ('onbeforeunload' in window) {
    converse_core_converse.unloadevent = 'beforeunload';
  } else if ('onunload' in window) {
    converse_core_converse.unloadevent = 'unload';
  }
}

const converse = window.converse || {};
/**
 * ### The Public API
 *
 * This namespace contains public API methods which are are
 * accessible on the global `converse` object.
 * They are public, because any JavaScript in the
 * page can call them. Public methods therefore don’t expose any sensitive
 * or closured data. To do that, you’ll need to create a plugin, which has
 * access to the private API method.
 *
 * @global
 * @namespace converse
 */

Object.assign(converse, {
  CHAT_STATES: ['active', 'composing', 'gone', 'inactive', 'paused'],
  keycodes: {
    TAB: 9,
    ENTER: 13,
    SHIFT: 16,
    CTRL: 17,
    ALT: 18,
    ESCAPE: 27,
    LEFT_ARROW: 37,
    UP_ARROW: 38,
    RIGHT_ARROW: 39,
    DOWN_ARROW: 40,
    FORWARD_SLASH: 47,
    AT: 50,
    META: 91,
    META_RIGHT: 93
  },

  /**
   * Public API method which initializes Converse.
   * This method must always be called when using Converse.
   * @async
   * @memberOf converse
   * @method initialize
   * @param {object} config A map of [configuration-settings](https://conversejs.org/docs/html/configuration.html#configuration-settings).
   * @example
   * converse.initialize({
   *     auto_list_rooms: false,
   *     auto_subscribe: false,
   *     bosh_service_url: 'https://bind.example.com',
   *     hide_muc_server: false,
   *     i18n: 'en',
   *     play_sounds: true,
   *     show_controlbox_by_default: true,
   *     debug: false,
   *     roster_groups: true
   * });
   */
  async initialize(settings) {
    await cleanup();
    setUnloadEvent();
    initSettings(settings);
    converse_core_converse.strict_plugin_dependencies = settings.strict_plugin_dependencies; // Needed by pluggable.js

    headless_log.setLogLevel(converse_core_api.settings.get("loglevel"));

    if (converse_core_api.settings.get("authentication") === converse_core_converse.ANONYMOUS) {
      if (converse_core_api.settings.get("auto_login") && !converse_core_api.settings.get('jid')) {
        throw new Error("Config Error: you need to provide the server's " + "domain via the 'jid' option when using anonymous " + "authentication with auto_login.");
      }
    }

    converse_core_converse.router.route(/^converse\?loglevel=(debug|info|warn|error|fatal)$/, 'loglevel', l => headless_log.setLogLevel(l));

    converse_core_converse.connfeedback = new converse_core_converse.ConnectionFeedback();
    /* When reloading the page:
     * For new sessions, we need to send out a presence stanza to notify
     * the server/network that we're online.
     * When re-attaching to an existing session we don't need to again send out a presence stanza,
     * because it's as if "we never left" (see onConnectStatusChanged).
     * https://github.com/conversejs/converse.js/issues/521
     */

    converse_core_converse.send_initial_presence = true;
    await initSessionStorage();
    await initClientConfig();
    await i18n.initialize();
    initPlugins();
    converse_core_registerGlobalEventHandlers();
    !History.started && converse_core_converse.router.history.start();

    if (converse_core_api.settings.get("idle_presence_timeout") > 0) {
      converse_core_api.listen.on('addClientFeatures', () => converse_core_api.disco.own.features.add(strophe["e" /* Strophe */].NS.IDLE));
    }

    const plugins = converse_core_converse.pluggable.plugins;

    if (converse_core_api.settings.get("auto_login") || converse_core_api.settings.get("keepalive") && lodash_es_invoke(plugins['converse-bosh'], 'enabled')) {
      await converse_core_api.user.login(null, null, true);
    }
    /**
     * Triggered once converse.initialize has finished.
     * @event _converse#initialized
     */


    converse_core_api.trigger('initialized');

    if (converse_core_converse.isTestEnv()) {
      return converse_core_converse;
    }
  },

  /**
   * Exposes methods for adding and removing plugins. You'll need to write a plugin
   * if you want to have access to the private API methods defined further down below.
   *
   * For more information on plugins, read the documentation on [writing a plugin](/docs/html/plugin_development.html).
   * @namespace plugins
   * @memberOf converse
   */
  plugins: {
    /**
     * Registers a new plugin.
     * @method converse.plugins.add
     * @param {string} name The name of the plugin
     * @param {object} plugin The plugin object
     * @example
     *  const plugin = {
     *      initialize: function () {
     *          // Gets called as soon as the plugin has been loaded.
     *
     *          // Inside this method, you have access to the private
     *          // API via `_covnerse.api`.
     *
     *          // The private _converse object contains the core logic
     *          // and data-structures of Converse.
     *      }
     *  }
     *  converse.plugins.add('myplugin', plugin);
     */
    add(name, plugin) {
      plugin.__name__ = name;

      if (converse_core_converse.pluggable.plugins[name] !== undefined) {
        throw new TypeError(`Error: plugin with name "${name}" has already been ` + 'registered!');
      } else {
        converse_core_converse.pluggable.plugins[name] = plugin;
      }
    }

  },

  /**
   * Utility methods and globals from bundled 3rd party libraries.
   * @typedef ConverseEnv
   * @property {function} converse.env.$build    - Creates a Strophe.Builder, for creating stanza objects.
   * @property {function} converse.env.$iq       - Creates a Strophe.Builder with an <iq/> element as the root.
   * @property {function} converse.env.$msg      - Creates a Strophe.Builder with an <message/> element as the root.
   * @property {function} converse.env.$pres     - Creates a Strophe.Builder with an <presence/> element as the root.
   * @property {function} converse.env.Promise   - The Promise implementation used by Converse.
   * @property {function} converse.env.Strophe   - The [Strophe](http://strophe.im/strophejs) XMPP library used by Converse.
   * @property {function} converse.env.f         - And instance of Lodash with its methods wrapped to produce immutable auto-curried iteratee-first data-last methods.
   * @property {function} converse.env.sizzle    - [Sizzle](https://sizzlejs.com) CSS selector engine.
   * @property {function} converse.env.sprintf
   * @property {object} converse.env._           - The instance of [lodash-es](http://lodash.com) used by Converse.
   * @property {object} converse.env.dayjs       - [DayJS](https://github.com/iamkun/dayjs) date manipulation library.
   * @property {object} converse.env.utils       - Module containing common utility methods used by Converse.
   * @memberOf converse
   */
  'env': {
    $build: strophe["a" /* $build */],
    $iq: strophe["b" /* $iq */],
    $msg: strophe["c" /* $msg */],
    $pres: strophe["d" /* $pres */],
    'utils': utils_core,
    Collection: Collection,
    Model: model_Model,
    Promise,
    Strophe: strophe["e" /* Strophe */],
    dayjs: dayjs_min_default.a,
    html: lit_html_html,
    log: headless_log,
    sizzle: sizzle_default.a,
    sprintf: sprintf["sprintf"],
    stanza_utils: utils_stanza,
    u: utils_core
  }
});
/**
 * Once Converse.js has loaded, it'll dispatch a custom event with the name `converse-loaded`.
 * You can listen for this event in order to be informed as soon as converse.js has been
 * loaded and parsed, which would mean it's safe to call `converse.initialize`.
 * @event converse-loaded
 * @example window.addEventListener('converse-loaded', () => converse.initialize());
 */

const converse_core_ev = new CustomEvent('converse-loaded', {
  'detail': {
    converse
  }
});
window.dispatchEvent(converse_core_ev);
// CONCATENATED MODULE: ./src/headless/converse-adhoc.js




const {
  Strophe: converse_adhoc_Strophe
} = converse.env;

let converse_adhoc_converse, converse_adhoc_api;

converse_adhoc_Strophe.addNamespace('ADHOC', 'http://jabber.org/protocol/commands');

function parseForCommands(stanza) {
  const items = sizzle_default()(`query[xmlns="${converse_adhoc_Strophe.NS.DISCO_ITEMS}"][node="${converse_adhoc_Strophe.NS.ADHOC}"] item`, stanza);
  return items.map(utils_stanza.getAttributes);
}

const adhoc_api = {
  /**
   * The XEP-0050 Ad-Hoc Commands API
   *
   * This API lets you discover ad-hoc commands available for an entity in the XMPP network.
   *
   * @namespace api.adhoc
   * @memberOf api
   */
  adhoc: {
    /**
     * @method api.adhoc.getCommands
     * @param { String } to_jid
     */
    async getCommands(to_jid) {
      let commands = [];

      try {
        commands = parseForCommands(await converse_adhoc_api.disco.items(to_jid, converse_adhoc_Strophe.NS.ADHOC));
      } catch (e) {
        if (e === null) {
          headless_log.error(`Error: timeout while fetching ad-hoc commands for ${to_jid}`);
        } else {
          headless_log.error(`Error while fetching ad-hoc commands for ${to_jid}`);
          headless_log.error(e);
        }
      }

      return commands;
    }

  }
};
converse.plugins.add('converse-adhoc', {
  dependencies: ["converse-disco"],

  initialize() {
    converse_adhoc_converse = this._converse;
    converse_adhoc_api = converse_adhoc_converse.api;
    Object.assign(converse_adhoc_api, adhoc_api);
  }

});
/* harmony default export */ var converse_adhoc = (adhoc_api);
// EXTERNAL MODULE: ./node_modules/filesize/lib/filesize.min.js
var filesize_min = __webpack_require__(60);
var filesize_min_default = /*#__PURE__*/__webpack_require__.n(filesize_min);

// CONCATENATED MODULE: ./node_modules/lodash-es/_createFind.js



/**
 * Creates a `_.find` or `_.findLast` function.
 *
 * @private
 * @param {Function} findIndexFunc The function to find the collection index.
 * @returns {Function} Returns the new find function.
 */

function createFind(findIndexFunc) {
  return function (collection, predicate, fromIndex) {
    var iterable = Object(collection);

    if (!lodash_es_isArrayLike(collection)) {
      var iteratee = _baseIteratee(predicate, 3);
      collection = lodash_es_keys(collection);

      predicate = function (key) {
        return iteratee(iterable[key], key, iterable);
      };
    }

    var index = findIndexFunc(collection, predicate, fromIndex);
    return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
  };
}

/* harmony default export */ var _createFind = (createFind);
// CONCATENATED MODULE: ./node_modules/lodash-es/find.js


/**
 * Iterates over elements of `collection`, returning the first element
 * `predicate` returns truthy for. The predicate is invoked with three
 * arguments: (value, index|key, collection).
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to inspect.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @param {number} [fromIndex=0] The index to search from.
 * @returns {*} Returns the matched element, else `undefined`.
 * @example
 *
 * var users = [
 *   { 'user': 'barney',  'age': 36, 'active': true },
 *   { 'user': 'fred',    'age': 40, 'active': false },
 *   { 'user': 'pebbles', 'age': 1,  'active': true }
 * ];
 *
 * _.find(users, function(o) { return o.age < 40; });
 * // => object for 'barney'
 *
 * // The `_.matches` iteratee shorthand.
 * _.find(users, { 'age': 1, 'active': true });
 * // => object for 'pebbles'
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.find(users, ['active', false]);
 * // => object for 'fred'
 *
 * // The `_.property` iteratee shorthand.
 * _.find(users, 'active');
 * // => object for 'barney'
 */

var find = _createFind(lodash_es_findIndex);
/* harmony default export */ var lodash_es_find = (find);
// CONCATENATED MODULE: ./node_modules/lodash-es/isMatch.js


/**
 * Performs a partial deep comparison between `object` and `source` to
 * determine if `object` contains equivalent property values.
 *
 * **Note:** This method is equivalent to `_.matches` when `source` is
 * partially applied.
 *
 * Partial comparisons will match empty array and empty object `source`
 * values against any array or object value, respectively. See `_.isEqual`
 * for a list of supported value comparisons.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Lang
 * @param {Object} object The object to inspect.
 * @param {Object} source The object of property values to match.
 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
 * @example
 *
 * var object = { 'a': 1, 'b': 2 };
 *
 * _.isMatch(object, { 'b': 2 });
 * // => true
 *
 * _.isMatch(object, { 'b': 1 });
 * // => false
 */

function isMatch(object, source) {
  return object === source || _baseIsMatch(object, source, _getMatchData(source));
}

/* harmony default export */ var lodash_es_isMatch = (isMatch);
// CONCATENATED MODULE: ./src/headless/converse-chat.js
/**
 * @module converse-chat
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */







const {
  $msg: converse_chat_$msg,
  Strophe: converse_chat_Strophe,
  sizzle: converse_chat_sizzle,
  utils
} = converse.env;
const converse_chat_u = converse.env.utils;
converse.plugins.add('converse-chat', {
  /* Optional dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin. They are called "optional" because they might not be
   * available, in which case any overrides applicable to them will be
   * ignored.
   *
   * It's possible however to make optional dependencies non-optional.
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found.
   *
   * NB: These plugins need to have already been loaded via require.js.
   */
  dependencies: ["converse-chatboxes", "converse-disco"],

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    const {
      __
    } = converse_core_converse; // Configuration values for this plugin
    // ====================================
    // Refer to docs/source/configuration.rst for explanations of these
    // configuration settings.

    converse_core_api.settings.extend({
      'allow_message_corrections': 'all',
      'allow_message_retraction': 'all',
      'auto_join_private_chats': [],
      'clear_messages_on_reconnection': false,
      'filter_by_resource': false,
      'send_chat_state_notifications': true
    });
    const ModelWithContact = model_Model.extend({
      initialize() {
        this.rosterContactAdded = converse_chat_u.getResolveablePromise();
      },

      async setRosterContact(jid) {
        const contact = await converse_core_api.contacts.get(jid);

        if (contact) {
          this.contact = contact;
          this.set('nickname', contact.get('nickname'));
          this.rosterContactAdded.resolve();
        }
      }

    });
    /**
     * Represents a non-MUC message. These can be either `chat` messages or
     * `headline` messages.
     * @class
     * @namespace _converse.Message
     * @memberOf _converse
     * @example const msg = new _converse.Message({'message': 'hello world!'});
     */

    converse_core_converse.Message = ModelWithContact.extend({
      defaults() {
        return {
          'msgid': converse_chat_u.getUniqueId(),
          'time': new Date().toISOString(),
          'is_ephemeral': false
        };
      },

      async initialize() {
        if (!this.checkValidity()) {
          return;
        }

        this.initialized = converse_chat_u.getResolveablePromise();

        if (this.get('type') === 'chat') {
          ModelWithContact.prototype.initialize.apply(this, arguments);
          this.setRosterContact(converse_chat_Strophe.getBareJidFromJid(this.get('from')));
        }

        if (this.get('file')) {
          this.on('change:put', this.uploadFile, this);
        }

        this.setTimerForEphemeralMessage();
        /**
         * Triggered once a {@link _converse.Message} has been created and initialized.
         * @event _converse#messageInitialized
         * @type { _converse.Message}
         * @example _converse.api.listen.on('messageInitialized', model => { ... });
         */

        await converse_core_api.trigger('messageInitialized', this, {
          'Synchronous': true
        });
        this.initialized.resolve();
      },

      /**
       * Sets an auto-destruct timer for this message, if it's is_ephemeral.
       * @private
       * @method _converse.Message#setTimerForEphemeralMessage
       * @returns { Boolean } - Indicates whether the message is
       *   ephemeral or not, and therefore whether the timer was set or not.
       */
      setTimerForEphemeralMessage() {
        const setTimer = () => {
          this.ephemeral_timer = window.setTimeout(this.safeDestroy.bind(this), 10000);
        };

        if (this.isEphemeral()) {
          setTimer();
          return true;
        } else {
          this.on('change:is_ephemeral', () => this.isEphemeral() ? setTimer() : clearTimeout(this.ephemeral_timer));
          return false;
        }
      },

      checkValidity() {
        if (Object.keys(this.attributes).length === 3) {
          // XXX: This is an empty message with only the 3 default values.
          // This seems to happen when saving a newly created message
          // fails for some reason.
          // TODO: This is likely fixable by setting `wait` when
          // creating messages. See the wait-for-messages branch.
          this.validationError = "Empty message";
          this.safeDestroy();
          return false;
        }

        return true;
      },

      /**
       * Determines whether this messsage may be retracted by the current user.
       * @private
       * @method _converse.Messages#mayBeRetracted
       * @returns { Boolean }
       */
      mayBeRetracted() {
        const is_own_message = this.get('sender') === 'me';
        return is_own_message && ['all', 'own'].includes(converse_core_api.settings.get('allow_message_retraction'));
      },

      safeDestroy() {
        try {
          this.destroy();
        } catch (e) {
          headless_log.error(e);
        }
      },

      isEphemeral() {
        return this.get('is_ephemeral');
      },

      getDisplayName() {
        if (this.get('type') === 'groupchat') {
          return this.get('nick');
        } else if (this.contact) {
          return this.contact.getDisplayName();
        } else if (this.vcard) {
          return this.vcard.getDisplayName();
        } else {
          return this.get('from');
        }
      },

      getMessageText() {
        if (this.get('is_encrypted')) {
          return this.get('plaintext') || this.get('body') || __('Undecryptable OMEMO message');
        }

        return this.get('message');
      },

      isMeCommand() {
        const text = this.getMessageText();

        if (!text) {
          return false;
        }

        return text.startsWith('/me ');
      },

      sendSlotRequestStanza() {
        /* Send out an IQ stanza to request a file upload slot.
         *
         * https://xmpp.org/extensions/xep-0363.html#request
         */
        if (!this.file) {
          return Promise.reject(new Error("file is undefined"));
        }

        const iq = converse.env.$iq({
          'from': converse_core_converse.jid,
          'to': this.get('slot_request_url'),
          'type': 'get'
        }).c('request', {
          'xmlns': converse_chat_Strophe.NS.HTTPUPLOAD,
          'filename': this.file.name,
          'size': this.file.size,
          'content-type': this.file.type
        });
        return converse_core_api.sendIQ(iq);
      },

      async getRequestSlotURL() {
        let stanza;

        try {
          stanza = await this.sendSlotRequestStanza();
        } catch (e) {
          headless_log.error(e);
          return this.save({
            'type': 'error',
            'message': __("Sorry, could not determine upload URL."),
            'is_ephemeral': true
          });
        }

        const slot = stanza.querySelector('slot');

        if (slot) {
          this.save({
            'get': slot.querySelector('get').getAttribute('url'),
            'put': slot.querySelector('put').getAttribute('url')
          });
        } else {
          return this.save({
            'type': 'error',
            'message': __("Sorry, could not determine file upload URL."),
            'is_ephemeral': true
          });
        }
      },

      uploadFile() {
        const xhr = new XMLHttpRequest();

        xhr.onreadystatechange = () => {
          if (xhr.readyState === XMLHttpRequest.DONE) {
            headless_log.info("Status: " + xhr.status);

            if (xhr.status === 200 || xhr.status === 201) {
              this.save({
                'upload': converse_core_converse.SUCCESS,
                'oob_url': this.get('get'),
                'message': this.get('get')
              });
            } else {
              xhr.onerror();
            }
          }
        };

        xhr.upload.addEventListener("progress", evt => {
          if (evt.lengthComputable) {
            this.set('progress', evt.loaded / evt.total);
          }
        }, false);

        xhr.onerror = () => {
          let message;

          if (xhr.responseText) {
            message = __('Sorry, could not succesfully upload your file. Your server’s response: "%1$s"', xhr.responseText);
          } else {
            message = __('Sorry, could not succesfully upload your file.');
          }

          this.save({
            'type': 'error',
            'upload': converse_core_converse.FAILURE,
            'message': message,
            'is_ephemeral': true
          });
        };

        xhr.open('PUT', this.get('put'), true);
        xhr.setRequestHeader("Content-type", this.file.type);
        xhr.send(this.file);
      }

    });
    converse_core_converse.Messages = Collection.extend({
      model: converse_core_converse.Message,
      comparator: 'time'
    });
    /**
     * Represents an open/ongoing chat conversation.
     *
     * @class
     * @namespace _converse.ChatBox
     * @memberOf _converse
     */

    converse_core_converse.ChatBox = ModelWithContact.extend({
      messagesCollection: converse_core_converse.Messages,

      defaults() {
        return {
          'bookmarked': false,
          'chat_state': undefined,
          'hidden': converse_core_converse.isUniView() && !converse_core_api.settings.get('singleton'),
          'message_type': 'chat',
          'nickname': undefined,
          'num_unread': 0,
          'time_sent': new Date(0).toISOString(),
          'time_opened': this.get('time_opened') || new Date().getTime(),
          'type': converse_core_converse.PRIVATE_CHAT_TYPE,
          'url': ''
        };
      },

      async initialize() {
        this.initialized = converse_chat_u.getResolveablePromise();
        ModelWithContact.prototype.initialize.apply(this, arguments);
        const jid = this.get('jid');

        if (!jid) {
          // XXX: The `validate` method will prevent this model
          // from being persisted if there's no jid, but that gets
          // called after model instantiation, so we have to deal
          // with invalid models here also.
          // This happens when the controlbox is in browser storage,
          // but we're in embedded mode.
          return;
        }

        this.set({
          'box_id': `box-${jid}`
        });
        this.initNotifications();
        this.initMessages();

        if (this.get('type') === converse_core_converse.PRIVATE_CHAT_TYPE) {
          this.presence = converse_core_converse.presences.findWhere({
            'jid': jid
          }) || converse_core_converse.presences.create({
            'jid': jid
          });
          await this.setRosterContact(jid);
        }

        this.on('change:chat_state', this.sendChatState, this);
        await this.fetchMessages();
        /**
         * Triggered once a {@link _converse.ChatBox} has been created and initialized.
         * @event _converse#chatBoxInitialized
         * @type { _converse.ChatBox}
         * @example _converse.api.listen.on('chatBoxInitialized', model => { ... });
         */

        await converse_core_api.trigger('chatBoxInitialized', this, {
          'Synchronous': true
        });
        this.initialized.resolve();
      },

      getMessagesCacheKey() {
        return `converse.messages-${this.get('jid')}-${converse_core_converse.bare_jid}`;
      },

      initMessages() {
        this.messages = new this.messagesCollection();
        this.messages.fetched = converse_chat_u.getResolveablePromise();
        this.messages.fetched.then(() => {
          /**
           * Triggered whenever a `_converse.ChatBox` instance has fetched its messages from
           * `sessionStorage` but **NOT** from the server.
           * @event _converse#afterMessagesFetched
           * @type {_converse.ChatBoxView | _converse.ChatRoomView}
           * @example _converse.api.listen.on('afterMessagesFetched', view => { ... });
           */
          converse_core_api.trigger('afterMessagesFetched', this);
        });
        this.messages.chatbox = this;
        this.messages.browserStorage = converse_core_converse.createStore(this.getMessagesCacheKey());
        this.listenTo(this.messages, 'change:upload', message => {
          if (message.get('upload') === converse_core_converse.SUCCESS) {
            converse_core_api.send(this.createMessageStanza(message));
          }
        });
      },

      initNotifications() {
        this.notifications = new model_Model();
      },

      afterMessagesFetched() {
        /**
         * Triggered whenever a `_converse.ChatBox` instance has fetched its messages from
         * `sessionStorage` but **NOT** from the server.
         * @event _converse#afterMessagesFetched
         * @type {_converse.ChatBox | _converse.ChatRoom}
         * @example _converse.api.listen.on('afterMessagesFetched', view => { ... });
         */
        converse_core_api.trigger('afterMessagesFetched', this);
      },

      fetchMessages() {
        if (this.messages.fetched_flag) {
          headless_log.info(`Not re-fetching messages for ${this.get('jid')}`);
          return;
        }

        this.messages.fetched_flag = true;
        const resolve = this.messages.fetched.resolve;
        this.messages.fetch({
          'add': true,
          'success': () => {
            this.afterMessagesFetched();
            resolve();
          },
          'error': () => {
            this.afterMessagesFetched();
            resolve();
          }
        });
        return this.messages.fetched;
      },

      async handleErrorMessageStanza(stanza) {
        const attrs = await utils_stanza.parseMessage(stanza, converse_core_converse);

        if (!(await this.shouldShowErrorMessage(attrs))) {
          return;
        }

        const message = this.getMessageReferencedByError(attrs);

        if (message) {
          const new_attrs = {
            'error': attrs.error,
            'error_condition': attrs.error_condition,
            'error_text': attrs.error_text,
            'error_type': attrs.error_type,
            'editable': false
          };

          if (attrs.msgid === message.get('retraction_id')) {
            // The error message refers to a retraction
            new_attrs.retraction_id = undefined;

            if (!attrs.error) {
              if (attrs.error_condition === 'forbidden') {
                new_attrs.error = __("You're not allowed to retract your message.");
              } else {
                new_attrs.error = __('Sorry, an error occurred while trying to retract your message.');
              }
            }
          } else if (!attrs.error) {
            if (attrs.error_condition === 'forbidden') {
              new_attrs.error = __("You're not allowed to send a message.");
            } else {
              new_attrs.error = __('Sorry, an error occurred while trying to send your message.');
            }
          }

          message.save(new_attrs);
        } else {
          this.createMessage(attrs);
        }
      },

      /**
       * Queue an incoming `chat` message stanza for processing.
       * @async
       * @private
       * @method _converse.ChatRoom#queueMessage
       * @param { Promise<MessageAttributes> } attrs - A promise which resolves to the message attributes
       */
      queueMessage(attrs) {
        this.msg_chain = (this.msg_chain || this.messages.fetched).then(() => this.onMessage(attrs)).catch(e => headless_log.error(e));
        return this.msg_chain;
      },

      /**
       * @async
       * @private
       * @method _converse.ChatRoom#onMessage
       * @param { MessageAttributes } attrs_promse - A promise which resolves to the message attributes.
       */
      async onMessage(attrs) {
        attrs = await attrs;

        if (converse_chat_u.isErrorObject(attrs)) {
          attrs.stanza && headless_log.error(attrs.stanza);
          return headless_log.error(attrs.message);
        }

        const message = this.getDuplicateMessage(attrs);

        if (message) {
          this.updateMessage(message, attrs);
        } else if (!this.handleReceipt(attrs) && !this.handleChatMarker(attrs) && !(await this.handleRetraction(attrs))) {
          this.setEditable(attrs, attrs.time);

          if (attrs['chat_state'] && attrs.sender === 'them') {
            this.notifications.set('chat_state', attrs.chat_state);
          }

          if (converse_chat_u.shouldCreateMessage(attrs)) {
            const msg = this.handleCorrection(attrs) || (await this.createMessage(attrs));
            this.notifications.set({
              'chat_state': null
            });
            this.handleUnreadMessage(msg);
          }
        }
      },

      async clearMessages() {
        try {
          await this.messages.clearStore();
        } catch (e) {
          this.messages.trigger('reset');
          headless_log.error(e);
        } finally {
          delete this.msg_chain;
          delete this.messages.fetched_flag;
          this.messages.fetched = converse_chat_u.getResolveablePromise();
        }
      },

      async close() {
        try {
          await new Promise((success, reject) => {
            return this.destroy({
              success,
              'error': (m, e) => reject(e)
            });
          });
        } catch (e) {
          headless_log.error(e);
        } finally {
          if (converse_core_api.settings.get('clear_messages_on_reconnection')) {
            await this.clearMessages();
          }
        }
      },

      announceReconnection() {
        /**
         * Triggered whenever a `_converse.ChatBox` instance has reconnected after an outage
         * @event _converse#onChatReconnected
         * @type {_converse.ChatBox | _converse.ChatRoom}
         * @example _converse.api.listen.on('onChatReconnected', chatbox => { ... });
         */
        converse_core_api.trigger('chatReconnected', this);
      },

      async onReconnection() {
        if (converse_core_api.settings.get('clear_messages_on_reconnection')) {
          await this.clearMessages();
        }

        this.announceReconnection();
      },

      validate(attrs) {
        if (!attrs.jid) {
          return 'Ignored ChatBox without JID';
        }

        const room_jids = converse_core_converse.auto_join_rooms.map(s => lodash_es_isObject(s) ? s.jid : s);

        const auto_join = converse_core_api.settings.get('auto_join_private_chats').concat(room_jids);

        if (converse_core_api.settings.get("singleton") && !auto_join.includes(attrs.jid) && !converse_core_api.settings.get('auto_join_on_invite')) {
          const msg = `${attrs.jid} is not allowed because singleton is true and it's not being auto_joined`;
          headless_log.warn(msg);
          return msg;
        }
      },

      getDisplayName() {
        if (this.contact) {
          return this.contact.getDisplayName();
        } else if (this.vcard) {
          return this.vcard.getDisplayName();
        } else {
          return this.get('jid');
        }
      },

      async createMessageFromError(error) {
        if (error instanceof converse_core_converse.TimeoutError) {
          const msg = await this.createMessage({
            'type': 'error',
            'message': error.message,
            'retry_event_id': error.retry_event_id
          });
          msg.error = error;
        }
      },

      getOldestMessage() {
        for (let i = 0; i < this.messages.length; i++) {
          const message = this.messages.at(i);

          if (message.get('type') === this.get('message_type')) {
            return message;
          }
        }
      },

      getMostRecentMessage() {
        for (let i = this.messages.length - 1; i >= 0; i--) {
          const message = this.messages.at(i);

          if (message.get('type') === this.get('message_type')) {
            return message;
          }
        }
      },

      getUpdatedMessageAttributes(message, attrs) {
        // Filter the attrs object, restricting it to only the `is_archived` key.
        return (({
          is_archived
        }) => ({
          is_archived
        }))(attrs);
      },

      updateMessage(message, attrs) {
        const new_attrs = this.getUpdatedMessageAttributes(message, attrs);
        new_attrs && message.save(new_attrs);
      },

      /**
       * Mutator for setting the chat state of this chat session.
       * Handles clearing of any chat state notification timeouts and
       * setting new ones if necessary.
       * Timeouts are set when the  state being set is COMPOSING or PAUSED.
       * After the timeout, COMPOSING will become PAUSED and PAUSED will become INACTIVE.
       * See XEP-0085 Chat State Notifications.
       * @private
       * @method _converse.ChatBox#setChatState
       * @param { string } state - The chat state (consts ACTIVE, COMPOSING, PAUSED, INACTIVE, GONE)
       */
      setChatState(state, options) {
        if (this.chat_state_timeout !== undefined) {
          window.clearTimeout(this.chat_state_timeout);
          delete this.chat_state_timeout;
        }

        if (state === converse_core_converse.COMPOSING) {
          this.chat_state_timeout = window.setTimeout(this.setChatState.bind(this), converse_core_converse.TIMEOUTS.PAUSED, converse_core_converse.PAUSED);
        } else if (state === converse_core_converse.PAUSED) {
          this.chat_state_timeout = window.setTimeout(this.setChatState.bind(this), converse_core_converse.TIMEOUTS.INACTIVE, converse_core_converse.INACTIVE);
        }

        this.set('chat_state', state, options);
        return this;
      },

      /**
       * Given an error `<message>` stanza's attributes, find the saved message model which is
       * referenced by that error.
       * @param { Object } attrs
       */
      getMessageReferencedByError(attrs) {
        const id = attrs.msgid;
        return id && this.messages.models.find(m => [m.get('msgid'), m.get('retraction_id')].includes(id));
      },

      /**
       * @private
       * @method _converse.ChatBox#shouldShowErrorMessage
       * @returns {boolean}
       */
      shouldShowErrorMessage(attrs) {
        const msg = this.getMessageReferencedByError(attrs);

        if (!msg && !attrs.body) {
          // If the error refers to a message not included in our store,
          // and it doesn't have a <body> tag, we assume that this was a
          // CSI message (which we don't store).
          // See https://github.com/conversejs/converse.js/issues/1317
          return;
        } // Gets overridden in ChatRoom


        return true;
      },

      isSameUser(jid1, jid2) {
        return converse_chat_u.isSameBareJID(jid1, jid2);
      },

      /**
       * Looks whether we already have a retraction for this
       * incoming message. If so, it's considered "dangling" because it
       * probably hasn't been applied to anything yet, given that the
       * relevant message is only coming in now.
       * @private
       * @method _converse.ChatBox#findDanglingRetraction
       * @param { object } attrs - Attributes representing a received
       *  message, as returned by {@link st.parseMessage}
       * @returns { _converse.Message }
       */
      findDanglingRetraction(attrs) {
        if (!attrs.origin_id || !this.messages.length) {
          return null;
        } // Only look for dangling retractions if there are newer
        // messages than this one, since retractions come after.


        if (this.messages.last().get('time') > attrs.time) {
          // Search from latest backwards
          const messages = Array.from(this.messages.models);
          messages.reverse();
          return messages.find(({
            attributes
          }) => attributes.retracted_id === attrs.origin_id && attributes.from === attrs.from && !attributes.moderated_by);
        }
      },

      /**
       * Handles message retraction based on the passed in attributes.
       * @private
       * @method _converse.ChatBox#handleRetraction
       * @param { object } attrs - Attributes representing a received
       *  message, as returned by {@link st.parseMessage}
       * @returns { Boolean } Returns `true` or `false` depending on
       *  whether a message was retracted or not.
       */
      async handleRetraction(attrs) {
        const RETRACTION_ATTRIBUTES = ['retracted', 'retracted_id', 'editable'];

        if (attrs.retracted) {
          if (attrs.is_tombstone) {
            return false;
          }

          const message = this.messages.findWhere({
            'origin_id': attrs.retracted_id,
            'from': attrs.from
          });

          if (!message) {
            attrs['dangling_retraction'] = true;
            await this.createMessage(attrs);
            return true;
          }

          message.save(lodash_es_pick(attrs, RETRACTION_ATTRIBUTES));
          return true;
        } else {
          // Check if we have dangling retraction
          const message = this.findDanglingRetraction(attrs);

          if (message) {
            const retraction_attrs = lodash_es_pick(message.attributes, RETRACTION_ATTRIBUTES);
            const new_attrs = Object.assign({
              'dangling_retraction': false
            }, attrs, retraction_attrs);
            delete new_attrs['id']; // Delete id, otherwise a new cache entry gets created

            message.save(new_attrs);
            return true;
          }
        }

        return false;
      },

      /**
       * Determines whether the passed in message attributes represent a
       * message which corrects a previously received message, or an
       * older message which has already been corrected.
       * In both cases, update the corrected message accordingly.
       * @private
       * @method _converse.ChatBox#handleCorrection
       * @param { object } attrs - Attributes representing a received
       *  message, as returned by {@link st.parseMessage}
       * @returns { _converse.Message|undefined } Returns the corrected
       *  message or `undefined` if not applicable.
       */
      handleCorrection(attrs) {
        if (!attrs.replace_id || !attrs.from) {
          return;
        }

        const message = this.messages.findWhere({
          'msgid': attrs.replace_id,
          'from': attrs.from
        });

        if (!message) {
          return;
        }

        const older_versions = message.get('older_versions') || {};

        if (attrs.time < message.get('time') && message.get('edited')) {
          // This is an older message which has been corrected afterwards
          older_versions[attrs.time] = attrs['message'];
          message.save({
            'older_versions': older_versions
          });
        } else {
          // This is a correction of an earlier message we already received
          if (Object.keys(older_versions).length) {
            older_versions[message.get('edited')] = message.get('message');
          } else {
            older_versions[message.get('time')] = message.get('message');
          }

          attrs = Object.assign(attrs, {
            'older_versions': older_versions
          });
          delete attrs['id']; // Delete id, otherwise a new cache entry gets created

          attrs['time'] = message.get('time');
          message.save(attrs);
        }

        return message;
      },

      /**
       * Returns an already cached message (if it exists) based on the
       * passed in attributes map.
       * @private
       * @method _converse.ChatBox#getDuplicateMessage
       * @param { object } attrs - Attributes representing a received
       *  message, as returned by {@link st.parseMessage}
       * @returns {Promise<_converse.Message>}
       */
      getDuplicateMessage(attrs) {
        const queries = [...this.getStanzaIdQueryAttrs(attrs), this.getOriginIdQueryAttrs(attrs), this.getMessageBodyQueryAttrs(attrs)].filter(s => s);
        const msgs = this.messages.models;
        return lodash_es_find(msgs, m => queries.reduce((out, q) => out || lodash_es_isMatch(m.attributes, q), false));
      },

      getOriginIdQueryAttrs(attrs) {
        return attrs.origin_id && {
          'origin_id': attrs.origin_id,
          'from': attrs.from
        };
      },

      getStanzaIdQueryAttrs(attrs) {
        const keys = Object.keys(attrs).filter(k => k.startsWith('stanza_id '));
        return keys.map(key => {
          const by_jid = key.replace(/^stanza_id /, '');
          const query = {};
          query[`stanza_id ${by_jid}`] = attrs[key];
          return query;
        });
      },

      getMessageBodyQueryAttrs(attrs) {
        if (attrs.message && attrs.msgid) {
          const query = {
            'from': attrs.from,
            'msgid': attrs.msgid
          };

          if (!attrs.is_encrypted) {
            // We can't match the message if it's a reflected
            // encrypted message (e.g. via MAM or in a MUC)
            query['message'] = attrs.message;
          }

          return query;
        }
      },

      /**
       * Retract one of your messages in this chat
       * @private
       * @method _converse.ChatBoxView#retractOwnMessage
       * @param { _converse.Message } message - The message which we're retracting.
       */
      retractOwnMessage(message) {
        this.sendRetractionMessage(message);
        message.save({
          'retracted': new Date().toISOString(),
          'retracted_id': message.get('origin_id'),
          'retraction_id': message.get('id'),
          'is_ephemeral': true,
          'editable': false
        });
      },

      /**
       * Sends a message stanza to retract a message in this chat
       * @private
       * @method _converse.ChatBox#sendRetractionMessage
       * @param { _converse.Message } message - The message which we're retracting.
       */
      sendRetractionMessage(message) {
        const origin_id = message.get('origin_id');

        if (!origin_id) {
          throw new Error("Can't retract message without a XEP-0359 Origin ID");
        }

        const msg = converse_chat_$msg({
          'id': converse_chat_u.getUniqueId(),
          'to': this.get('jid'),
          'type': "chat"
        }).c('store', {
          xmlns: converse_chat_Strophe.NS.HINTS
        }).up().c("apply-to", {
          'id': origin_id,
          'xmlns': converse_chat_Strophe.NS.FASTEN
        }).c('retract', {
          xmlns: converse_chat_Strophe.NS.RETRACT
        });
        return converse_core_converse.connection.send(msg);
      },

      sendMarkerForMessage(msg) {
        if (msg !== null && msg !== void 0 && msg.get('is_markable')) {
          const from_jid = converse_chat_Strophe.getBareJidFromJid(msg.get('from'));
          this.sendMarker(from_jid, msg.get('msgid'), 'displayed', msg.get('type'));
        }
      },

      sendMarker(to_jid, id, type, msg_type) {
        const stanza = converse_chat_$msg({
          'from': converse_core_converse.connection.jid,
          'id': converse_chat_u.getUniqueId(),
          'to': to_jid,
          'type': msg_type ? msg_type : 'chat'
        }).c(type, {
          'xmlns': converse_chat_Strophe.NS.MARKERS,
          'id': id
        });
        converse_core_api.send(stanza);
      },

      handleChatMarker(attrs) {
        const to_bare_jid = converse_chat_Strophe.getBareJidFromJid(attrs.to);

        if (to_bare_jid !== converse_core_converse.bare_jid) {
          return false;
        }

        if (attrs.is_markable) {
          if (this.contact && !attrs.is_archived && !attrs.is_carbon) {
            this.sendMarker(attrs.from, attrs.msgid, 'received');
          }

          return false;
        } else if (attrs.marker_id) {
          const message = this.messages.findWhere({
            'msgid': attrs.marker_id
          });
          const field_name = `marker_${attrs.marker}`;

          if (message && !message.get(field_name)) {
            message.save({
              field_name: new Date().toISOString()
            });
          }

          return true;
        }
      },

      sendReceiptStanza(to_jid, id) {
        const receipt_stanza = converse_chat_$msg({
          'from': converse_core_converse.connection.jid,
          'id': converse_chat_u.getUniqueId(),
          'to': to_jid,
          'type': 'chat'
        }).c('received', {
          'xmlns': converse_chat_Strophe.NS.RECEIPTS,
          'id': id
        }).up().c('store', {
          'xmlns': converse_chat_Strophe.NS.HINTS
        }).up();
        converse_core_api.send(receipt_stanza);
      },

      handleReceipt(attrs) {
        if (attrs.sender === 'them') {
          if (attrs.is_valid_receipt_request) {
            this.sendReceiptStanza(attrs.from, attrs.msgid);
          } else if (attrs.receipt_id) {
            const message = this.messages.findWhere({
              'msgid': attrs.receipt_id
            });

            if (message && !message.get('received')) {
              message.save({
                'received': new Date().toISOString()
              });
            }

            return true;
          }
        }

        return false;
      },

      /**
       * Given a {@link _converse.Message} return the XML stanza that represents it.
       * @private
       * @method _converse.ChatBox#createMessageStanza
       * @param { _converse.Message } message - The message object
       */
      createMessageStanza(message) {
        const stanza = converse_chat_$msg({
          'from': converse_core_converse.connection.jid,
          'to': this.get('jid'),
          'type': this.get('message_type'),
          'id': message.get('edited') && converse_chat_u.getUniqueId() || message.get('msgid')
        }).c('body').t(message.get('message')).up().c(converse_core_converse.ACTIVE, {
          'xmlns': converse_chat_Strophe.NS.CHATSTATES
        }).root();

        if (message.get('type') === 'chat') {
          stanza.c('request', {
            'xmlns': converse_chat_Strophe.NS.RECEIPTS
          }).root();
        }

        if (message.get('is_spoiler')) {
          if (message.get('spoiler_hint')) {
            stanza.c('spoiler', {
              'xmlns': converse_chat_Strophe.NS.SPOILER
            }, message.get('spoiler_hint')).root();
          } else {
            stanza.c('spoiler', {
              'xmlns': converse_chat_Strophe.NS.SPOILER
            }).root();
          }
        }

        (message.get('references') || []).forEach(reference => {
          const attrs = {
            'xmlns': converse_chat_Strophe.NS.REFERENCE,
            'begin': reference.begin,
            'end': reference.end,
            'type': reference.type
          };

          if (reference.uri) {
            attrs.uri = reference.uri;
          }

          stanza.c('reference', attrs).root();
        });

        if (message.get('oob_url')) {
          stanza.c('x', {
            'xmlns': converse_chat_Strophe.NS.OUTOFBAND
          }).c('url').t(message.get('oob_url')).root();
        }

        if (message.get('edited')) {
          stanza.c('replace', {
            'xmlns': converse_chat_Strophe.NS.MESSAGE_CORRECT,
            'id': message.get('msgid')
          }).root();
        }

        if (message.get('origin_id')) {
          stanza.c('origin-id', {
            'xmlns': converse_chat_Strophe.NS.SID,
            'id': message.get('origin_id')
          }).root();
        }

        return stanza;
      },

      getOutgoingMessageAttributes(text, spoiler_hint) {
        const is_spoiler = this.get('composing_spoiler');
        const origin_id = converse_chat_u.getUniqueId();
        const body = text ? converse_chat_u.httpToGeoUri(converse_chat_u.shortnamesToUnicode(text), converse_core_converse) : undefined;
        return {
          'from': converse_core_converse.bare_jid,
          'fullname': converse_core_converse.xmppstatus.get('fullname'),
          'id': origin_id,
          'is_only_emojis': text ? converse_chat_u.isOnlyEmojis(text) : false,
          'jid': this.get('jid'),
          'message': body,
          'msgid': origin_id,
          'nickname': this.get('nickname'),
          'sender': 'me',
          'spoiler_hint': is_spoiler ? spoiler_hint : undefined,
          'time': new Date().toISOString(),
          'type': this.get('message_type'),
          body,
          is_spoiler,
          origin_id
        };
      },

      /**
       * Responsible for setting the editable attribute of messages.
       * If api.settings.get('allow_message_corrections') is "last", then only the last
       * message sent from me will be editable. If set to "all" all messages
       * will be editable. Otherwise no messages will be editable.
       * @method _converse.ChatBox#setEditable
       * @memberOf _converse.ChatBox
       * @param { Object } attrs An object containing message attributes.
       * @param { String } send_time - time when the message was sent
       */
      setEditable(attrs, send_time) {
        if (attrs.is_headline || converse_chat_u.isEmptyMessage(attrs) || attrs.sender !== 'me') {
          return;
        }

        if (converse_core_api.settings.get('allow_message_corrections') === 'all') {
          attrs.editable = !(attrs.file || attrs.retracted || 'oob_url' in attrs);
        } else if (converse_core_api.settings.get('allow_message_corrections') === 'last' && send_time > this.get('time_sent')) {
          this.set({
            'time_sent': send_time
          });
          const msg = this.messages.findWhere({
            'editable': true
          });

          if (msg) {
            msg.save({
              'editable': false
            });
          }

          attrs.editable = !(attrs.file || attrs.retracted || 'oob_url' in attrs);
        }
      },

      /**
       * Queue the creation of a message, to make sure that we don't run
       * into a race condition whereby we're creating a new message
       * before the collection has been fetched.
       * @async
       * @private
       * @method _converse.ChatRoom#queueMessageCreation
       * @param { Object } attrs
       */
      async createMessage(attrs, options) {
        attrs.time = attrs.time || new Date().toISOString();
        await this.messages.fetched;
        const p = this.messages.create(attrs, Object.assign({
          'wait': true,
          'promise': true
        }, options));
        return p;
      },

      /**
       * Responsible for sending off a text message inside an ongoing chat conversation.
       * @private
       * @method _converse.ChatBox#sendMessage
       * @memberOf _converse.ChatBox
       * @param { String } text - The chat message text
       * @param { String } spoiler_hint - An optional hint, if the message being sent is a spoiler
       * @returns { _converse.Message }
       * @example
       * const chat = api.chats.get('buddy1@example.com');
       * chat.sendMessage('hello world');
       */
      async sendMessage(text, spoiler_hint) {
        const attrs = this.getOutgoingMessageAttributes(text, spoiler_hint);
        let message = this.messages.findWhere('correcting');

        if (message) {
          const older_versions = message.get('older_versions') || {};
          older_versions[message.get('time')] = message.get('message');
          message.save({
            'correcting': false,
            'edited': new Date().toISOString(),
            'message': attrs.message,
            'older_versions': older_versions,
            'references': attrs.references,
            'is_only_emojis': attrs.is_only_emojis,
            'origin_id': converse_chat_u.getUniqueId(),
            'received': undefined
          });
        } else {
          this.setEditable(attrs, new Date().toISOString());
          message = await this.createMessage(attrs);
        }

        converse_core_api.send(this.createMessageStanza(message));
        /**
         * Triggered when a message is being sent out
         * @event _converse#sendMessage
         * @type { Object }
         * @param { Object } data
         * @property { (_converse.ChatBox | _converse.ChatRoom) } data.chatbox
         * @property { (_converse.Message | _converse.ChatRoomMessage) } data.message
         */

        converse_core_api.trigger('sendMessage', {
          'chatbox': this,
          message
        });
        return message;
      },

      /**
       * Sends a message with the current XEP-0085 chat state of the user
       * as taken from the `chat_state` attribute of the {@link _converse.ChatBox}.
       * @private
       * @method _converse.ChatBox#sendChatState
       */
      sendChatState() {
        if (converse_core_api.settings.get('send_chat_state_notifications') && this.get('chat_state')) {
          const allowed = converse_core_api.settings.get('send_chat_state_notifications');

          if (Array.isArray(allowed) && !allowed.includes(this.get('chat_state'))) {
            return;
          }

          converse_core_api.send(converse_chat_$msg({
            'id': converse_chat_u.getUniqueId(),
            'to': this.get('jid'),
            'type': 'chat'
          }).c(this.get('chat_state'), {
            'xmlns': converse_chat_Strophe.NS.CHATSTATES
          }).up().c('no-store', {
            'xmlns': converse_chat_Strophe.NS.HINTS
          }).up().c('no-permanent-store', {
            'xmlns': converse_chat_Strophe.NS.HINTS
          }));
        }
      },

      async sendFiles(files) {
        var _maxFileSize;

        const result = await converse_core_api.disco.features.get(converse_chat_Strophe.NS.HTTPUPLOAD, converse_core_converse.domain);
        const item = result.pop();

        if (!item) {
          this.createMessage({
            'message': __("Sorry, looks like file upload is not supported by your server."),
            'type': 'error',
            'is_ephemeral': true
          });
          return;
        }

        const data = item.dataforms.where({
          'FORM_TYPE': {
            'value': converse_chat_Strophe.NS.HTTPUPLOAD,
            'type': "hidden"
          }
        }).pop();
        const max_file_size = window.parseInt((_maxFileSize = ((data === null || data === void 0 ? void 0 : data.attributes) || {})['max-file-size']) === null || _maxFileSize === void 0 ? void 0 : _maxFileSize.value);
        const slot_request_url = item === null || item === void 0 ? void 0 : item.id;

        if (!slot_request_url) {
          this.createMessage({
            'message': __("Sorry, looks like file upload is not supported by your server."),
            'type': 'error',
            'is_ephemeral': true
          });
          return;
        }

        Array.from(files).forEach(async file => {
          if (!window.isNaN(max_file_size) && window.parseInt(file.size) > max_file_size) {
            return this.createMessage({
              'message': __('The size of your file, %1$s, exceeds the maximum allowed by your server, which is %2$s.', file.name, filesize_min_default()(max_file_size)),
              'type': 'error',
              'is_ephemeral': true
            });
          } else {
            const attrs = Object.assign(this.getOutgoingMessageAttributes(), {
              'file': true,
              'progress': 0,
              'slot_request_url': slot_request_url
            });
            this.setEditable(attrs, new Date().toISOString());
            const message = await this.createMessage(attrs, {
              'silent': true
            });
            message.file = file;
            this.messages.trigger('add', message);
            message.getRequestSlotURL();
          }
        });
      },

      maybeShow(force) {
        if (force) {
          if (converse_core_converse.isUniView()) {
            // We only have one chat visible at any one time.
            // So before opening a chat, we make sure all other chats are hidden.
            const filter = c => !c.get('hidden') && c.get('jid') !== this.get('jid') && c.get('id') !== 'controlbox';

            converse_core_converse.chatboxes.filter(filter).forEach(c => converse_chat_u.safeSave(c, {
              'hidden': true
            }));
          }

          converse_chat_u.safeSave(this, {
            'hidden': false
          });
        }

        if (converse_core_converse.isUniView() && this.get('hidden')) {
          return;
        } else {
          return this.trigger("show");
        }
      },

      /**
       * Indicates whether the chat is hidden and therefore
       * whether a newly received message will be visible
       * to the user or not.
       * @returns {boolean}
       */
      isHidden() {
        // Note: This methods gets overridden by converse-minimize
        const hidden = converse_core_converse.isUniView() && this.get('hidden');
        return hidden || this.isScrolledUp() || converse_core_converse.windowState === 'hidden';
      },

      /**
       * Given a newly received {@link _converse.Message} instance,
       * update the unread counter if necessary.
       * @private
       * @param {_converse.Message} message
       */
      handleUnreadMessage(message) {
        if (!(message !== null && message !== void 0 && message.get('body'))) {
          return;
        }

        if (utils.isNewMessage(message)) {
          if (this.isHidden()) {
            const settings = {
              'num_unread': this.get('num_unread') + 1
            };

            if (this.get('num_unread') === 0) {
              settings['first_unread_id'] = message.get('id');
            }

            this.save(settings);
          } else {
            this.sendMarkerForMessage(message);
          }
        }
      },

      clearUnreadMsgCounter() {
        if (this.get('num_unread') > 0) {
          this.sendMarkerForMessage(this.messages.last());
        }

        converse_chat_u.safeSave(this, {
          'num_unread': 0
        });
      },

      isScrolledUp() {
        return this.get('scrolled', true);
      }

    });

    async function handleErrorMessage(stanza) {
      const from_jid = converse_chat_Strophe.getBareJidFromJid(stanza.getAttribute('from'));

      if (utils.isSameBareJID(from_jid, converse_core_converse.bare_jid)) {
        return;
      }

      const chatbox = await converse_core_api.chatboxes.get(from_jid);
      chatbox === null || chatbox === void 0 ? void 0 : chatbox.handleErrorMessageStanza(stanza);
    }
    /**
     * Handler method for all incoming single-user chat "message" stanzas.
     * @private
     * @method _converse#handleMessageStanza
     * @param { MessageAttributes } attrs - The message attributes
     */


    converse_core_converse.handleMessageStanza = async function (stanza) {
      if (utils_stanza.isServerMessage(stanza)) {
        // Prosody sends headline messages with type `chat`, so we need to filter them out here.
        const from = stanza.getAttribute('from');
        return headless_log.info(`handleMessageStanza: Ignoring incoming server message from JID: ${from}`);
      }

      const attrs = await utils_stanza.parseMessage(stanza, converse_core_converse);

      if (converse_chat_u.isErrorObject(attrs)) {
        attrs.stanza && headless_log.error(attrs.stanza);
        return headless_log.error(attrs.message);
      }

      const has_body = !!converse_chat_sizzle(`body, encrypted[xmlns="${converse_chat_Strophe.NS.OMEMO}"]`, stanza).length;
      const chatbox = await converse_core_api.chats.get(attrs.contact_jid, {
        'nickname': attrs.nick
      }, has_body);
      await (chatbox === null || chatbox === void 0 ? void 0 : chatbox.queueMessage(attrs));
      /**
       * @typedef { Object } MessageData
       * An object containing the original message stanza, as well as the
       * parsed attributes.
       * @property { XMLElement } stanza
       * @property { MessageAttributes } stanza
       * @property { ChatBox } chatbox
       */

      const data = {
        stanza,
        attrs,
        chatbox
      };
      /**
       * Triggered when a message stanza is been received and processed.
       * @event _converse#message
       * @type { object }
       * @property { module:converse-chat~MessageData } data
       */

      converse_core_api.trigger('message', data);
    };

    function registerMessageHandlers() {
      converse_core_converse.connection.addHandler(stanza => {
        if (converse_chat_sizzle(`message > result[xmlns="${converse_chat_Strophe.NS.MAM}"]`, stanza).pop()) {
          // MAM messages are handled in converse-mam.
          // We shouldn't get MAM messages here because
          // they shouldn't have a `type` attribute.
          headless_log.warn(`Received a MAM message with type "chat".`);
          return true;
        }

        converse_core_converse.handleMessageStanza(stanza);

        return true;
      }, null, 'message', 'chat');

      converse_core_converse.connection.addHandler(stanza => {
        // Message receipts are usually without the `type` attribute. See #1353
        if (stanza.getAttribute('type') !== null) {
          // TODO: currently Strophe has no way to register a handler
          // for stanzas without a `type` attribute.
          // We could update it to accept null to mean no attribute,
          // but that would be a backward-incompatible change
          return true; // Gets handled above.
        }

        converse_core_converse.handleMessageStanza(stanza);

        return true;
      }, converse_chat_Strophe.NS.RECEIPTS, 'message');

      converse_core_converse.connection.addHandler(stanza => {
        handleErrorMessage(stanza);
        return true;
      }, null, 'message', 'error');
    }

    function autoJoinChats() {
      // Automatically join private chats, based on the
      // "auto_join_private_chats" configuration setting.
      converse_core_api.settings.get('auto_join_private_chats').forEach(jid => {
        if (converse_core_converse.chatboxes.where({
          'jid': jid
        }).length) {
          return;
        }

        if (typeof jid === 'string') {
          converse_core_api.chats.open(jid);
        } else {
          headless_log.error('Invalid jid criteria specified for "auto_join_private_chats"');
        }
      });
      /**
       * Triggered once any private chats have been automatically joined as
       * specified by the `auto_join_private_chats` setting.
       * See: https://conversejs.org/docs/html/configuration.html#auto-join-private-chats
       * @event _converse#privateChatsAutoJoined
       * @example _converse.api.listen.on('privateChatsAutoJoined', () => { ... });
       * @example _converse.api.waitUntil('privateChatsAutoJoined').then(() => { ... });
       */

      converse_core_api.trigger('privateChatsAutoJoined');
    }
    /************************ BEGIN Route Handlers ************************/


    function openChat(jid) {
      if (!utils.isValidJID(jid)) {
        return headless_log.warn(`Invalid JID "${jid}" provided in URL fragment`);
      }

      converse_core_api.chats.open(jid);
    }

    converse_core_converse.router.route('converse/chat?jid=:jid', openChat);
    /************************ END Route Handlers ************************/

    /************************ BEGIN Event Handlers ************************/


    converse_core_api.listen.on('chatBoxesFetched', autoJoinChats);
    converse_core_api.listen.on('presencesInitialized', registerMessageHandlers);
    converse_core_api.listen.on('clearSession', async () => {
      if (converse_core_converse.shouldClearCache()) {
        await Promise.all(converse_core_converse.chatboxes.map(c => c.messages && c.messages.clearStore({
          'silent': true
        })));

        const filter = o => o.get('type') !== converse_core_converse.CONTROLBOX_TYPE;

        converse_core_converse.chatboxes.clearStore({
          'silent': true
        }, filter);
      }
    });
    /************************ END Event Handlers ************************/

    /************************ BEGIN API ************************/

    Object.assign(converse_core_api, {
      /**
       * The "chats" namespace (used for one-on-one chats)
       *
       * @namespace api.chats
       * @memberOf api
       */
      chats: {
        /**
         * @method api.chats.create
         * @param {string|string[]} jid|jids An jid or array of jids
         * @param {object} [attrs] An object containing configuration attributes.
         */
        async create(jids, attrs) {
          if (typeof jids === 'string') {
            if (attrs && !(attrs !== null && attrs !== void 0 && attrs.fullname)) {
              var _contact$attributes;

              const contact = await converse_core_api.contacts.get(jids);
              attrs.fullname = contact === null || contact === void 0 ? void 0 : (_contact$attributes = contact.attributes) === null || _contact$attributes === void 0 ? void 0 : _contact$attributes.fullname;
            }

            const chatbox = converse_core_api.chats.get(jids, attrs, true);

            if (!chatbox) {
              headless_log.error("Could not open chatbox for JID: " + jids);
              return;
            }

            return chatbox;
          }

          if (Array.isArray(jids)) {
            return Promise.all(jids.forEach(async jid => {
              var _contact$attributes2;

              const contact = await converse_core_api.contacts.get(jids);
              attrs.fullname = contact === null || contact === void 0 ? void 0 : (_contact$attributes2 = contact.attributes) === null || _contact$attributes2 === void 0 ? void 0 : _contact$attributes2.fullname;
              return converse_core_api.chats.get(jid, attrs, true).maybeShow();
            }));
          }

          headless_log.error("chats.create: You need to provide at least one JID");
          return null;
        },

        /**
         * Opens a new one-on-one chat.
         *
         * @method api.chats.open
         * @param {String|string[]} name - e.g. 'buddy@example.com' or ['buddy1@example.com', 'buddy2@example.com']
         * @param {Object} [attrs] - Attributes to be set on the _converse.ChatBox model.
         * @param {Boolean} [attrs.minimized] - Should the chat be created in minimized state.
         * @param {Boolean} [force=false] - By default, a minimized
         *   chat won't be maximized (in `overlayed` view mode) and in
         *   `fullscreen` view mode a newly opened chat won't replace
         *   another chat already in the foreground.
         *   Set `force` to `true` if you want to force the chat to be
         *   maximized or shown.
         * @returns {Promise} Promise which resolves with the
         *   _converse.ChatBox representing the chat.
         *
         * @example
         * // To open a single chat, provide the JID of the contact you're chatting with in that chat:
         * converse.plugins.add('myplugin', {
         *     initialize: function() {
         *         const _converse = this._converse;
         *         // Note, buddy@example.org must be in your contacts roster!
         *         api.chats.open('buddy@example.com').then(chat => {
         *             // Now you can do something with the chat model
         *         });
         *     }
         * });
         *
         * @example
         * // To open an array of chats, provide an array of JIDs:
         * converse.plugins.add('myplugin', {
         *     initialize: function () {
         *         const _converse = this._converse;
         *         // Note, these users must first be in your contacts roster!
         *         api.chats.open(['buddy1@example.com', 'buddy2@example.com']).then(chats => {
         *             // Now you can do something with the chat models
         *         });
         *     }
         * });
         */
        async open(jids, attrs, force) {
          if (typeof jids === 'string') {
            const chat = await converse_core_api.chats.get(jids, attrs, true);

            if (chat) {
              return chat.maybeShow(force);
            }

            return chat;
          } else if (Array.isArray(jids)) {
            return Promise.all(jids.map(j => converse_core_api.chats.get(j, attrs, true).then(c => c && c.maybeShow(force))).filter(c => c));
          }

          const err_msg = "chats.open: You need to provide at least one JID";
          headless_log.error(err_msg);
          throw new Error(err_msg);
        },

        /**
         * Retrieves a chat or all chats.
         *
         * @method api.chats.get
         * @param {String|string[]} jids - e.g. 'buddy@example.com' or ['buddy1@example.com', 'buddy2@example.com']
         * @param {Object} [attrs] - Attributes to be set on the _converse.ChatBox model.
         * @param {Boolean} [create=false] - Whether the chat should be created if it's not found.
         * @returns { Promise<_converse.ChatBox> }
         *
         * @example
         * // To return a single chat, provide the JID of the contact you're chatting with in that chat:
         * const model = await api.chats.get('buddy@example.com');
         *
         * @example
         * // To return an array of chats, provide an array of JIDs:
         * const models = await api.chats.get(['buddy1@example.com', 'buddy2@example.com']);
         *
         * @example
         * // To return all open chats, call the method without any parameters::
         * const models = await api.chats.get();
         *
         */
        async get(jids, attrs = {}, create = false) {
          async function _get(jid) {
            let model = await converse_core_api.chatboxes.get(jid);

            if (!model && create) {
              model = await converse_core_api.chatboxes.create(jid, attrs, converse_core_converse.ChatBox);
            } else {
              model = model && model.get('type') === converse_core_converse.PRIVATE_CHAT_TYPE ? model : null;

              if (model && Object.keys(attrs).length) {
                model.save(attrs);
              }
            }

            return model;
          }

          if (jids === undefined) {
            const chats = await converse_core_api.chatboxes.get();
            return chats.filter(c => c.get('type') === converse_core_converse.PRIVATE_CHAT_TYPE);
          } else if (typeof jids === 'string') {
            return _get(jids);
          }

          return Promise.all(jids.map(jid => _get(jid)));
        }

      }
    });
    /************************ END API ************************/
  }

});
// CONCATENATED MODULE: ./src/headless/converse-disco.js
/**
 * @module converse-disco
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description Converse plugin which add support for XEP-0030: Service Discovery
 */






const {
  Strophe: converse_disco_Strophe,
  $iq,
  utils: converse_disco_utils
} = converse.env;
converse.plugins.add('converse-disco', {
  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    // Promises exposed by this plugin
    converse_core_api.promises.add('discoInitialized');
    converse_core_api.promises.add('streamFeaturesAdded');
    /**
     * @class
     * @namespace _converse.DiscoEntity
     * @memberOf _converse
     */

    converse_core_converse.DiscoEntity = model_Model.extend({
      /* A Disco Entity is a JID addressable entity that can be queried
       * for features.
       *
       * See XEP-0030: https://xmpp.org/extensions/xep-0030.html
       */
      idAttribute: 'jid',

      initialize(attrs, options) {
        this.waitUntilFeaturesDiscovered = converse_disco_utils.getResolveablePromise();
        this.dataforms = new Collection();
        let id = `converse.dataforms-${this.get('jid')}`;
        this.dataforms.browserStorage = converse_core_converse.createStore(id, 'session');
        this.features = new Collection();
        id = `converse.features-${this.get('jid')}`;
        this.features.browserStorage = converse_core_converse.createStore(id, 'session');
        this.listenTo(this.features, 'add', this.onFeatureAdded);
        this.fields = new Collection();
        id = `converse.fields-${this.get('jid')}`;
        this.fields.browserStorage = converse_core_converse.createStore(id, 'session');
        this.listenTo(this.fields, 'add', this.onFieldAdded);
        this.identities = new Collection();
        id = `converse.identities-${this.get('jid')}`;
        this.identities.browserStorage = converse_core_converse.createStore(id, 'session');
        this.fetchFeatures(options);
        this.items = new converse_core_converse.DiscoEntities();
        id = `converse.disco-items-${this.get('jid')}`;
        this.items.browserStorage = converse_core_converse.createStore(id, 'session');
        this.items.fetch();
      },

      /**
       * Returns a Promise which resolves with a map indicating
       * whether a given identity is provided by this entity.
       * @private
       * @method _converse.DiscoEntity#getIdentity
       * @param { String } category - The identity category
       * @param { String } type - The identity type
       */
      async getIdentity(category, type) {
        await this.waitUntilFeaturesDiscovered;
        return this.identities.findWhere({
          'category': category,
          'type': type
        });
      },

      /**
       * Returns a Promise which resolves with a map indicating
       * whether a given feature is supported.
       * @private
       * @method _converse.DiscoEntity#hasFeature
       * @param { String } feature - The feature that might be supported.
       */
      async hasFeature(feature) {
        await this.waitUntilFeaturesDiscovered;

        if (this.features.findWhere({
          'var': feature
        })) {
          return this;
        }
      },

      onFeatureAdded(feature) {
        feature.entity = this;
        /**
         * Triggered when Converse has learned of a service provided by the XMPP server.
         * See XEP-0030.
         * @event _converse#serviceDiscovered
         * @type { Model }
         * @example _converse.api.listen.on('featuresDiscovered', feature => { ... });
         */

        converse_core_api.trigger('serviceDiscovered', feature);
      },

      onFieldAdded(field) {
        field.entity = this;
        /**
         * Triggered when Converse has learned of a disco extension field.
         * See XEP-0030.
         * @event _converse#discoExtensionFieldDiscovered
         * @example _converse.api.listen.on('discoExtensionFieldDiscovered', () => { ... });
         */

        converse_core_api.trigger('discoExtensionFieldDiscovered', field);
      },

      async fetchFeatures(options) {
        if (options.ignore_cache) {
          this.queryInfo();
        } else {
          const store_id = this.features.browserStorage.name;
          const result = await this.features.browserStorage.store.getItem(store_id);

          if (result && result.length === 0 || result === null) {
            this.queryInfo();
          } else {
            this.features.fetch({
              add: true,
              success: () => {
                this.waitUntilFeaturesDiscovered.resolve(this);
                this.trigger('featuresDiscovered');
              }
            });
            this.identities.fetch({
              add: true
            });
          }
        }
      },

      async queryInfo() {
        let stanza;

        try {
          stanza = await converse_core_api.disco.info(this.get('jid'), null);
        } catch (iq) {
          iq === null ? headless_log.error(`Timeout for disco#info query for ${this.get('jid')}`) : headless_log.error(iq);
          this.waitUntilFeaturesDiscovered.resolve(this);
          return;
        }

        this.onInfo(stanza);
      },

      onDiscoItems(stanza) {
        sizzle_default()(`query[xmlns="${converse_disco_Strophe.NS.DISCO_ITEMS}"] item`, stanza).forEach(item => {
          if (item.getAttribute("node")) {
            // XXX: Ignore nodes for now.
            // See: https://xmpp.org/extensions/xep-0030.html#items-nodes
            return;
          }

          const jid = item.getAttribute('jid');

          if (this.items.get(jid) === undefined) {
            const entity = converse_core_converse.disco_entities.get(jid);

            if (entity) {
              this.items.add(entity);
            } else {
              this.items.create({
                'jid': jid
              });
            }
          }
        });
      },

      async queryForItems() {
        if (this.identities.where({
          'category': 'server'
        }).length === 0) {
          // Don't fetch features and items if this is not a
          // server or a conference component.
          return;
        }

        const stanza = await converse_core_api.disco.items(this.get('jid'));
        this.onDiscoItems(stanza);
      },

      onInfo(stanza) {
        Array.from(stanza.querySelectorAll('identity')).forEach(identity => {
          this.identities.create({
            'category': identity.getAttribute('category'),
            'type': identity.getAttribute('type'),
            'name': identity.getAttribute('name')
          });
        });
        sizzle_default()(`x[type="result"][xmlns="${converse_disco_Strophe.NS.XFORM}"]`, stanza).forEach(form => {
          const data = {};
          sizzle_default()('field', form).forEach(field => {
            var _field$querySelector;

            data[field.getAttribute('var')] = {
              'value': (_field$querySelector = field.querySelector('value')) === null || _field$querySelector === void 0 ? void 0 : _field$querySelector.textContent,
              'type': field.getAttribute('type')
            };
          });
          this.dataforms.create(data);
        });

        if (stanza.querySelector(`feature[var="${converse_disco_Strophe.NS.DISCO_ITEMS}"]`)) {
          this.queryForItems();
        }

        Array.from(stanza.querySelectorAll('feature')).forEach(feature => {
          this.features.create({
            'var': feature.getAttribute('var'),
            'from': stanza.getAttribute('from')
          });
        }); // XEP-0128 Service Discovery Extensions

        sizzle_default()('x[type="result"][xmlns="jabber:x:data"] field', stanza).forEach(field => {
          var _field$querySelector2;

          this.fields.create({
            'var': field.getAttribute('var'),
            'value': (_field$querySelector2 = field.querySelector('value')) === null || _field$querySelector2 === void 0 ? void 0 : _field$querySelector2.textContent,
            'from': stanza.getAttribute('from')
          });
        });
        this.waitUntilFeaturesDiscovered.resolve(this);
        this.trigger('featuresDiscovered');
      }

    });
    converse_core_converse.DiscoEntities = Collection.extend({
      model: converse_core_converse.DiscoEntity,

      fetchEntities() {
        return new Promise((resolve, reject) => {
          this.fetch({
            add: true,
            success: resolve,

            error(m, e) {
              headless_log.error(e);
              reject(new Error("Could not fetch disco entities"));
            }

          });
        });
      }

    });

    function addClientFeatures() {
      // See https://xmpp.org/registrar/disco-categories.html
      converse_core_api.disco.own.identities.add('client', 'web', 'Converse');
      converse_core_api.disco.own.features.add(converse_disco_Strophe.NS.CHATSTATES);
      converse_core_api.disco.own.features.add(converse_disco_Strophe.NS.DISCO_INFO);
      converse_core_api.disco.own.features.add(converse_disco_Strophe.NS.ROSTERX); // Limited support

      if (converse_core_api.settings.get("message_carbons")) {
        converse_core_api.disco.own.features.add(converse_disco_Strophe.NS.CARBONS);
      }
      /**
       * Triggered in converse-disco once the core disco features of
       * Converse have been added.
       * @event _converse#addClientFeatures
       * @example _converse.api.listen.on('addClientFeatures', () => { ... });
       */


      converse_core_api.trigger('addClientFeatures');
      return this;
    }

    function initStreamFeatures() {
      // Initialize the stream_features collection, and if we're
      // re-attaching to a pre-existing BOSH session, we restore the
      // features from cache.
      // Otherwise the features will be created once we've received them
      // from the server (see populateStreamFeatures).
      if (!converse_core_converse.stream_features) {
        const bare_jid = converse_disco_Strophe.getBareJidFromJid(converse_core_converse.jid);
        const id = `converse.stream-features-${bare_jid}`;
        converse_core_api.promises.add('streamFeaturesAdded');
        converse_core_converse.stream_features = new Collection();
        converse_core_converse.stream_features.browserStorage = converse_core_converse.createStore(id, "session");
      }
    }

    function populateStreamFeatures() {
      // Strophe.js sets the <stream:features> element on the
      // Strophe.Connection instance (_converse.connection).
      //
      // Once this is done, we populate the _converse.stream_features collection
      // and trigger streamFeaturesAdded.
      initStreamFeatures();
      Array.from(converse_core_converse.connection.features.childNodes).forEach(feature => {
        converse_core_converse.stream_features.create({
          'name': feature.nodeName,
          'xmlns': feature.getAttribute('xmlns')
        });
      });
      notifyStreamFeaturesAdded();
    }

    function notifyStreamFeaturesAdded() {
      /**
       * Triggered as soon as the stream features are known.
       * If you want to check whether a stream feature is supported before proceeding,
       * then you'll first want to wait for this event.
       * @event _converse#streamFeaturesAdded
       * @example _converse.api.listen.on('streamFeaturesAdded', () => { ... });
       */
      converse_core_api.trigger('streamFeaturesAdded');
    }

    const plugin = this;
    plugin._identities = [];
    plugin._features = [];

    function onDiscoInfoRequest(stanza) {
      const node = stanza.getElementsByTagName('query')[0].getAttribute('node');
      const attrs = {
        xmlns: converse_disco_Strophe.NS.DISCO_INFO
      };

      if (node) {
        attrs.node = node;
      }

      const iqresult = $iq({
        'type': 'result',
        'id': stanza.getAttribute('id')
      });
      const from = stanza.getAttribute('from');

      if (from !== null) {
        iqresult.attrs({
          'to': from
        });
      }

      iqresult.c('query', attrs);

      plugin._identities.forEach(identity => {
        const attrs = {
          'category': identity.category,
          'type': identity.type
        };

        if (identity.name) {
          attrs.name = identity.name;
        }

        if (identity.lang) {
          attrs['xml:lang'] = identity.lang;
        }

        iqresult.c('identity', attrs).up();
      });

      plugin._features.forEach(feature => iqresult.c('feature', {
        'var': feature
      }).up());

      converse_core_api.send(iqresult.tree());
      return true;
    }

    async function initializeDisco() {
      addClientFeatures();

      converse_core_converse.connection.addHandler(onDiscoInfoRequest, converse_disco_Strophe.NS.DISCO_INFO, 'iq', 'get', null, null);

      converse_core_converse.disco_entities = new converse_core_converse.DiscoEntities();
      const id = `converse.disco-entities-${converse_core_converse.bare_jid}`;
      converse_core_converse.disco_entities.browserStorage = converse_core_converse.createStore(id, 'session');
      const collection = await converse_core_converse.disco_entities.fetchEntities();

      if (collection.length === 0 || !collection.get(converse_core_converse.domain)) {
        // If we don't have an entity for our own XMPP server,
        // create one.
        converse_core_converse.disco_entities.create({
          'jid': converse_core_converse.domain
        });
      }
      /**
       * Triggered once the `converse-disco` plugin has been initialized and the
       * `_converse.disco_entities` collection will be available and populated with at
       * least the service discovery features of the user's own server.
       * @event _converse#discoInitialized
       * @example _converse.api.listen.on('discoInitialized', () => { ... });
       */


      converse_core_api.trigger('discoInitialized');
    }
    /******************** Event Handlers ********************/


    converse_core_api.listen.on('userSessionInitialized', async () => {
      initStreamFeatures();

      if (converse_core_converse.connfeedback.get('connection_status') === converse_disco_Strophe.Status.ATTACHED) {
        // When re-attaching to a BOSH session, we fetch the stream features from the cache.
        await new Promise((success, error) => converse_core_converse.stream_features.fetch({
          success,
          error
        }));
        notifyStreamFeaturesAdded();
      }
    });
    converse_core_api.listen.on('beforeResourceBinding', populateStreamFeatures);
    converse_core_api.listen.on('reconnected', initializeDisco);
    converse_core_api.listen.on('connected', initializeDisco);
    converse_core_api.listen.on('beforeTearDown', async () => {
      converse_core_api.promises.add('streamFeaturesAdded');

      if (converse_core_converse.stream_features) {
        await converse_core_converse.stream_features.clearStore();
        delete converse_core_converse.stream_features;
      }
    });
    converse_core_api.listen.on('clearSession', () => {
      if (converse_core_converse.shouldClearCache() && converse_core_converse.disco_entities) {
        Array.from(converse_core_converse.disco_entities.models).forEach(e => e.features.clearStore());
        Array.from(converse_core_converse.disco_entities.models).forEach(e => e.identities.clearStore());
        Array.from(converse_core_converse.disco_entities.models).forEach(e => e.dataforms.clearStore());
        Array.from(converse_core_converse.disco_entities.models).forEach(e => e.fields.clearStore());

        converse_core_converse.disco_entities.clearStore();

        delete converse_core_converse.disco_entities;
      }
    });
    /************************ API ************************/

    Object.assign(converse_core_api, {
      /**
       * The XEP-0030 service discovery API
       *
       * This API lets you discover information about entities on the
       * XMPP network.
       *
       * @namespace api.disco
       * @memberOf api
       */
      disco: {
        /**
         * @namespace api.disco.stream
         * @memberOf api.disco
         */
        stream: {
          /**
           * @method api.disco.stream.getFeature
           * @param {String} name The feature name
           * @param {String} xmlns The XML namespace
           * @example _converse.api.disco.stream.getFeature('ver', 'urn:xmpp:features:rosterver')
           */
          async getFeature(name, xmlns) {
            await converse_core_api.waitUntil('streamFeaturesAdded');

            if (!name || !xmlns) {
              throw new Error("name and xmlns need to be provided when calling disco.stream.getFeature");
            }

            if (converse_core_converse.stream_features === undefined && !converse_core_api.connection.connected()) {
              // Happens during tests when disco lookups happen asynchronously after teardown.
              const msg = `Tried to get feature ${name} ${xmlns} but _converse.stream_features has been torn down`;
              headless_log.warn(msg);
              return;
            }

            return converse_core_converse.stream_features.findWhere({
              'name': name,
              'xmlns': xmlns
            });
          }

        },

        /**
         * @namespace api.disco.own
         * @memberOf api.disco
         */
        own: {
          /**
           * @namespace api.disco.own.identities
           * @memberOf api.disco.own
           */
          identities: {
            /**
             * Lets you add new identities for this client (i.e. instance of Converse)
             * @method api.disco.own.identities.add
             *
             * @param {String} category - server, client, gateway, directory, etc.
             * @param {String} type - phone, pc, web, etc.
             * @param {String} name - "Converse"
             * @param {String} lang - en, el, de, etc.
             *
             * @example _converse.api.disco.own.identities.clear();
             */
            add(category, type, name, lang) {
              for (var i = 0; i < plugin._identities.length; i++) {
                if (plugin._identities[i].category == category && plugin._identities[i].type == type && plugin._identities[i].name == name && plugin._identities[i].lang == lang) {
                  return false;
                }
              }

              plugin._identities.push({
                category: category,
                type: type,
                name: name,
                lang: lang
              });
            },

            /**
             * Clears all previously registered identities.
             * @method api.disco.own.identities.clear
             * @example _converse.api.disco.own.identities.clear();
             */
            clear() {
              plugin._identities = [];
            },

            /**
             * Returns all of the identities registered for this client
             * (i.e. instance of Converse).
             * @method api.disco.identities.get
             * @example const identities = api.disco.own.identities.get();
             */
            get() {
              return plugin._identities;
            }

          },

          /**
           * @namespace api.disco.own.features
           * @memberOf api.disco.own
           */
          features: {
            /**
             * Lets you register new disco features for this client (i.e. instance of Converse)
             * @method api.disco.own.features.add
             * @param {String} name - e.g. http://jabber.org/protocol/caps
             * @example _converse.api.disco.own.features.add("http://jabber.org/protocol/caps");
             */
            add(name) {
              for (var i = 0; i < plugin._features.length; i++) {
                if (plugin._features[i] == name) {
                  return false;
                }
              }

              plugin._features.push(name);
            },

            /**
             * Clears all previously registered features.
             * @method api.disco.own.features.clear
             * @example _converse.api.disco.own.features.clear();
             */
            clear() {
              plugin._features = [];
            },

            /**
             * Returns all of the features registered for this client (i.e. instance of Converse).
             * @method api.disco.own.features.get
             * @example const features = api.disco.own.features.get();
             */
            get() {
              return plugin._features;
            }

          }
        },

        /**
         * Query for information about an XMPP entity
         *
         * @method api.disco.info
         * @param {string} jid The Jabber ID of the entity to query
         * @param {string} [node] A specific node identifier associated with the JID
         * @returns {promise} Promise which resolves once we have a result from the server.
         */
        info(jid, node) {
          const attrs = {
            xmlns: converse_disco_Strophe.NS.DISCO_INFO
          };

          if (node) {
            attrs.node = node;
          }

          const info = $iq({
            'from': converse_core_converse.connection.jid,
            'to': jid,
            'type': 'get'
          }).c('query', attrs);
          return converse_core_api.sendIQ(info);
        },

        /**
         * Query for items associated with an XMPP entity
         *
         * @method api.disco.items
         * @param {string} jid The Jabber ID of the entity to query for items
         * @param {string} [node] A specific node identifier associated with the JID
         * @returns {promise} Promise which resolves once we have a result from the server.
         */
        items(jid, node) {
          const attrs = {
            'xmlns': converse_disco_Strophe.NS.DISCO_ITEMS
          };

          if (node) {
            attrs.node = node;
          }

          return converse_core_api.sendIQ($iq({
            'from': converse_core_converse.connection.jid,
            'to': jid,
            'type': 'get'
          }).c('query', attrs));
        },

        /**
         * Namespace for methods associated with disco entities
         *
         * @namespace api.disco.entities
         * @memberOf api.disco
         */
        entities: {
          /**
           * Get the corresponding `DiscoEntity` instance.
           *
           * @method api.disco.entities.get
           * @param {string} jid The Jabber ID of the entity
           * @param {boolean} [create] Whether the entity should be created if it doesn't exist.
           * @example _converse.api.disco.entities.get(jid);
           */
          async get(jid, create = false) {
            await converse_core_api.waitUntil('discoInitialized');

            if (!jid) {
              return converse_core_converse.disco_entities;
            }

            if (converse_core_converse.disco_entities === undefined && !converse_core_api.connection.connected()) {
              // Happens during tests when disco lookups happen asynchronously after teardown.
              const msg = `Tried to look up entity ${jid} but _converse.disco_entities has been torn down`;
              headless_log.warn(msg);
              return;
            }

            const entity = converse_core_converse.disco_entities.get(jid);

            if (entity || !create) {
              return entity;
            }

            return converse_core_api.disco.entities.create(jid);
          },

          /**
           * Create a new disco entity. It's identity and features
           * will automatically be fetched from cache or from the
           * XMPP server.
           *
           * Fetching from cache can be disabled by passing in
           * `ignore_cache: true` in the options parameter.
           *
           * @method api.disco.entities.create
           * @param {string} jid The Jabber ID of the entity
           * @param {object} [options] Additional options
           * @param {boolean} [options.ignore_cache]
           *     If true, fetch all features from the XMPP server instead of restoring them from cache
           * @example _converse.api.disco.entities.create(jid, {'ignore_cache': true});
           */
          create(jid, options) {
            return converse_core_converse.disco_entities.create({
              'jid': jid
            }, options);
          }

        },

        /**
         * @namespace api.disco.features
         * @memberOf api.disco
         */
        features: {
          /**
           * Return a given feature of a disco entity
           *
           * @method api.disco.features.get
           * @param {string} feature The feature that might be
           *     supported. In the XML stanza, this is the `var`
           *     attribute of the `<feature>` element. For
           *     example: `http://jabber.org/protocol/muc`
           * @param {string} jid The JID of the entity
           *     (and its associated items) which should be queried
           * @returns {promise} A promise which resolves with a list containing
           *     _converse.Entity instances representing the entity
           *     itself or those items associated with the entity if
           *     they support the given feature.
           * @example
           * api.disco.features.get(Strophe.NS.MAM, _converse.bare_jid);
           */
          async get(feature, jid) {
            if (!jid) {
              throw new TypeError('You need to provide an entity JID');
            }

            await converse_core_api.waitUntil('discoInitialized');
            let entity = await converse_core_api.disco.entities.get(jid, true);

            if (converse_core_converse.disco_entities === undefined && !converse_core_api.connection.connected()) {
              // Happens during tests when disco lookups happen asynchronously after teardown.
              const msg = `Tried to get feature ${feature} for ${jid} but _converse.disco_entities has been torn down`;
              headless_log.warn(msg);
              return;
            }

            entity = await entity.waitUntilFeaturesDiscovered;
            const promises = [...entity.items.map(i => i.hasFeature(feature)), entity.hasFeature(feature)];
            const result = await Promise.all(promises);
            return result.filter(lodash_es_isObject);
          }

        },

        /**
         * Used to determine whether an entity supports a given feature.
         *
         * @method api.disco.supports
         * @param {string} feature The feature that might be
         *     supported. In the XML stanza, this is the `var`
         *     attribute of the `<feature>` element. For
         *     example: `http://jabber.org/protocol/muc`
         * @param {string} jid The JID of the entity
         *     (and its associated items) which should be queried
         * @returns {promise} A promise which resolves with `true` or `false`.
         * @example
         * if (await api.disco.supports(Strophe.NS.MAM, _converse.bare_jid)) {
         *     // The feature is supported
         * } else {
         *     // The feature is not supported
         * }
         */
        async supports(feature, jid) {
          const features = await converse_core_api.disco.features.get(feature, jid);
          return features.length > 0;
        },

        /**
         * Refresh the features, fields and identities associated with a
         * disco entity by refetching them from the server
         * @method api.disco.refresh
         * @param {string} jid The JID of the entity whose features are refreshed.
         * @returns {promise} A promise which resolves once the features have been refreshed
         * @example
         * await api.disco.refresh('room@conference.example.org');
         */
        async refresh(jid) {
          if (!jid) {
            throw new TypeError('api.disco.refresh: You need to provide an entity JID');
          }

          await converse_core_api.waitUntil('discoInitialized');
          let entity = await converse_core_api.disco.entities.get(jid);

          if (entity) {
            entity.features.reset();
            entity.fields.reset();
            entity.identities.reset();

            if (!entity.waitUntilFeaturesDiscovered.isPending) {
              entity.waitUntilFeaturesDiscovered = converse_disco_utils.getResolveablePromise();
            }

            entity.queryInfo();
          } else {
            // Create it if it doesn't exist
            entity = await converse_core_api.disco.entities.create(jid, {
              'ignore_cache': true
            });
          }

          return entity.waitUntilFeaturesDiscovered;
        },

        /**
         * @deprecated Use {@link api.disco.refresh} instead.
         * @method api.disco.refreshFeatures
         */
        refreshFeatures(jid) {
          return converse_core_api.refresh(jid);
        },

        /**
         * Return all the features associated with a disco entity
         *
         * @method api.disco.getFeatures
         * @param {string} jid The JID of the entity whose features are returned.
         * @returns {promise} A promise which resolves with the returned features
         * @example
         * const features = await api.disco.getFeatures('room@conference.example.org');
         */
        async getFeatures(jid) {
          if (!jid) {
            throw new TypeError('api.disco.getFeatures: You need to provide an entity JID');
          }

          await converse_core_api.waitUntil('discoInitialized');
          let entity = await converse_core_api.disco.entities.get(jid, true);
          entity = await entity.waitUntilFeaturesDiscovered;
          return entity.features;
        },

        /**
         * Return all the service discovery extensions fields
         * associated with an entity.
         *
         * See [XEP-0129: Service Discovery Extensions](https://xmpp.org/extensions/xep-0128.html)
         *
         * @method api.disco.getFields
         * @param {string} jid The JID of the entity whose fields are returned.
         * @example
         * const fields = await api.disco.getFields('room@conference.example.org');
         */
        async getFields(jid) {
          if (!jid) {
            throw new TypeError('api.disco.getFields: You need to provide an entity JID');
          }

          await converse_core_api.waitUntil('discoInitialized');
          let entity = await converse_core_api.disco.entities.get(jid, true);
          entity = await entity.waitUntilFeaturesDiscovered;
          return entity.fields;
        },

        /**
         * Get the identity (with the given category and type) for a given disco entity.
         *
         * For example, when determining support for PEP (personal eventing protocol), you
         * want to know whether the user's own JID has an identity with
         * `category='pubsub'` and `type='pep'` as explained in this section of
         * XEP-0163: https://xmpp.org/extensions/xep-0163.html#support
         *
         * @method api.disco.getIdentity
         * @param {string} The identity category.
         *     In the XML stanza, this is the `category`
         *     attribute of the `<identity>` element.
         *     For example: 'pubsub'
         * @param {string} type The identity type.
         *     In the XML stanza, this is the `type`
         *     attribute of the `<identity>` element.
         *     For example: 'pep'
         * @param {string} jid The JID of the entity which might have the identity
         * @returns {promise} A promise which resolves with a map indicating
         *     whether an identity with a given type is provided by the entity.
         * @example
         * api.disco.getIdentity('pubsub', 'pep', _converse.bare_jid).then(
         *     function (identity) {
         *         if (identity) {
         *             // The entity DOES have this identity
         *         } else {
         *             // The entity DOES NOT have this identity
         *         }
         *     }
         * ).catch(e => log.error(e));
         */
        async getIdentity(category, type, jid) {
          const e = await converse_core_api.disco.entities.get(jid, true);

          if (e === undefined && !converse_core_api.connection.connected()) {
            // Happens during tests when disco lookups happen asynchronously after teardown.
            const msg = `Tried to look up category ${category} for ${jid} but _converse.disco_entities has been torn down`;
            headless_log.warn(msg);
            return;
          }

          return e.getIdentity(category, type);
        }

      }
    });
  }

});
// CONCATENATED MODULE: ./src/headless/emoji_regexes.js
const ASCII_REGEX = '(\\*\\\\0\\/\\*|\\*\\\\O\\/\\*|\\-___\\-|\\:\'\\-\\)|\'\\:\\-\\)|\'\\:\\-D|\\>\\:\\-\\)|>\\:\\-\\)|\'\\:\\-\\(|\\>\\:\\-\\(|>\\:\\-\\(|\\:\'\\-\\(|O\\:\\-\\)|0\\:\\-3|0\\:\\-\\)|0;\\^\\)|O;\\-\\)|0;\\-\\)|O\\:\\-3|\\-__\\-|\\:\\-Þ|\\:\\-Þ|\\<\\/3|<\\/3|\\:\'\\)|\\:\\-D|\'\\:\\)|\'\\=\\)|\'\\:D|\'\\=D|\\>\\:\\)|>\\:\\)|\\>;\\)|>;\\)|\\>\\=\\)|>\\=\\)|;\\-\\)|\\*\\-\\)|;\\-\\]|;\\^\\)|\'\\:\\(|\'\\=\\(|\\:\\-\\*|\\:\\^\\*|\\>\\:P|>\\:P|X\\-P|\\>\\:\\[|>\\:\\[|\\:\\-\\(|\\:\\-\\[|\\>\\:\\(|>\\:\\(|\\:\'\\(|;\\-\\(|\\>\\.\\<|>\\.<|#\\-\\)|%\\-\\)|X\\-\\)|\\\\0\\/|\\\\O\\/|0\\:3|0\\:\\)|O\\:\\)|O\\=\\)|O\\:3|B\\-\\)|8\\-\\)|B\\-D|8\\-D|\\-_\\-|\\>\\:\\\\|>\\:\\\\|\\>\\:\\/|>\\:\\/|\\:\\-\\/|\\:\\-\\.|\\:\\-P|\\:Þ|\\:Þ|\\:\\-b|\\:\\-O|O_O|\\>\\:O|>\\:O|\\:\\-X|\\:\\-#|\\:\\-\\)|\\(y\\)|\\<3|<3|\\:D|\\=D|;\\)|\\*\\)|;\\]|;D|\\:\\*|\\=\\*|\\:\\(|\\:\\[|\\=\\(|\\:@|;\\(|D\\:|\\:\\$|\\=\\$|#\\)|%\\)|X\\)|B\\)|8\\)|\\:\\/|\\:\\\\|\\=\\/|\\=\\\\|\\:L|\\=L|\\:P|\\=P|\\:b|\\:O|\\:X|\\:#|\\=X|\\=#|\\:\\)|\\=\\]|\\=\\)|\\:\\])';
const ASCII_REPLACE_REGEX = new RegExp("<object[^>]*>.*?<\/object>|<span[^>]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|((\\s|^)" + ASCII_REGEX + "(?=\\s|$|[!,.?]))", "gi");
const CODEPOINTS_REGEX = /(?:\ud83d\udc68\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc68\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc68\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\u200d\ud83e\udd1d\u200d\ud83e\uddd1|\ud83d\udc6b\ud83c[\udffb-\udfff]|\ud83d\udc6c\ud83c[\udffb-\udfff]|\ud83d\udc6d\ud83c[\udffb-\udfff]|\ud83d[\udc6b-\udc6d])|(?:\ud83d[\udc68\udc69]|\ud83e\uddd1)(?:\ud83c[\udffb-\udfff])?\u200d(?:\u2695\ufe0f|\u2696\ufe0f|\u2708\ufe0f|\ud83c[\udf3e\udf73\udf93\udfa4\udfa8\udfeb\udfed]|\ud83d[\udcbb\udcbc\udd27\udd2c\ude80\ude92]|\ud83e[\uddaf-\uddb3\uddbc\uddbd])|(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75]|\u26f9)((?:\ud83c[\udffb-\udfff]|\ufe0f)\u200d[\u2640\u2642]\ufe0f)|(?:\ud83c[\udfc3\udfc4\udfca]|\ud83d[\udc6e\udc71\udc73\udc77\udc81\udc82\udc86\udc87\ude45-\ude47\ude4b\ude4d\ude4e\udea3\udeb4-\udeb6]|\ud83e[\udd26\udd35\udd37-\udd39\udd3d\udd3e\uddb8\uddb9\uddcd-\uddcf\uddd6-\udddd])(?:\ud83c[\udffb-\udfff])?\u200d[\u2640\u2642]\ufe0f|(?:\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f|\ud83c\udff3\ufe0f\u200d\ud83c\udf08|\ud83c\udff4\u200d\u2620\ufe0f|\ud83d\udc15\u200d\ud83e\uddba|\ud83d\udc41\u200d\ud83d\udde8|\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc6f\u200d\u2640\ufe0f|\ud83d\udc6f\u200d\u2642\ufe0f|\ud83e\udd3c\u200d\u2640\ufe0f|\ud83e\udd3c\u200d\u2642\ufe0f|\ud83e\uddde\u200d\u2640\ufe0f|\ud83e\uddde\u200d\u2642\ufe0f|\ud83e\udddf\u200d\u2640\ufe0f|\ud83e\udddf\u200d\u2642\ufe0f)|[#*0-9]\ufe0f?\u20e3|(?:[©®\u2122\u265f]\ufe0f)|(?:\ud83c[\udc04\udd70\udd71\udd7e\udd7f\ude02\ude1a\ude2f\ude37\udf21\udf24-\udf2c\udf36\udf7d\udf96\udf97\udf99-\udf9b\udf9e\udf9f\udfcd\udfce\udfd4-\udfdf\udff3\udff5\udff7]|\ud83d[\udc3f\udc41\udcfd\udd49\udd4a\udd6f\udd70\udd73\udd76-\udd79\udd87\udd8a-\udd8d\udda5\udda8\uddb1\uddb2\uddbc\uddc2-\uddc4\uddd1-\uddd3\udddc-\uddde\udde1\udde3\udde8\uddef\uddf3\uddfa\udecb\udecd-\udecf\udee0-\udee5\udee9\udef0\udef3]|[\u203c\u2049\u2139\u2194-\u2199\u21a9\u21aa\u231a\u231b\u2328\u23cf\u23ed-\u23ef\u23f1\u23f2\u23f8-\u23fa\u24c2\u25aa\u25ab\u25b6\u25c0\u25fb-\u25fe\u2600-\u2604\u260e\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262a\u262e\u262f\u2638-\u263a\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267b\u267f\u2692-\u2697\u2699\u269b\u269c\u26a0\u26a1\u26a7\u26aa\u26ab\u26b0\u26b1\u26bd\u26be\u26c4\u26c5\u26c8\u26cf\u26d1\u26d3\u26d4\u26e9\u26ea\u26f0-\u26f5\u26f8\u26fa\u26fd\u2702\u2708\u2709\u270f\u2712\u2714\u2716\u271d\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u2764\u27a1\u2934\u2935\u2b05-\u2b07\u2b1b\u2b1c\u2b50\u2b55\u3030\u303d\u3297\u3299])(?:\ufe0f|(?!\ufe0e))|(?:(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75\udd90]|[\u261d\u26f7\u26f9\u270c\u270d])(?:\ufe0f|(?!\ufe0e))|(?:\ud83c[\udf85\udfc2-\udfc4\udfc7\udfca]|\ud83d[\udc42\udc43\udc46-\udc50\udc66-\udc69\udc6e\udc70-\udc78\udc7c\udc81-\udc83\udc85-\udc87\udcaa\udd7a\udd95\udd96\ude45-\ude47\ude4b-\ude4f\udea3\udeb4-\udeb6\udec0\udecc]|\ud83e[\udd0f\udd18-\udd1c\udd1e\udd1f\udd26\udd30-\udd39\udd3d\udd3e\uddb5\uddb6\uddb8\uddb9\uddbb\uddcd-\uddcf\uddd1-\udddd]|[\u270a\u270b]))(?:\ud83c[\udffb-\udfff])?|(?:\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc73\udb40\udc63\udb40\udc74\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc77\udb40\udc6c\udb40\udc73\udb40\udc7f|\ud83c\udde6\ud83c[\udde8-\uddec\uddee\uddf1\uddf2\uddf4\uddf6-\uddfa\uddfc\uddfd\uddff]|\ud83c\udde7\ud83c[\udde6\udde7\udde9-\uddef\uddf1-\uddf4\uddf6-\uddf9\uddfb\uddfc\uddfe\uddff]|\ud83c\udde8\ud83c[\udde6\udde8\udde9\uddeb-\uddee\uddf0-\uddf5\uddf7\uddfa-\uddff]|\ud83c\udde9\ud83c[\uddea\uddec\uddef\uddf0\uddf2\uddf4\uddff]|\ud83c\uddea\ud83c[\udde6\udde8\uddea\uddec\udded\uddf7-\uddfa]|\ud83c\uddeb\ud83c[\uddee-\uddf0\uddf2\uddf4\uddf7]|\ud83c\uddec\ud83c[\udde6\udde7\udde9-\uddee\uddf1-\uddf3\uddf5-\uddfa\uddfc\uddfe]|\ud83c\udded\ud83c[\uddf0\uddf2\uddf3\uddf7\uddf9\uddfa]|\ud83c\uddee\ud83c[\udde8-\uddea\uddf1-\uddf4\uddf6-\uddf9]|\ud83c\uddef\ud83c[\uddea\uddf2\uddf4\uddf5]|\ud83c\uddf0\ud83c[\uddea\uddec-\uddee\uddf2\uddf3\uddf5\uddf7\uddfc\uddfe\uddff]|\ud83c\uddf1\ud83c[\udde6-\udde8\uddee\uddf0\uddf7-\uddfb\uddfe]|\ud83c\uddf2\ud83c[\udde6\udde8-\udded\uddf0-\uddff]|\ud83c\uddf3\ud83c[\udde6\udde8\uddea-\uddec\uddee\uddf1\uddf4\uddf5\uddf7\uddfa\uddff]|\ud83c\uddf4\ud83c\uddf2|\ud83c\uddf5\ud83c[\udde6\uddea-\udded\uddf0-\uddf3\uddf7-\uddf9\uddfc\uddfe]|\ud83c\uddf6\ud83c\udde6|\ud83c\uddf7\ud83c[\uddea\uddf4\uddf8\uddfa\uddfc]|\ud83c\uddf8\ud83c[\udde6-\uddea\uddec-\uddf4\uddf7-\uddf9\uddfb\uddfd-\uddff]|\ud83c\uddf9\ud83c[\udde6\udde8\udde9\uddeb-\udded\uddef-\uddf4\uddf7\uddf9\uddfb\uddfc\uddff]|\ud83c\uddfa\ud83c[\udde6\uddec\uddf2\uddf3\uddf8\uddfe\uddff]|\ud83c\uddfb\ud83c[\udde6\udde8\uddea\uddec\uddee\uddf3\uddfa]|\ud83c\uddfc\ud83c[\uddeb\uddf8]|\ud83c\uddfd\ud83c\uddf0|\ud83c\uddfe\ud83c[\uddea\uddf9]|\ud83c\uddff\ud83c[\udde6\uddf2\uddfc]|\ud83c[\udccf\udd8e\udd91-\udd9a\udde6-\uddff\ude01\ude32-\ude36\ude38-\ude3a\ude50\ude51\udf00-\udf20\udf2d-\udf35\udf37-\udf7c\udf7e-\udf84\udf86-\udf93\udfa0-\udfc1\udfc5\udfc6\udfc8\udfc9\udfcf-\udfd3\udfe0-\udff0\udff4\udff8-\udfff]|\ud83d[\udc00-\udc3e\udc40\udc44\udc45\udc51-\udc65\udc6a\udc6f\udc79-\udc7b\udc7d-\udc80\udc84\udc88-\udca9\udcab-\udcfc\udcff-\udd3d\udd4b-\udd4e\udd50-\udd67\udda4\uddfb-\ude44\ude48-\ude4a\ude80-\udea2\udea4-\udeb3\udeb7-\udebf\udec1-\udec5\uded0-\uded2\uded5\udeeb\udeec\udef4-\udefa\udfe0-\udfeb]|\ud83e[\udd0d\udd0e\udd10-\udd17\udd1d\udd20-\udd25\udd27-\udd2f\udd3a\udd3c\udd3f-\udd45\udd47-\udd71\udd73-\udd76\udd7a-\udda2\udda5-\uddaa\uddae-\uddb4\uddb7\uddba\uddbc-\uddca\uddd0\uddde-\uddff\ude70-\ude73\ude78-\ude7a\ude80-\ude82\ude90-\ude95]|[\u23e9-\u23ec\u23f0\u23f3\u267e\u26ce\u2705\u2728\u274c\u274e\u2753-\u2755\u2795-\u2797\u27b0\u27bf\ue50a])|\ufe0f/g;
// CONCATENATED MODULE: ./src/headless/converse-emoji.js
/**
 * @module converse-emoji
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */




const converse_emoji_u = converse.env.utils;
converse.emojis = {
  'initialized': false,
  'initialized_promise': converse_emoji_u.getResolveablePromise()
};
const ASCII_LIST = {
  '*\\0/*': '1f646',
  '*\\O/*': '1f646',
  '-___-': '1f611',
  ':\'-)': '1f602',
  '\':-)': '1f605',
  '\':-D': '1f605',
  '>:-)': '1f606',
  '\':-(': '1f613',
  '>:-(': '1f620',
  ':\'-(': '1f622',
  'O:-)': '1f607',
  '0:-3': '1f607',
  '0:-)': '1f607',
  '0;^)': '1f607',
  'O;-)': '1f607',
  '0;-)': '1f607',
  'O:-3': '1f607',
  '-__-': '1f611',
  ':-Þ': '1f61b',
  '</3': '1f494',
  ':\')': '1f602',
  ':-D': '1f603',
  '\':)': '1f605',
  '\'=)': '1f605',
  '\':D': '1f605',
  '\'=D': '1f605',
  '>:)': '1f606',
  '>;)': '1f606',
  '>=)': '1f606',
  ';-)': '1f609',
  '*-)': '1f609',
  ';-]': '1f609',
  ';^)': '1f609',
  '\':(': '1f613',
  '\'=(': '1f613',
  ':-*': '1f618',
  ':^*': '1f618',
  '>:P': '1f61c',
  'X-P': '1f61c',
  '>:[': '1f61e',
  ':-(': '1f61e',
  ':-[': '1f61e',
  '>:(': '1f620',
  ':\'(': '1f622',
  ';-(': '1f622',
  '>.<': '1f623',
  '#-)': '1f635',
  '%-)': '1f635',
  'X-)': '1f635',
  '\\0/': '1f646',
  '\\O/': '1f646',
  '0:3': '1f607',
  '0:)': '1f607',
  'O:)': '1f607',
  'O=)': '1f607',
  'O:3': '1f607',
  'B-)': '1f60e',
  '8-)': '1f60e',
  'B-D': '1f60e',
  '8-D': '1f60e',
  '-_-': '1f611',
  '>:\\': '1f615',
  '>:/': '1f615',
  ':-/': '1f615',
  ':-.': '1f615',
  ':-P': '1f61b',
  ':Þ': '1f61b',
  ':-b': '1f61b',
  ':-O': '1f62e',
  'O_O': '1f62e',
  '>:O': '1f62e',
  ':-X': '1f636',
  ':-#': '1f636',
  ':-)': '1f642',
  '(y)': '1f44d',
  '<3': '2764',
  ':D': '1f603',
  '=D': '1f603',
  ';)': '1f609',
  '*)': '1f609',
  ';]': '1f609',
  ';D': '1f609',
  ':*': '1f618',
  '=*': '1f618',
  ':(': '1f61e',
  ':[': '1f61e',
  '=(': '1f61e',
  ':@': '1f620',
  ';(': '1f622',
  'D:': '1f628',
  ':$': '1f633',
  '=$': '1f633',
  '#)': '1f635',
  '%)': '1f635',
  'X)': '1f635',
  'B)': '1f60e',
  '8)': '1f60e',
  ':/': '1f615',
  ':\\': '1f615',
  '=/': '1f615',
  '=\\': '1f615',
  ':L': '1f615',
  '=L': '1f615',
  ':P': '1f61b',
  '=P': '1f61b',
  ':b': '1f61b',
  ':O': '1f62e',
  ':X': '1f636',
  ':#': '1f636',
  '=X': '1f636',
  '=#': '1f636',
  ':)': '1f642',
  '=]': '1f642',
  '=)': '1f642',
  ':]': '1f642'
};

function toCodePoint(unicode_surrogates) {
  const r = [];
  let p = 0;
  let i = 0;

  while (i < unicode_surrogates.length) {
    const c = unicode_surrogates.charCodeAt(i++);

    if (p) {
      r.push((0x10000 + (p - 0xD800 << 10) + (c - 0xDC00)).toString(16));
      p = 0;
    } else if (0xD800 <= c && c <= 0xDBFF) {
      p = c;
    } else {
      r.push(c.toString(16));
    }
  }

  return r.join('-');
}

function fromCodePoint(codepoint) {
  let code = typeof codepoint === 'string' ? parseInt(codepoint, 16) : codepoint;

  if (code < 0x10000) {
    return String.fromCharCode(code);
  }

  code -= 0x10000;
  return String.fromCharCode(0xD800 + (code >> 10), 0xDC00 + (code & 0x3FF));
}

function converse_emoji_convert(unicode) {
  // Converts unicode code points and code pairs to their respective characters
  if (unicode.indexOf("-") > -1) {
    const parts = [],
          s = unicode.split('-');

    for (let i = 0; i < s.length; i++) {
      let part = parseInt(s[i], 16);

      if (part >= 0x10000 && part <= 0x10FFFF) {
        const hi = Math.floor((part - 0x10000) / 0x400) + 0xD800;
        const lo = (part - 0x10000) % 0x400 + 0xDC00;
        part = String.fromCharCode(hi) + String.fromCharCode(lo);
      } else {
        part = String.fromCharCode(part);
      }

      parts.push(part);
    }

    return parts.join('');
  }

  return fromCodePoint(unicode);
}

function unique(arr) {
  return [...new Set(arr)];
}

function getTonedEmojis() {
  if (!converse.emojis.toned) {
    converse.emojis.toned = unique(Object.values(converse.emojis.json.people).filter(person => person.sn.includes('_tone')).map(person => person.sn.replace(/_tone[1-5]/, '')));
  }

  return converse.emojis.toned;
}

function convertASCII2Emoji(str) {
  // Replace ASCII smileys
  return str.replace(ASCII_REPLACE_REGEX, (entire, m1, m2, m3) => {
    if (typeof m3 === 'undefined' || m3 === '' || !(converse_emoji_u.unescapeHTML(m3) in ASCII_LIST)) {
      // if the ascii doesnt exist just return the entire match
      return entire;
    }

    m3 = converse_emoji_u.unescapeHTML(m3);
    const unicode = ASCII_LIST[m3].toUpperCase();
    return m2 + converse_emoji_convert(unicode);
  });
}
function getEmojiMarkup(data, options = {
  unicode_only: false,
  add_title_wrapper: false
}) {
  const emoji = data.emoji;
  const shortname = data.shortname;

  if (emoji) {
    if (options.unicode_only) {
      return emoji;
    } else if (converse_core_api.settings.get('use_system_emojis')) {
      if (options.add_title_wrapper) {
        return shortname ? lit_html_html`<span title="${shortname}">${emoji}</span>` : emoji;
      } else {
        return emoji;
      }
    } else {
      const path = converse_core_api.settings.get('emoji_image_path');
      return lit_html_html`<img class="emoji"
                draggable="false"
                title="${shortname}"
                alt="${emoji}"
                src="${path}/72x72/${data.cp}.png"/>`;
    }
  } else if (options.unicode_only) {
    return shortname;
  } else {
    return lit_html_html`<img class="emoji"
            draggable="false"
            title="${shortname}"
            alt="${shortname}"
            src="${converse.emojis.by_sn[shortname].url}">`;
  }
}
function getShortnameReferences(text) {
  if (!converse.emojis.initialized) {
    throw new Error('getShortnameReferences called before emojis are initialized. ' + 'To avoid this problem, first await the converse.emojis.initilaized_promise.');
  }

  const references = [...text.matchAll(converse.emojis.shortnames_regex)].filter(ref => ref[0].length > 0);
  return references.map(ref => {
    const cp = converse.emojis.by_sn[ref[0]].cp;
    return {
      cp,
      'begin': ref.index,
      'end': ref.index + ref[0].length,
      'shortname': ref[0],
      'emoji': cp ? converse_emoji_convert(cp) : null
    };
  });
}

function parseStringForEmojis(str, callback) {
  const UFE0Fg = /\uFE0F/g;
  const U200D = String.fromCharCode(0x200D);
  return String(str).replace(CODEPOINTS_REGEX, (emoji, _, offset) => {
    const icon_id = toCodePoint(emoji.indexOf(U200D) < 0 ? emoji.replace(UFE0Fg, '') : emoji);
    if (icon_id) callback(icon_id, emoji, offset);
  });
}

function getCodePointReferences(text) {
  const references = [];
  parseStringForEmojis(text, (icon_id, emoji, offset) => {
    var _u$getEmojisByAtrribu;

    references.push({
      'begin': offset,
      'cp': icon_id,
      'emoji': emoji,
      'end': offset + emoji.length,
      'shortname': ((_u$getEmojisByAtrribu = converse_emoji_u.getEmojisByAtrribute('cp')[icon_id]) === null || _u$getEmojisByAtrribu === void 0 ? void 0 : _u$getEmojisByAtrribu.sn) || ''
    });
  });
  return references;
}

function addEmojisMarkup(text, options) {
  let list = [text];
  [...getShortnameReferences(text), ...getCodePointReferences(text)].sort((a, b) => b.begin - a.begin).forEach(ref => {
    const text = list.shift();
    const emoji = getEmojiMarkup(ref, options);

    if (typeof emoji === 'string') {
      list = [text.slice(0, ref.begin) + emoji + text.slice(ref.end), ...list];
    } else {
      list = [text.slice(0, ref.begin), emoji, text.slice(ref.end), ...list];
    }
  });
  return list;
}

converse.plugins.add('converse-emoji', {
  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    const {
      ___
    } = converse_core_converse;
    converse_core_api.settings.extend({
      'emoji_image_path': 'https://twemoji.maxcdn.com/v/12.1.6/',
      'emoji_categories': {
        "smileys": ":grinning:",
        "people": ":thumbsup:",
        "activity": ":soccer:",
        "travel": ":motorcycle:",
        "objects": ":bomb:",
        "nature": ":rainbow:",
        "food": ":hotdog:",
        "symbols": ":musical_note:",
        "flags": ":flag_ac:",
        "custom": null
      },
      // We use the triple-underscore method which doesn't actually
      // translate but does signify to gettext that these strings should
      // go into the POT file. The translation then happens in the
      // template. We do this so that users can pass in their own
      // strings via converse.initialize, which is before __ is
      // available.
      'emoji_category_labels': {
        "smileys": ___("Smileys and emotions"),
        "people": ___("People"),
        "activity": ___("Activities"),
        "travel": ___("Travel"),
        "objects": ___("Objects"),
        "nature": ___("Animals and nature"),
        "food": ___("Food and drink"),
        "symbols": ___("Symbols"),
        "flags": ___("Flags"),
        "custom": ___("Stickers")
      }
    });
    /**
     * Model for storing data related to the Emoji picker widget
     * @class
     * @namespace _converse.EmojiPicker
     * @memberOf _converse
     */

    converse_core_converse.EmojiPicker = model_Model.extend({
      defaults: {
        'current_category': 'smileys',
        'current_skintone': '',
        'scroll_position': 0
      }
    });
    /************************ BEGIN Utils ************************/
    // Closured cache

    const emojis_by_attribute = {};
    Object.assign(converse_emoji_u, {
      /**
       * Returns an emoji represented by the passed in shortname.
       * Scans the passed in text for shortnames and replaces them with
       * emoji unicode glyphs or alternatively if it's a custom emoji
       * without unicode representation then a lit-html TemplateResult
       * which represents image tag markup is returned.
       *
       * The shortname needs to be defined in `emojis.json`
       * and needs to have either a `cp` attribute for the codepoint, or
       * an `url` attribute which points to the source for the image.
       *
       * @method u.shortnamesToEmojis
       * @param { String } str - String containg the shortname(s)
       * @param { Object } options
       * @param { Boolean } options.unicode_only - Whether emojis are rendered as
       *  unicode codepoints. If so, the returned result will be an array
       *  with containing one string, because the emojis themselves will
       *  also be strings. If set to false, emojis will be represented by
       *  lit-html TemplateResult objects.
       * @param { Boolean } options.add_title_wrapper - Whether unicode
       *  codepoints should be wrapped with a `<span>` element with a
       *  title, so that the shortname is shown upon hovering with the
       *  mouse.
       * @returns {Array} An array of at least one string, or otherwise
       * strings and lit-html TemplateResult objects.
       */
      shortnamesToEmojis(str, options = {
        unicode_only: false,
        add_title_wrapper: false
      }) {
        str = convertASCII2Emoji(str);
        return addEmojisMarkup(str, options);
      },

      /**
       * Replaces all shortnames in the passed in string with their
       * unicode (emoji) representation.
       * @method u.shortnamesToUnicode
       * @param { String } str - String containing the shortname(s)
       * @returns { String }
       */
      shortnamesToUnicode(str) {
        return converse_emoji_u.shortnamesToEmojis(str, {
          'unicode_only': true
        })[0];
      },

      /**
       * Determines whether the passed in string is just a single emoji shortname;
       * @method u.isOnlyEmojis
       * @param { String } shortname - A string which migh be just an emoji shortname
       * @returns { Boolean }
       */
      isOnlyEmojis(text) {
        const words = text.trim().split(/\s+/);

        if (words.length === 0 || words.length > 3) {
          return false;
        }

        const emojis = words.filter(text => {
          const refs = getCodePointReferences(converse_emoji_u.shortnamesToUnicode(text));
          return refs.length === 1 && (text === refs[0]['shortname'] || text === refs[0]['emoji']);
        });
        return emojis.length === words.length;
      },

      /**
       * @method u.getEmojisByAtrribute
       * @param { String } attr - The attribute according to which the
       *  returned map should be keyed.
       * @returns { Object } - Map of emojis with the passed in attribute values
       *  as keys and a list of emojis for a particular category as values.
       */
      getEmojisByAtrribute(attr) {
        if (emojis_by_attribute[attr]) {
          return emojis_by_attribute[attr];
        }

        if (attr === 'category') {
          return converse.emojis.json;
        }

        const all_variants = converse.emojis.list.map(e => e[attr]).filter((c, i, arr) => arr.indexOf(c) == i);
        emojis_by_attribute[attr] = {};
        all_variants.forEach(v => emojis_by_attribute[attr][v] = converse.emojis.list.find(i => i[attr] === v));
        return emojis_by_attribute[attr];
      }

    });
    /************************ END Utils ************************/

    /************************ BEGIN API ************************/
    // We extend the default converse.js API to add methods specific to MUC groupchats.

    Object.assign(converse_core_api, {
      /**
       * @namespace api.emojis
       * @memberOf api
       */
      emojis: {
        /**
         * Initializes Emoji support by downloading the emojis JSON (and any applicable images).
         * @method api.emojis.initialize
         * @returns {Promise}
         */
        async initialize() {
          if (!converse.emojis.initialized) {
            converse.emojis.initialized = true;
            const {
              default: json
            } = await __webpack_require__.e(/* import() | emojis */ 137).then(__webpack_require__.t.bind(null, 542, 3));
            converse.emojis.json = json;
            converse.emojis.by_sn = Object.keys(json).reduce((result, cat) => Object.assign(result, json[cat]), {});
            converse.emojis.list = Object.values(converse.emojis.by_sn);
            converse.emojis.list.sort((a, b) => a.sn < b.sn ? -1 : a.sn > b.sn ? 1 : 0);
            converse.emojis.shortnames = converse.emojis.list.map(m => m.sn);

            const getShortNames = () => converse.emojis.shortnames.map(s => s.replace(/[+]/g, "\\$&")).join('|');

            converse.emojis.shortnames_regex = new RegExp(getShortNames(), "gi");
            converse.emojis.toned = getTonedEmojis();
            converse.emojis.initialized_promise.resolve();
          }

          return converse.emojis.initialized_promise;
        }

      }
    });
  }

});
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseZipObject.js
/**
 * This base implementation of `_.zipObject` which assigns values using `assignFunc`.
 *
 * @private
 * @param {Array} props The property identifiers.
 * @param {Array} values The property values.
 * @param {Function} assignFunc The function to assign values.
 * @returns {Object} Returns the new object.
 */
function baseZipObject(props, values, assignFunc) {
  var index = -1,
      length = props.length,
      valsLength = values.length,
      result = {};

  while (++index < length) {
    var value = index < valsLength ? values[index] : undefined;
    assignFunc(result, props[index], value);
  }

  return result;
}

/* harmony default export */ var _baseZipObject = (baseZipObject);
// CONCATENATED MODULE: ./node_modules/lodash-es/zipObject.js


/**
 * This method is like `_.fromPairs` except that it accepts two arrays,
 * one of property identifiers and one of corresponding values.
 *
 * @static
 * @memberOf _
 * @since 0.4.0
 * @category Array
 * @param {Array} [props=[]] The property identifiers.
 * @param {Array} [values=[]] The property values.
 * @returns {Object} Returns the new object.
 * @example
 *
 * _.zipObject(['a', 'b'], [1, 2]);
 * // => { 'a': 1, 'b': 2 }
 */

function zipObject(props, values) {
  return _baseZipObject(props || [], values || [], _assignValue);
}

/* harmony default export */ var lodash_es_zipObject = (zipObject);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIntersection.js






/* Built-in method references for those with the same name as other `lodash` methods. */

var _baseIntersection_nativeMin = Math.min;
/**
 * The base implementation of methods like `_.intersection`, without support
 * for iteratee shorthands, that accepts an array of arrays to inspect.
 *
 * @private
 * @param {Array} arrays The arrays to inspect.
 * @param {Function} [iteratee] The iteratee invoked per element.
 * @param {Function} [comparator] The comparator invoked per element.
 * @returns {Array} Returns the new array of shared values.
 */

function baseIntersection(arrays, iteratee, comparator) {
  var includes = comparator ? _arrayIncludesWith : _arrayIncludes,
      length = arrays[0].length,
      othLength = arrays.length,
      othIndex = othLength,
      caches = Array(othLength),
      maxLength = Infinity,
      result = [];

  while (othIndex--) {
    var array = arrays[othIndex];

    if (othIndex && iteratee) {
      array = _arrayMap(array, _baseUnary(iteratee));
    }

    maxLength = _baseIntersection_nativeMin(array.length, maxLength);
    caches[othIndex] = !comparator && (iteratee || length >= 120 && array.length >= 120) ? new _SetCache(othIndex && array) : undefined;
  }

  array = arrays[0];
  var index = -1,
      seen = caches[0];

  outer: while (++index < length && result.length < maxLength) {
    var value = array[index],
        computed = iteratee ? iteratee(value) : value;
    value = comparator || value !== 0 ? value : 0;

    if (!(seen ? _cacheHas(seen, computed) : includes(result, computed, comparator))) {
      othIndex = othLength;

      while (--othIndex) {
        var cache = caches[othIndex];

        if (!(cache ? _cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator))) {
          continue outer;
        }
      }

      if (seen) {
        seen.push(computed);
      }

      result.push(value);
    }
  }

  return result;
}

/* harmony default export */ var _baseIntersection = (baseIntersection);
// CONCATENATED MODULE: ./node_modules/lodash-es/_castArrayLikeObject.js

/**
 * Casts `value` to an empty array if it's not an array like object.
 *
 * @private
 * @param {*} value The value to inspect.
 * @returns {Array|Object} Returns the cast array-like object.
 */

function castArrayLikeObject(value) {
  return lodash_es_isArrayLikeObject(value) ? value : [];
}

/* harmony default export */ var _castArrayLikeObject = (castArrayLikeObject);
// CONCATENATED MODULE: ./node_modules/lodash-es/intersection.js




/**
 * Creates an array of unique values that are included in all given arrays
 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons. The order and references of result values are
 * determined by the first array.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {...Array} [arrays] The arrays to inspect.
 * @returns {Array} Returns the new array of intersecting values.
 * @example
 *
 * _.intersection([2, 1], [2, 3]);
 * // => [2]
 */

var intersection = _baseRest(function (arrays) {
  var mapped = _arrayMap(arrays, _castArrayLikeObject);
  return mapped.length && mapped[0] === arrays[0] ? _baseIntersection(mapped) : [];
});
/* harmony default export */ var lodash_es_intersection = (intersection);
// CONCATENATED MODULE: ./src/headless/utils/muc.js
/**
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description This is the MUC utilities module.
 */



const {
  Strophe: muc_Strophe,
  sizzle: muc_sizzle
} = converse.env;
/**
 * The MUC utils object. Contains utility functions related to multi-user chat.
 * @namespace muc_utils
 */

const muc_utils = {
  /**
   * Given two lists of objects with 'jid', 'affiliation' and
   * 'reason' properties, return a new list containing
   * those objects that are new, changed or removed
   * (depending on the 'remove_absentees' boolean).
   *
   * The affiliations for new and changed members stay the
   * same, for removed members, the affiliation is set to 'none'.
   *
   * The 'reason' property is not taken into account when
   * comparing whether affiliations have been changed.
   * @private
   * @method muc_utils#computeAffiliationsDelta
   * @param { boolean } exclude_existing - Indicates whether JIDs from
   *      the new list which are also in the old list
   *      (regardless of affiliation) should be excluded
   *      from the delta. One reason to do this
   *      would be when you want to add a JID only if it
   *      doesn't have *any* existing affiliation at all.
   * @param { boolean } remove_absentees - Indicates whether JIDs
   *      from the old list which are not in the new list
   *      should be considered removed and therefore be
   *      included in the delta with affiliation set
   *      to 'none'.
   * @param { array } new_list - Array containing the new affiliations
   * @param { array } old_list - Array containing the old affiliations
   * @returns { array }
   */
  computeAffiliationsDelta(exclude_existing, remove_absentees, new_list, old_list) {
    const new_jids = new_list.map(o => o.jid);
    const old_jids = old_list.map(o => o.jid); // Get the new affiliations

    let delta = lodash_es_difference(new_jids, old_jids).map(jid => new_list[lodash_es_indexOf(new_jids, jid)]);

    if (!exclude_existing) {
      // Get the changed affiliations
      delta = delta.concat(new_list.filter(item => {
        const idx = lodash_es_indexOf(old_jids, item.jid);
        return idx >= 0 ? item.affiliation !== old_list[idx].affiliation : false;
      }));
    }

    if (remove_absentees) {
      // Get the removed affiliations
      delta = delta.concat(lodash_es_difference(old_jids, new_jids).map(jid => ({
        'jid': jid,
        'affiliation': 'none'
      })));
    }

    return delta;
  },

  /**
   * Given an IQ stanza with a member list, create an array of objects containing
   * known member data (e.g. jid, nick, role, affiliation).
   * @private
   * @method muc_utils#parseMemberListIQ
   * @returns { MemberListItem[] }
   */
  parseMemberListIQ(iq) {
    return muc_sizzle(`query[xmlns="${muc_Strophe.NS.MUC_ADMIN}"] item`, iq).map(item => {
      /**
       * @typedef {Object} MemberListItem
       * Either the JID or the nickname (or both) will be available.
       * @property {string} affiliation
       * @property {string} [role]
       * @property {string} [jid]
       * @property {string} [nick]
       */
      const data = {
        'affiliation': item.getAttribute('affiliation')
      };
      const jid = item.getAttribute('jid');

      if (utils_core.isValidJID(jid)) {
        data['jid'] = jid;
      } else {
        // XXX: Prosody sends nick for the jid attribute value
        // Perhaps for anonymous room?
        data['nick'] = jid;
      }

      const nick = item.getAttribute('nick');

      if (nick) {
        data['nick'] = nick;
      }

      const role = item.getAttribute('role');

      if (role) {
        data['role'] = nick;
      }

      return data;
    });
  }

};
/* harmony default export */ var utils_muc = (muc_utils);
// CONCATENATED MODULE: ./src/headless/utils/form.js
/**
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description This is the form utilities module.
 */

/**
 * Takes an HTML DOM and turns it into an XForm field.
 * @private
 * @method u#webForm2xForm
 * @param { DOMElement } field - the field to convert
 */

utils_core.webForm2xForm = function (field) {
  const name = field.getAttribute('name');

  if (!name) {
    return null; // See #1924
  }

  let value;

  if (field.getAttribute('type') === 'checkbox') {
    value = field.checked && 1 || 0;
  } else if (field.tagName == "TEXTAREA") {
    value = field.value.split('\n').filter(s => s.trim());
  } else if (field.tagName == "SELECT") {
    value = utils_core.getSelectValues(field);
  } else {
    value = field.value;
  }

  return utils_core.toStanza(`
        <field var="${name}">
            ${value.constructor === Array ? value.map(v => `<value>${v}</value>`) : `<value>${value}</value>`}
        </field>`);
};

/* harmony default export */ var utils_form = (utils_core);
// CONCATENATED MODULE: ./src/headless/utils/parse-helpers.js
/**
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description Pure functions to help funcitonally parse messages.
 * @todo Other parsing helpers can be made more abstract and placed here.
 */
const helpers = {}; // Captures all mentions, but includes a space before the @

helpers.mention_regex = /(?:\s|^)([@][\w_-]+(?:\.\w+)*)/ig;

helpers.matchRegexInText = text => regex => text.matchAll(regex);

const escapeRegexChars = (string, char) => string.replace(RegExp('\\' + char, 'ig'), '\\' + char);

helpers.escapeCharacters = characters => string => characters.split('').reduce(escapeRegexChars, string);

helpers.escapeRegexString = helpers.escapeCharacters('[\\^$.?*+(){}'); // `for` is ~25% faster than using `Array.find()`

helpers.findFirstMatchInArray = array => text => {
  for (let i = 0; i < array.length; i++) {
    if (text.localeCompare(array[i], undefined, {
      sensitivity: 'base'
    }) === 0) {
      return array[i];
    }
  }

  return null;
};

const reduceReferences = ([text, refs], ref, index) => {
  let updated_text = text;
  let {
    begin,
    end
  } = ref;
  const {
    value
  } = ref;
  begin = begin - index;
  end = end - index - 1; // -1 to compensate for the removed @

  updated_text = `${updated_text.slice(0, begin)}${value}${updated_text.slice(end + 1)}`;
  return [updated_text, [...refs, { ...ref,
    begin,
    end
  }]];
};

helpers.reduceTextFromReferences = (text, refs) => refs.reduce(reduceReferences, [text, []]);

/* harmony default export */ var parse_helpers = (helpers);
// CONCATENATED MODULE: ./src/headless/converse-muc.js
/**
 * @module converse-muc
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description Implements the non-view logic for XEP-0045 Multi-User Chat
 */












const ROLES = ['moderator', 'participant', 'visitor'];
const AFFILIATIONS = ['owner', 'admin', 'member', 'outcast', 'none'];
converse.MUC_TRAFFIC_STATES = ['entered', 'exited'];
converse.MUC_ROLE_CHANGES = ['op', 'deop', 'voice', 'mute'];
const ACTION_INFO_CODES = ['301', '303', '333', '307', '321', '322'];
const MUC_ROLE_WEIGHTS = {
  'moderator': 1,
  'participant': 2,
  'visitor': 3,
  'none': 2
};
const {
  Strophe: converse_muc_Strophe,
  $iq: converse_muc_$iq,
  $build,
  $msg: converse_muc_$msg,
  $pres,
  sizzle: converse_muc_sizzle
} = converse.env; // Add Strophe Namespaces

converse_muc_Strophe.addNamespace('MUC_ADMIN', converse_muc_Strophe.NS.MUC + "#admin");
converse_muc_Strophe.addNamespace('MUC_OWNER', converse_muc_Strophe.NS.MUC + "#owner");
converse_muc_Strophe.addNamespace('MUC_REGISTER', "jabber:iq:register");
converse_muc_Strophe.addNamespace('MUC_ROOMCONF', converse_muc_Strophe.NS.MUC + "#roomconfig");
converse_muc_Strophe.addNamespace('MUC_USER', converse_muc_Strophe.NS.MUC + "#user");
converse_muc_Strophe.addNamespace('MUC_HATS', "xmpp:prosody.im/protocol/hats:1");
converse.MUC_NICK_CHANGED_CODE = "303";
converse.ROOM_FEATURES = ['passwordprotected', 'unsecured', 'hidden', 'publicroom', 'membersonly', 'open', 'persistent', 'temporary', 'nonanonymous', 'semianonymous', 'moderated', 'unmoderated', 'mam_enabled']; // No longer used in code, but useful as reference.
//
// const ROOM_FEATURES_MAP = {
//     'passwordprotected': 'unsecured',
//     'unsecured': 'passwordprotected',
//     'hidden': 'publicroom',
//     'publicroom': 'hidden',
//     'membersonly': 'open',
//     'open': 'membersonly',
//     'persistent': 'temporary',
//     'temporary': 'persistent',
//     'nonanonymous': 'semianonymous',
//     'semianonymous': 'nonanonymous',
//     'moderated': 'unmoderated',
//     'unmoderated': 'moderated'
// };

converse.ROOMSTATUS = {
  CONNECTED: 0,
  CONNECTING: 1,
  NICKNAME_REQUIRED: 2,
  PASSWORD_REQUIRED: 3,
  DISCONNECTED: 4,
  ENTERED: 5,
  DESTROYED: 6
};
converse.plugins.add('converse-muc', {
  /* Optional dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin. They are called "optional" because they might not be
   * available, in which case any overrides applicable to them will be
   * ignored.
   *
   * It's possible however to make optional dependencies non-optional.
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found.
   *
   * NB: These plugins need to have already been loaded via require.js.
   */
  dependencies: ["converse-chatboxes", "converse-chat", "converse-disco", "converse-controlbox"],
  overrides: {
    ChatBoxes: {
      model(attrs, options) {
        const {
          _converse
        } = this.__super__;

        if (attrs && attrs.type == _converse.CHATROOMS_TYPE) {
          return new _converse.ChatRoom(attrs, options);
        } else {
          return this.__super__.model.apply(this, arguments);
        }
      }

    }
  },

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    const {
      __,
      ___
    } = converse_core_converse; // Configuration values for this plugin
    // ====================================
    // Refer to docs/source/configuration.rst for explanations of these
    // configuration settings.

    converse_core_api.settings.extend({
      'allow_muc': true,
      'allow_muc_invitations': true,
      'auto_join_on_invite': false,
      'auto_join_rooms': [],
      'auto_register_muc_nickname': false,
      'hide_muc_participants': false,
      'locked_muc_domain': false,
      'muc_domain': undefined,
      'muc_fetch_members': true,
      'muc_history_max_stanzas': undefined,
      'muc_instant_rooms': true,
      'muc_nickname_from_jid': false,
      'muc_send_probes': false,
      'muc_show_join_leave': true,
      'muc_show_logs_before_join': false
    });
    converse_core_api.promises.add(['roomsAutoJoined']);

    if (converse_core_api.settings.get('locked_muc_domain') && typeof converse_core_api.settings.get('muc_domain') !== 'string') {
      throw new Error("Config Error: it makes no sense to set locked_muc_domain " + "to true when muc_domain is not set");
    }
    /* https://xmpp.org/extensions/xep-0045.html
     * ----------------------------------------
     * 100 message      Entering a groupchat         Inform user that any occupant is allowed to see the user's full JID
     * 101 message (out of band)                     Affiliation change  Inform user that his or her affiliation changed while not in the groupchat
     * 102 message      Configuration change         Inform occupants that groupchat now shows unavailable members
     * 103 message      Configuration change         Inform occupants that groupchat now does not show unavailable members
     * 104 message      Configuration change         Inform occupants that a non-privacy-related groupchat configuration change has occurred
     * 110 presence     Any groupchat presence       Inform user that presence refers to one of its own groupchat occupants
     * 170 message or initial presence               Configuration change    Inform occupants that groupchat logging is now enabled
     * 171 message      Configuration change         Inform occupants that groupchat logging is now disabled
     * 172 message      Configuration change         Inform occupants that the groupchat is now non-anonymous
     * 173 message      Configuration change         Inform occupants that the groupchat is now semi-anonymous
     * 174 message      Configuration change         Inform occupants that the groupchat is now fully-anonymous
     * 201 presence     Entering a groupchat         Inform user that a new groupchat has been created
     * 210 presence     Entering a groupchat         Inform user that the service has assigned or modified the occupant's roomnick
     * 301 presence     Removal from groupchat       Inform user that he or she has been banned from the groupchat
     * 303 presence     Exiting a groupchat          Inform all occupants of new groupchat nickname
     * 307 presence     Removal from groupchat       Inform user that he or she has been kicked from the groupchat
     * 321 presence     Removal from groupchat       Inform user that he or she is being removed from the groupchat because of an affiliation change
     * 322 presence     Removal from groupchat       Inform user that he or she is being removed from the groupchat because the groupchat has been changed to members-only and the user is not a member
     * 332 presence     Removal from groupchat       Inform user that he or she is being removed from the groupchat because of a system shutdown
     */


    converse_core_converse.muc = {
      info_messages: {
        100: __('This groupchat is not anonymous'),
        102: __('This groupchat now shows unavailable members'),
        103: __('This groupchat does not show unavailable members'),
        104: __('The groupchat configuration has changed'),
        170: __('Groupchat logging is now enabled'),
        171: __('Groupchat logging is now disabled'),
        172: __('This groupchat is now no longer anonymous'),
        173: __('This groupchat is now semi-anonymous'),
        174: __('This groupchat is now fully-anonymous'),
        201: __('A new groupchat has been created')
      },
      new_nickname_messages: {
        // XXX: Note the triple underscore function and not double underscore.
        210: ___('Your nickname has been automatically set to %1$s'),
        303: ___('Your nickname has been changed to %1$s')
      },
      disconnect_messages: {
        301: __('You have been banned from this groupchat'),
        333: __('You have exited this groupchat due to a technical problem'),
        307: __('You have been kicked from this groupchat'),
        321: __("You have been removed from this groupchat because of an affiliation change"),
        322: __("You have been removed from this groupchat because the groupchat has changed to members-only and you're not a member"),
        332: __("You have been removed from this groupchat because the service hosting it is being shut down")
      }
    };

    async function openRoom(jid) {
      if (!utils_form.isValidMUCJID(jid)) {
        return headless_log.warn(`invalid jid "${jid}" provided in url fragment`);
      }

      await converse_core_api.waitUntil('roomsAutoJoined');

      if (converse_core_api.settings.get('allow_bookmarks')) {
        await converse_core_api.waitUntil('bookmarksInitialized');
      }

      converse_core_api.rooms.open(jid);
    }

    converse_core_converse.router.route('converse/room?jid=:jid', openRoom);

    converse_core_converse.getDefaultMUCNickname = function () {
      // XXX: if anything changes here, update the docs for the
      // locked_muc_nickname setting.
      if (!converse_core_converse.xmppstatus) {
        throw new Error("Can't call _converse.getDefaultMUCNickname before the statusInitialized has been fired.");
      }

      const nick = converse_core_converse.xmppstatus.getNickname();

      if (nick) {
        return nick;
      } else if (converse_core_api.settings.get('muc_nickname_from_jid')) {
        return converse_muc_Strophe.unescapeNode(converse_muc_Strophe.getNodeFromJid(converse_core_converse.bare_jid));
      }
    };

    async function openChatRoom(jid, settings) {
      /* Opens a groupchat, making sure that certain attributes
       * are correct, for example that the "type" is set to
       * "chatroom".
       */
      settings.type = converse_core_converse.CHATROOMS_TYPE;
      settings.id = jid;
      const chatbox = await converse_core_api.rooms.get(jid, settings, true);
      chatbox.maybeShow(true);
      return chatbox;
    }
    /**
     * Represents a MUC message
     * @class
     * @namespace _converse.ChatRoomMessage
     * @memberOf _converse
     */


    converse_core_converse.ChatRoomMessage = converse_core_converse.Message.extend({
      initialize() {
        if (!this.checkValidity()) {
          return;
        }

        if (this.get('file')) {
          this.on('change:put', this.uploadFile, this);
        }

        if (!this.setTimerForEphemeralMessage()) {
          this.setOccupant();
        }
        /**
         * Triggered once a {@link _converse.ChatRoomMessageInitialized} has been created and initialized.
         * @event _converse#chatRoomMessageInitialized
         * @type { _converse.ChatRoomMessages}
         * @example _converse.api.listen.on('chatRoomMessageInitialized', model => { ... });
         */


        converse_core_api.trigger('chatRoomMessageInitialized', this);
      },

      /**
       * Determines whether this messsage may be moderated,
       * based on configuration settings and server support.
       * @async
       * @private
       * @method _converse.ChatRoomMessages#mayBeModerated
       * @returns { Boolean }
       */
      mayBeModerated() {
        return ['all', 'moderator'].includes(converse_core_api.settings.get('allow_message_retraction')) && this.collection.chatbox.canModerateMessages();
      },

      checkValidity() {
        const result = converse_core_converse.Message.prototype.checkValidity.call(this);

        !result && this.collection.chatbox.debouncedRejoin();
        return result;
      },

      onOccupantRemoved() {
        var _this$collection;

        this.stopListening(this.occupant);
        delete this.occupant;
        const chatbox = this === null || this === void 0 ? void 0 : (_this$collection = this.collection) === null || _this$collection === void 0 ? void 0 : _this$collection.chatbox;

        if (!chatbox) {
          return headless_log.error(`Could not get collection.chatbox for message: ${JSON.stringify(this.toJSON())}`);
        }

        this.listenTo(chatbox.occupants, 'add', this.onOccupantAdded);
      },

      onOccupantAdded(occupant) {
        if (occupant.get('nick') === converse_muc_Strophe.getResourceFromJid(this.get('from'))) {
          var _this$collection2;

          this.occupant = occupant;
          this.trigger('occupantAdded');
          this.listenTo(this.occupant, 'destroy', this.onOccupantRemoved);
          const chatbox = this === null || this === void 0 ? void 0 : (_this$collection2 = this.collection) === null || _this$collection2 === void 0 ? void 0 : _this$collection2.chatbox;

          if (!chatbox) {
            return headless_log.error(`Could not get collection.chatbox for message: ${JSON.stringify(this.toJSON())}`);
          }

          this.stopListening(chatbox.occupants, 'add', this.onOccupantAdded);
        }
      },

      setOccupant() {
        var _this$collection3;

        if (this.get('type') !== 'groupchat') {
          return;
        }

        const chatbox = this === null || this === void 0 ? void 0 : (_this$collection3 = this.collection) === null || _this$collection3 === void 0 ? void 0 : _this$collection3.chatbox;

        if (!chatbox) {
          return headless_log.error(`Could not get collection.chatbox for message: ${JSON.stringify(this.toJSON())}`);
        }

        const nick = converse_muc_Strophe.getResourceFromJid(this.get('from'));
        this.occupant = chatbox.occupants.findWhere({
          nick
        });

        if (!this.occupant && converse_core_api.settings.get("muc_send_probes")) {
          this.occupant = chatbox.occupants.create({
            nick,
            'type': 'unavailable'
          });
          const jid = `${chatbox.get('jid')}/${nick}`;
          converse_core_api.user.presence.send('probe', jid);
        }

        if (this.occupant) {
          this.listenTo(this.occupant, 'destroy', this.onOccupantRemoved);
        } else {
          this.listenTo(chatbox.occupants, 'add', this.onOccupantAdded);
        }
      }

    });
    const MUCSession = model_Model.extend({
      defaults() {
        return {
          'connection_status': converse.ROOMSTATUS.DISCONNECTED
        };
      }

    });
    /**
     * Collection which stores MUC messages
     * @class
     * @namespace _converse.ChatRoomMessages
     * @memberOf _converse
     */

    converse_core_converse.ChatRoomMessages = Collection.extend({
      model: converse_core_converse.ChatRoomMessage,
      comparator: 'time'
    });
    /**
     * Represents an open/ongoing groupchat conversation.
     * @class
     * @namespace _converse.ChatRoom
     * @memberOf _converse
     */

    converse_core_converse.ChatRoom = converse_core_converse.ChatBox.extend({
      messagesCollection: converse_core_converse.ChatRoomMessages,

      defaults() {
        return {
          // For group chats, we distinguish between generally unread
          // messages and those ones that specifically mention the
          // user.
          //
          // To keep things simple, we reuse `num_unread` from
          // _converse.ChatBox to indicate unread messages which
          // mention the user and `num_unread_general` to indicate
          // generally unread messages (which *includes* mentions!).
          'num_unread_general': 0,
          'bookmarked': false,
          'chat_state': undefined,
          'hidden': converse_core_converse.isUniView() && !converse_core_api.settings.get('singleton'),
          'hidden_occupants': !!converse_core_api.settings.get('hide_muc_participants'),
          'message_type': 'groupchat',
          'name': '',
          'num_unread': 0,
          'roomconfig': {},
          'time_opened': this.get('time_opened') || new Date().getTime(),
          'time_sent': new Date(0).toISOString(),
          'type': converse_core_converse.CHATROOMS_TYPE
        };
      },

      async initialize() {
        this.initialized = utils_form.getResolveablePromise();
        this.debouncedRejoin = lodash_es_debounce(this.rejoin, 250);
        this.set('box_id', `box-${this.get('jid')}`);
        this.initNotifications();
        this.initMessages();
        this.initOccupants();
        this.initDiscoModels(); // sendChatState depends on this.features

        this.registerHandlers();
        this.on('change:chat_state', this.sendChatState, this);
        await this.restoreSession();
        this.session.on('change:connection_status', this.onConnectionStatusChanged, this);
        this.listenTo(this.occupants, 'add', this.onOccupantAdded);
        this.listenTo(this.occupants, 'remove', this.onOccupantRemoved);
        this.listenTo(this.occupants, 'change:show', this.onOccupantShowChanged);
        this.listenTo(this.occupants, 'change:affiliation', this.createAffiliationChangeMessage);
        this.listenTo(this.occupants, 'change:role', this.createRoleChangeMessage);
        const restored = await this.restoreFromCache();

        if (!restored) {
          this.join();
        }
        /**
         * Triggered once a {@link _converse.ChatRoom} has been created and initialized.
         * @event _converse#chatRoomInitialized
         * @type { _converse.ChatRoom }
         * @example _converse.api.listen.on('chatRoomInitialized', model => { ... });
         */


        await converse_core_api.trigger('chatRoomInitialized', this, {
          'Synchronous': true
        });
        this.initialized.resolve();
      },

      /**
       * Checks whether we're still joined and if so, restores the MUC state from cache.
       * @private
       * @method _converse.ChatRoom#restoreFromCache
       * @returns { Boolean } Returns `true` if we're still joined, otherwise returns `false`.
       */
      async restoreFromCache() {
        if (this.session.get('connection_status') === converse.ROOMSTATUS.ENTERED && (await this.isJoined())) {
          // We've restored the room from cache and we're still joined.
          await new Promise(resolve => this.features.fetch({
            'success': resolve,
            'error': resolve
          }));
          await this.fetchOccupants().catch(e => headless_log.error(e));
          await this.fetchMessages().catch(e => headless_log.error(e));
          return true;
        } else {
          await this.clearCache();
          return false;
        }
      },

      /**
       * Join the MUC
       * @private
       * @method _converse.ChatRoom#join
       * @param { String } nick - The user's nickname
       * @param { String } [password] - Optional password, if required by the groupchat.
       *  Will fall back to the `password` value stored in the room
       *  model (if available).
       */
      async join(nick, password) {
        if (this.session.get('connection_status') === converse.ROOMSTATUS.ENTERED) {
          // We have restored a groupchat from session storage,
          // so we don't send out a presence stanza again.
          return this;
        }

        await this.refreshDiscoInfo();
        nick = await this.getAndPersistNickname(nick);

        if (!nick) {
          utils_form.safeSave(this.session, {
            'connection_status': converse.ROOMSTATUS.NICKNAME_REQUIRED
          });

          if (converse_core_api.settings.get('muc_show_logs_before_join')) {
            await this.fetchMessages();
          }

          return this;
        }

        const stanza = $pres({
          'from': converse_core_converse.connection.jid,
          'to': this.getRoomJIDAndNick()
        }).c("x", {
          'xmlns': converse_muc_Strophe.NS.MUC
        }).c("history", {
          'maxstanzas': this.features.get('mam_enabled') ? 0 : converse_core_api.settings.get('muc_history_max_stanzas')
        }).up();
        password = password || this.get('password');

        if (password) {
          stanza.cnode(converse_muc_Strophe.xmlElement("password", [], password));
        }

        this.session.save('connection_status', converse.ROOMSTATUS.CONNECTING);
        converse_core_api.send(stanza);
        return this;
      },

      async clearCache() {
        this.session.save('connection_status', converse.ROOMSTATUS.DISCONNECTED);

        if (this.occupants.length) {
          // Remove non-members when reconnecting
          this.occupants.filter(o => !o.isMember()).forEach(o => o.destroy());
        } else {
          // Looks like we haven't restored occupants from cache, so we clear it.
          this.occupants.clearStore();
        }

        if (converse_core_api.settings.get('clear_messages_on_reconnection')) {
          await this.clearMessages();
        }
      },

      onOccupantAdded(occupant) {
        if (converse_core_api.settings.get('muc_show_join_leave') && this.session.get('connection_status') === converse.ROOMSTATUS.ENTERED && occupant.get('show') === 'online') {
          this.updateNotifications(occupant.get('nick'), 'entered');
        }
      },

      onOccupantRemoved(occupant) {
        if (converse_core_api.settings.get('muc_show_join_leave') && this.session.get('connection_status') === converse.ROOMSTATUS.ENTERED && occupant.get('show') === 'online') {
          this.updateNotifications(occupant.get('nick'), 'exited');
        }
      },

      onOccupantShowChanged(occupant) {
        if (occupant.get('states').includes('303') || !converse_core_api.settings.get('muc_show_join_leave')) {
          return;
        }

        if (occupant.get('show') === 'offline') {
          this.updateNotifications(occupant.get('nick'), 'exited');
        } else if (occupant.get('show') === 'online') {
          this.updateNotifications(occupant.get('nick'), 'entered');
        }
      },

      /**
       * Clear stale cache and re-join a MUC we've been in before.
       * @private
       * @method _converse.ChatRoom#rejoin
       */
      rejoin() {
        this.clearCache();
        return this.join();
      },

      async onConnectionStatusChanged() {
        if (this.session.get('connection_status') === converse.ROOMSTATUS.ENTERED) {
          await this.occupants.fetchMembers();
          await this.fetchMessages();
          /**
           * Triggered when the user has entered a new MUC
           * @event _converse#enteredNewRoom
           * @type { _converse.ChatRoom}
           * @example _converse.api.listen.on('enteredNewRoom', model => { ... });
           */

          converse_core_api.trigger('enteredNewRoom', this);

          if (converse_core_api.settings.get('auto_register_muc_nickname') && (await converse_core_api.disco.supports(converse_muc_Strophe.NS.MUC_REGISTER, this.get('jid')))) {
            this.registerNickname();
          }
        }
      },

      async onReconnection() {
        this.registerHandlers();
        await this.rejoin();
        this.announceReconnection();
      },

      restoreSession() {
        const id = `muc.session-${converse_core_converse.bare_jid}-${this.get('jid')}`;
        this.session = new MUCSession({
          id
        });
        this.session.browserStorage = converse_core_converse.createStore(id, "session");
        return new Promise(r => this.session.fetch({
          'success': r,
          'error': r
        }));
      },

      initDiscoModels() {
        let id = `converse.muc-features-${converse_core_converse.bare_jid}-${this.get('jid')}`;
        this.features = new model_Model(Object.assign({
          id
        }, lodash_es_zipObject(converse.ROOM_FEATURES, converse.ROOM_FEATURES.map(() => false))));
        this.features.browserStorage = converse_core_converse.createStore(id, "session");
        id = `converse.muc-config-{_converse.bare_jid}-${this.get('jid')}`;
        this.config = new model_Model();
        this.config.browserStorage = converse_core_converse.createStore(id, "session");
      },

      initOccupants() {
        this.occupants = new converse_core_converse.ChatRoomOccupants();
        const id = `converse.occupants-${converse_core_converse.bare_jid}${this.get('jid')}`;
        this.occupants.browserStorage = converse_core_converse.createStore(id, 'session');
        this.occupants.chatroom = this;
      },

      fetchOccupants() {
        this.occupants.fetched = new Promise(resolve => {
          this.occupants.fetch({
            'add': true,
            'silent': true,
            'success': resolve,
            'error': resolve
          });
        });
        return this.occupants.fetched;
      },

      handleAffiliationChangedMessage(stanza) {
        const item = converse_muc_sizzle(`x[xmlns="${converse_muc_Strophe.NS.MUC_USER}"] item`, stanza).pop();

        if (item) {
          const from = stanza.getAttribute("from");
          const type = stanza.getAttribute("type");
          const affiliation = item.getAttribute('affiliation');
          const jid = item.getAttribute('jid');
          const data = {
            from,
            type,
            affiliation,
            'nick': converse_muc_Strophe.getNodeFromJid(jid),
            'states': [],
            'show': type == 'unavailable' ? 'offline' : 'online',
            'role': item.getAttribute('role'),
            'jid': converse_muc_Strophe.getBareJidFromJid(jid),
            'resource': converse_muc_Strophe.getResourceFromJid(jid)
          };
          const occupant = this.occupants.findOccupant({
            'jid': data.jid
          });

          if (occupant) {
            occupant.save(data);
          } else {
            this.occupants.create(data);
          }
        }
      },

      async handleErrorMessageStanza(stanza) {
        const attrs = await utils_stanza.parseMUCMessage(stanza, this, converse_core_converse);

        if (!(await this.shouldShowErrorMessage(attrs))) {
          return;
        }

        const message = this.getMessageReferencedByError(attrs);

        if (message) {
          const new_attrs = {
            'error': attrs.error,
            'error_condition': attrs.error_condition,
            'error_text': attrs.error_text,
            'error_type': attrs.error_type,
            'editable': false
          };

          if (attrs.msgid === message.get('retraction_id')) {
            // The error message refers to a retraction
            new_attrs.retraction_id = undefined;

            if (!attrs.error) {
              if (attrs.error_condition === 'forbidden') {
                new_attrs.error = __("You're not allowed to retract your message.");
              } else if (attrs.error_condition === 'not-acceptable') {
                new_attrs.error = __("Your retraction was not delivered because you're not present in the groupchat.");
              } else {
                new_attrs.error = __('Sorry, an error occurred while trying to retract your message.');
              }
            }
          } else if (!attrs.error) {
            if (attrs.error_condition === 'forbidden') {
              new_attrs.error = __("Your message was not delivered because you weren't allowed to send it.");
            } else if (attrs.error_condition === 'not-acceptable') {
              new_attrs.error = __("Your message was not delivered because you're not present in the groupchat.");
            } else {
              new_attrs.error = __('Sorry, an error occurred while trying to send your message.');
            }
          }

          message.save(new_attrs);
        } else {
          this.createMessage(attrs);
        }
      },

      /**
       * Parses an incoming message stanza and queues it for processing.
       * @private
       * @method _converse.ChatRoom#handleMessageStanza
       * @param { XMLElement } stanza
       */
      async handleMessageStanza(stanza) {
        if (utils_stanza.isArchived(stanza)) {
          // MAM messages are handled in converse-mam.
          // We shouldn't get MAM messages here because
          // they shouldn't have a `type` attribute.
          return headless_log.warn(`Received a MAM message with type "groupchat"`);
        }

        this.createInfoMessages(stanza);
        this.fetchFeaturesIfConfigurationChanged(stanza);
        /**
         * @typedef { Object } MUCMessageData
         * An object containing the original groupchat message stanza,
         * as well as the parsed attributes.
         * @property { XMLElement } stanza
         * @property { MUCMessageAttributes } attrs
         * @property { ChatRoom } chatbox
         */

        const attrs = await utils_stanza.parseMUCMessage(stanza, this, converse_core_converse);
        const data = {
          stanza,
          attrs,
          'chatbox': this
        };
        /**
         * Triggered when a groupchat message stanza has been received and parsed.
         * @event _converse#message
         * @type { object }
         * @property { module:converse-muc~MUCMessageData } data
         */

        converse_core_api.trigger('message', data);
        return attrs && this.queueMessage(attrs);
      },

      registerHandlers() {
        // Register presence and message handlers for this groupchat
        const room_jid = this.get('jid');
        this.removeHandlers();
        this.presence_handler = converse_core_converse.connection.addHandler(stanza => this.onPresence(stanza) || true, null, 'presence', null, null, room_jid, {
          'ignoreNamespaceFragment': true,
          'matchBareFromJid': true
        });
        this.message_handler = converse_core_converse.connection.addHandler(stanza => !!this.handleMessageStanza(stanza) || true, null, 'message', 'groupchat', null, room_jid, {
          'matchBareFromJid': true
        });
        this.affiliation_message_handler = converse_core_converse.connection.addHandler(stanza => this.handleAffiliationChangedMessage(stanza) || true, converse_muc_Strophe.NS.MUC_USER, 'message', null, null, room_jid);
      },

      removeHandlers() {
        // Remove the presence and message handlers that were
        // registered for this groupchat.
        if (this.message_handler) {
          converse_core_converse.connection && converse_core_converse.connection.deleteHandler(this.message_handler);
          delete this.message_handler;
        }

        if (this.presence_handler) {
          converse_core_converse.connection && converse_core_converse.connection.deleteHandler(this.presence_handler);
          delete this.presence_handler;
        }

        if (this.affiliation_message_handler) {
          converse_core_converse.connection && converse_core_converse.connection.deleteHandler(this.affiliation_message_handler);
          delete this.affiliation_message_handler;
        }

        return this;
      },

      invitesAllowed() {
        return converse_core_api.settings.get('allow_muc_invitations') && (this.features.get('open') || this.getOwnAffiliation() === "owner");
      },

      getDisplayName() {
        const name = this.get('name');

        if (name) {
          return name;
        } else if (converse_core_api.settings.get('locked_muc_domain') === 'hidden') {
          return converse_muc_Strophe.getNodeFromJid(this.get('jid'));
        } else {
          return this.get('jid');
        }
      },

      /**
       * Sends a message stanza to the XMPP server and expects a reflection
       * or error message within a specific timeout period.
       * @private
       * @method _converse.ChatRoom#sendTimedMessage
       * @param { _converse.Message|XMLElement } message
       * @returns { Promise<XMLElement>|Promise<_converse.TimeoutError> } Returns a promise
       *  which resolves with the reflected message stanza or rejects
       *  with an error stanza or with a {@link _converse.TimeoutError}.
       */
      sendTimedMessage(el) {
        if (typeof el.tree === "function") {
          el = el.tree();
        }

        let id = el.getAttribute('id');

        if (!id) {
          // inject id if not found
          id = this.getUniqueId("sendIQ");
          el.setAttribute("id", id);
        }

        const promise = utils_form.getResolveablePromise();

        const timeoutHandler = converse_core_converse.connection.addTimedHandler(converse_core_converse.STANZA_TIMEOUT, () => {
          converse_core_converse.connection.deleteHandler(handler);

          promise.reject(new converse_core_converse.TimeoutError("Timeout Error: No response from server"));
          return false;
        });

        const handler = converse_core_converse.connection.addHandler(stanza => {
          timeoutHandler && converse_core_converse.connection.deleteTimedHandler(timeoutHandler);

          if (stanza.getAttribute('type') === 'groupchat') {
            promise.resolve(stanza);
          } else {
            promise.reject(stanza);
          }
        }, null, 'message', ['error', 'groupchat'], id);

        converse_core_api.send(el);
        return promise;
      },

      /**
       * Retract one of your messages in this groupchat
       * @private
       * @method _converse.ChatRoom#retractOwnMessage
       * @param { _converse.Message } message - The message which we're retracting.
       */
      async retractOwnMessage(message) {
        const origin_id = message.get('origin_id');

        if (!origin_id) {
          throw new Error("Can't retract message without a XEP-0359 Origin ID");
        }

        const editable = message.get('editable');
        const stanza = converse_muc_$msg({
          'id': utils_form.getUniqueId(),
          'to': this.get('jid'),
          'type': "groupchat"
        }).c('store', {
          xmlns: converse_muc_Strophe.NS.HINTS
        }).up().c("apply-to", {
          'id': origin_id,
          'xmlns': converse_muc_Strophe.NS.FASTEN
        }).c('retract', {
          xmlns: converse_muc_Strophe.NS.RETRACT
        }); // Optimistic save

        message.set({
          'retracted': new Date().toISOString(),
          'retracted_id': origin_id,
          'retraction_id': stanza.nodeTree.getAttribute('id'),
          'editable': false
        });

        try {
          await this.sendTimedMessage(stanza);
        } catch (e) {
          headless_log.error(e);
          message.save({
            editable,
            'error_type': 'timeout',
            'error': __('A timeout happened while while trying to retract your message.'),
            'retracted': undefined,
            'retracted_id': undefined
          });
        }
      },

      /**
       * Retract someone else's message in this groupchat.
       * @private
       * @method _converse.ChatRoom#retractOtherMessage
       * @param { _converse.Message } message - The message which we're retracting.
       * @param { string } [reason] - The reason for retracting the message.
       */
      async retractOtherMessage(message, reason) {
        const editable = message.get('editable'); // Optimistic save

        message.save({
          'moderated': 'retracted',
          'moderated_by': converse_core_converse.bare_jid,
          'moderated_id': message.get('msgid'),
          'moderation_reason': reason,
          'editable': false
        });
        const result = await this.sendRetractionIQ(message, reason);

        if (result === null || utils_form.isErrorStanza(result)) {
          // Undo the save if something went wrong
          message.save({
            editable,
            'moderated': undefined,
            'moderated_by': undefined,
            'moderated_id': undefined,
            'moderation_reason': undefined
          });
        }

        return result;
      },

      /**
       * Sends an IQ stanza to the XMPP server to retract a message in this groupchat.
       * @private
       * @method _converse.ChatRoom#sendRetractionIQ
       * @param { _converse.Message } message - The message which we're retracting.
       * @param { string } [reason] - The reason for retracting the message.
       */
      sendRetractionIQ(message, reason) {
        const iq = converse_muc_$iq({
          'to': this.get('jid'),
          'type': "set"
        }).c("apply-to", {
          'id': message.get(`stanza_id ${this.get('jid')}`),
          'xmlns': converse_muc_Strophe.NS.FASTEN
        }).c('moderate', {
          xmlns: converse_muc_Strophe.NS.MODERATE
        }).c('retract', {
          xmlns: converse_muc_Strophe.NS.RETRACT
        }).up().c('reason').t(reason || '');
        return converse_core_api.sendIQ(iq, null, false);
      },

      /**
       * Sends an IQ stanza to the XMPP server to destroy this groupchat. Not
       * to be confused with the {@link _converse.ChatRoom#destroy}
       * method, which simply removes the room from the local browser storage cache.
       * @private
       * @method _converse.ChatRoom#sendDestroyIQ
       * @param { string } [reason] - The reason for destroying the groupchat.
       * @param { string } [new_jid] - The JID of the new groupchat which replaces this one.
       */
      sendDestroyIQ(reason, new_jid) {
        const destroy = $build("destroy");

        if (new_jid) {
          destroy.attrs({
            'jid': new_jid
          });
        }

        const iq = converse_muc_$iq({
          'to': this.get('jid'),
          'type': "set"
        }).c("query", {
          'xmlns': converse_muc_Strophe.NS.MUC_OWNER
        }).cnode(destroy.node);

        if (reason && reason.length > 0) {
          iq.c("reason", reason);
        }

        return converse_core_api.sendIQ(iq);
      },

      /**
       * Leave the groupchat.
       * @private
       * @method _converse.ChatRoom#leave
       * @param { string } [exit_msg] - Message to indicate your reason for leaving
       */
      async leave(exit_msg) {
        this.features.destroy();
        this.occupants.clearStore();

        if (converse_core_converse.disco_entities) {
          const disco_entity = converse_core_converse.disco_entities.get(this.get('jid'));

          if (disco_entity) {
            await new Promise((success, error) => disco_entity.destroy({
              success,
              error
            }));
          }
        }

        if (converse_core_api.connection.connected()) {
          converse_core_api.user.presence.send('unavailable', this.getRoomJIDAndNick(), exit_msg);
        }

        utils_form.safeSave(this.session, {
          'connection_status': converse.ROOMSTATUS.DISCONNECTED
        });
        this.removeHandlers();
      },

      async close() {
        // Delete the session model
        await new Promise(resolve => this.session.destroy({
          'success': resolve,
          'error': (m, e) => {
            headless_log.error(e);
            resolve();
          }
        })); // Delete the features model

        await new Promise(resolve => this.features.destroy({
          'success': resolve,
          'error': (m, e) => {
            headless_log.error(e);
            resolve();
          }
        }));
        return converse_core_converse.ChatBox.prototype.close.call(this);
      },

      canModerateMessages() {
        const self = this.getOwnOccupant();
        return self && self.isModerator() && converse_core_api.disco.supports(converse_muc_Strophe.NS.MODERATE, this.get('jid'));
      },

      /**
       * Return an array of unique nicknames based on all occupants and messages in this MUC.
       * @private
       * @method _converse.ChatRoom#getAllKnownNicknames
       * @returns { String[] }
       */
      getAllKnownNicknames() {
        return [...new Set([...this.occupants.map(o => o.get('nick')), ...this.messages.map(m => m.get('nick'))])].filter(n => n);
      },

      getAllKnownNicknamesRegex() {
        const longNickString = this.getAllKnownNicknames().join('|');
        const escapedLongNickString = parse_helpers.escapeRegexString(longNickString);
        return RegExp(`(?:\\s|^)@(${escapedLongNickString})(?![\\w@-])`, 'ig');
      },

      getOccupantByJID(jid) {
        return this.occupants.findOccupant({
          jid
        });
      },

      getOccupantByNickname(nick) {
        return this.occupants.findOccupant({
          nick
        });
      },

      parseTextForReferences(original_message) {
        if (!original_message) return ['', []];
        const findRegexInMessage = parse_helpers.matchRegexInText(original_message);
        const raw_mentions = findRegexInMessage(parse_helpers.mention_regex);
        if (!raw_mentions) return [original_message, []];
        const known_nicknames = this.getAllKnownNicknames();
        const getMatchingNickname = parse_helpers.findFirstMatchInArray(known_nicknames);

        const uriFromNickname = nickname => {
          const jid = this.get('jid');
          const occupant = this.getOccupant(nickname) || this.getOccupant(jid);
          const uri = occupant && occupant.get('jid') || `${jid}/${nickname}`;
          return encodeURI(`xmpp:${uri}`);
        };

        const matchToReference = match => {
          const at_sign_index = match[0].indexOf('@');
          const begin = match.index + at_sign_index;
          const end = begin + match[0].length - at_sign_index;
          const value = getMatchingNickname(match[1]);
          const type = 'mention';
          const uri = uriFromNickname(value);
          return {
            begin,
            end,
            value,
            type,
            uri
          };
        };

        const mentions = [...findRegexInMessage(this.getAllKnownNicknamesRegex())];
        const references = mentions.map(matchToReference);
        const [updated_message, updated_references] = parse_helpers.reduceTextFromReferences(original_message, references);
        return [updated_message, updated_references];
      },

      getOutgoingMessageAttributes(original_message, spoiler_hint) {
        const is_spoiler = this.get('composing_spoiler');
        const [text, references] = this.parseTextForReferences(original_message);
        const origin_id = utils_form.getUniqueId();
        const body = text ? utils_form.httpToGeoUri(utils_form.shortnamesToUnicode(text), converse_core_converse) : undefined;
        return {
          body,
          is_spoiler,
          origin_id,
          references,
          'id': origin_id,
          'msgid': origin_id,
          'from': `${this.get('jid')}/${this.get('nick')}`,
          'fullname': this.get('nick'),
          'is_only_emojis': text ? utils_form.isOnlyEmojis(text) : false,
          'message': body,
          'nick': this.get('nick'),
          'sender': 'me',
          'spoiler_hint': is_spoiler ? spoiler_hint : undefined,
          'type': 'groupchat'
        };
      },

      /**
       * Utility method to construct the JID for the current user as occupant of the groupchat.
       * @private
       * @method _converse.ChatRoom#getRoomJIDAndNick
       * @returns {string} - The groupchat JID with the user's nickname added at the end.
       * @example groupchat@conference.example.org/nickname
       */
      getRoomJIDAndNick() {
        const nick = this.get('nick');
        const jid = converse_muc_Strophe.getBareJidFromJid(this.get('jid'));
        return jid + (nick !== null ? `/${nick}` : "");
      },

      /**
       * Sends a message with the current XEP-0085 chat state of the user
       * as taken from the `chat_state` attribute of the {@link _converse.ChatRoom}.
       * @private
       * @method _converse.ChatRoom#sendChatState
       */
      sendChatState() {
        if (!converse_core_api.settings.get('send_chat_state_notifications') || !this.get('chat_state') || this.session.get('connection_status') !== converse.ROOMSTATUS.ENTERED || this.features.get('moderated') && this.getOwnRole() === 'visitor') {
          return;
        }

        const allowed = converse_core_api.settings.get('send_chat_state_notifications');

        if (Array.isArray(allowed) && !allowed.includes(this.get('chat_state'))) {
          return;
        }

        const chat_state = this.get('chat_state');

        if (chat_state === converse_core_converse.GONE) {
          // <gone/> is not applicable within MUC context
          return;
        }

        converse_core_api.send(converse_muc_$msg({
          'to': this.get('jid'),
          'type': 'groupchat'
        }).c(chat_state, {
          'xmlns': converse_muc_Strophe.NS.CHATSTATES
        }).up().c('no-store', {
          'xmlns': converse_muc_Strophe.NS.HINTS
        }).up().c('no-permanent-store', {
          'xmlns': converse_muc_Strophe.NS.HINTS
        }));
      },

      /**
       * Send a direct invitation as per XEP-0249
       * @private
       * @method _converse.ChatRoom#directInvite
       * @param { String } recipient - JID of the person being invited
       * @param { String } [reason] - Reason for the invitation
       */
      directInvite(recipient, reason) {
        if (this.features.get('membersonly')) {
          // When inviting to a members-only groupchat, we first add
          // the person to the member list by giving them an
          // affiliation of 'member' otherwise they won't be able to join.
          this.updateMemberLists([{
            'jid': recipient,
            'affiliation': 'member',
            'reason': reason
          }]);
        }

        const attrs = {
          'xmlns': 'jabber:x:conference',
          'jid': this.get('jid')
        };

        if (reason !== null) {
          attrs.reason = reason;
        }

        if (this.get('password')) {
          attrs.password = this.get('password');
        }

        const invitation = converse_muc_$msg({
          'from': converse_core_converse.connection.jid,
          'to': recipient,
          'id': utils_form.getUniqueId()
        }).c('x', attrs);
        converse_core_api.send(invitation);
        /**
         * After the user has sent out a direct invitation (as per XEP-0249),
         * to a roster contact, asking them to join a room.
         * @event _converse#chatBoxMaximized
         * @type {object}
         * @property {_converse.ChatRoom} room
         * @property {string} recipient - The JID of the person being invited
         * @property {string} reason - The original reason for the invitation
         * @example _converse.api.listen.on('chatBoxMaximized', view => { ... });
         */

        converse_core_api.trigger('roomInviteSent', {
          'room': this,
          'recipient': recipient,
          'reason': reason
        });
      },

      /**
       * Refresh the disco identity, features and fields for this {@link _converse.ChatRoom}.
       * *features* are stored on the features {@link Model} attribute on this {@link _converse.ChatRoom}.
       * *fields* are stored on the config {@link Model} attribute on this {@link _converse.ChatRoom}.
       * @private
       * @returns {Promise}
       */
      refreshDiscoInfo() {
        return converse_core_api.disco.refresh(this.get('jid')).then(() => this.getDiscoInfo()).catch(e => headless_log.error(e));
      },

      /**
       * Fetch the *extended* MUC info from the server and cache it locally
       * https://xmpp.org/extensions/xep-0045.html#disco-roominfo
       * @private
       * @method _converse.ChatRoom#getDiscoInfo
       * @returns {Promise}
       */
      getDiscoInfo() {
        return converse_core_api.disco.getIdentity('conference', 'text', this.get('jid')).then(identity => this.save({
          'name': identity === null || identity === void 0 ? void 0 : identity.get('name')
        })).then(() => this.getDiscoInfoFields()).then(() => this.getDiscoInfoFeatures()).catch(e => headless_log.error(e));
      },

      /**
       * Fetch the *extended* MUC info fields from the server and store them locally
       * in the `config` {@link Model} attribute.
       * See: https://xmpp.org/extensions/xep-0045.html#disco-roominfo
       * @private
       * @method _converse.ChatRoom#getDiscoInfoFields
       * @returns {Promise}
       */
      async getDiscoInfoFields() {
        const fields = await converse_core_api.disco.getFields(this.get('jid'));
        const config = fields.reduce((config, f) => {
          const name = f.get('var');

          if (name && name.startsWith('muc#roominfo_')) {
            config[name.replace('muc#roominfo_', '')] = f.get('value');
          }

          return config;
        }, {});
        this.config.save(config);
      },

      /**
       * Use converse-disco to populate the features {@link Model} which
       * is stored as an attibute on this {@link _converse.ChatRoom}.
       * The results may be cached. If you want to force fetching the features from the
       * server, call {@link _converse.ChatRoom#refreshDiscoInfo} instead.
       * @private
       * @returns {Promise}
       */
      async getDiscoInfoFeatures() {
        const features = await converse_core_api.disco.getFeatures(this.get('jid'));
        const attrs = Object.assign(lodash_es_zipObject(converse.ROOM_FEATURES, converse.ROOM_FEATURES.map(() => false)), {
          'fetched': new Date().toISOString()
        });
        features.each(feature => {
          const fieldname = feature.get('var');

          if (!fieldname.startsWith('muc_')) {
            if (fieldname === converse_muc_Strophe.NS.MAM) {
              attrs.mam_enabled = true;
            }

            return;
          }

          attrs[fieldname.replace('muc_', '')] = true;
        });
        this.features.save(attrs);
      },

      /**
       * Send IQ stanzas to the server to set an affiliation for
       * the provided JIDs.
       * See: https://xmpp.org/extensions/xep-0045.html#modifymember
       *
       * Prosody doesn't accept multiple JIDs' affiliations
       * being set in one IQ stanza, so as a workaround we send
       * a separate stanza for each JID.
       * Related ticket: https://issues.prosody.im/345
       *
       * @private
       * @method _converse.ChatRoom#setAffiliation
       * @param { string } affiliation - The affiliation
       * @param { object } members - A map of jids, affiliations and
       *      optionally reasons. Only those entries with the
       *      same affiliation as being currently set will be considered.
       * @returns { Promise } A promise which resolves and fails depending on the XMPP server response.
       */
      setAffiliation(affiliation, members) {
        members = members.filter(m => m.affiliation === undefined || m.affiliation === affiliation);
        return Promise.all(members.map(m => this.sendAffiliationIQ(affiliation, m)));
      },

      /**
       * Given a <field> element, return a copy with a <value> child if
       * we can find a value for it in this rooms config.
       * @private
       * @method _converse.ChatRoom#addFieldValue
       * @returns { Element }
       */
      addFieldValue(field) {
        const type = field.getAttribute('type');

        if (type === 'fixed') {
          return field;
        }

        const fieldname = field.getAttribute('var').replace('muc#roomconfig_', '');
        const config = this.get('roomconfig');

        if (fieldname in config) {
          let values;

          switch (type) {
            case 'boolean':
              values = [config[fieldname] ? 1 : 0];
              break;

            case 'list-multi':
              values = config[fieldname];
              break;

            default:
              values = [config[fieldname]];
          }

          field.innerHTML = values.map(v => $build('value').t(v)).join('');
        }

        return field;
      },

      /**
       * Automatically configure the groupchat based on this model's
       * 'roomconfig' data.
       * @private
       * @method _converse.ChatRoom#autoConfigureChatRoom
       * @returns { Promise<XMLElement> }
       * Returns a promise which resolves once a response IQ has
       * been received.
       */
      async autoConfigureChatRoom() {
        const stanza = await this.fetchRoomConfiguration();
        const fields = converse_muc_sizzle('field', stanza);
        const configArray = fields.map(f => this.addFieldValue(f));

        if (configArray.length) {
          return this.sendConfiguration(configArray);
        }
      },

      /**
       * Send an IQ stanza to fetch the groupchat configuration data.
       * Returns a promise which resolves once the response IQ
       * has been received.
       * @private
       * @method _converse.ChatRoom#fetchRoomConfiguration
       * @returns { Promise<XMLElement> }
       */
      fetchRoomConfiguration() {
        return converse_core_api.sendIQ(converse_muc_$iq({
          'to': this.get('jid'),
          'type': "get"
        }).c("query", {
          xmlns: converse_muc_Strophe.NS.MUC_OWNER
        }));
      },

      /**
       * Sends an IQ stanza with the groupchat configuration.
       * @private
       * @method _converse.ChatRoom#sendConfiguration
       * @param { Array } config - The groupchat configuration
       * @returns { Promise<XMLElement> } - A promise which resolves with
       * the `result` stanza received from the XMPP server.
       */
      sendConfiguration(config = []) {
        const iq = converse_muc_$iq({
          to: this.get('jid'),
          type: "set"
        }).c("query", {
          xmlns: converse_muc_Strophe.NS.MUC_OWNER
        }).c("x", {
          xmlns: converse_muc_Strophe.NS.XFORM,
          type: "submit"
        });
        config.forEach(node => iq.cnode(node).up());
        return converse_core_api.sendIQ(iq);
      },

      /**
       * Returns the `role` which the current user has in this MUC
       * @private
       * @method _converse.ChatRoom#getOwnRole
       * @returns { ('none'|'visitor'|'participant'|'moderator') }
       */
      getOwnRole() {
        var _this$getOwnOccupant, _this$getOwnOccupant$;

        return (_this$getOwnOccupant = this.getOwnOccupant()) === null || _this$getOwnOccupant === void 0 ? void 0 : (_this$getOwnOccupant$ = _this$getOwnOccupant.attributes) === null || _this$getOwnOccupant$ === void 0 ? void 0 : _this$getOwnOccupant$.role;
      },

      /**
       * Returns the `affiliation` which the current user has in this MUC
       * @private
       * @method _converse.ChatRoom#getOwnAffiliation
       * @returns { ('none'|'outcast'|'member'|'admin'|'owner') }
       */
      getOwnAffiliation() {
        var _this$getOwnOccupant2, _this$getOwnOccupant3;

        return (_this$getOwnOccupant2 = this.getOwnOccupant()) === null || _this$getOwnOccupant2 === void 0 ? void 0 : (_this$getOwnOccupant3 = _this$getOwnOccupant2.attributes) === null || _this$getOwnOccupant3 === void 0 ? void 0 : _this$getOwnOccupant3.affiliation;
      },

      /**
       * Get the {@link _converse.ChatRoomOccupant} instance which
       * represents the current user.
       * @private
       * @method _converse.ChatRoom#getOwnOccupant
       * @returns { _converse.ChatRoomOccupant }
       */
      getOwnOccupant() {
        return this.occupants.findWhere({
          'jid': converse_core_converse.bare_jid
        });
      },

      /**
       * Send an IQ stanza specifying an affiliation change.
       * @private
       * @method _converse.ChatRoom#
       * @param { String } affiliation: affiliation
       *     (could also be stored on the member object).
       * @param { Object } member: Map containing the member's jid and
       *     optionally a reason and affiliation.
       */
      sendAffiliationIQ(affiliation, member) {
        const iq = converse_muc_$iq({
          to: this.get('jid'),
          type: "set"
        }).c("query", {
          xmlns: converse_muc_Strophe.NS.MUC_ADMIN
        }).c("item", {
          'affiliation': member.affiliation || affiliation,
          'nick': member.nick,
          'jid': member.jid
        });

        if (member.reason !== undefined) {
          iq.c("reason", member.reason);
        }

        return converse_core_api.sendIQ(iq);
      },

      /**
       * Send IQ stanzas to the server to modify affiliations for users in this groupchat.
       *
       * See: https://xmpp.org/extensions/xep-0045.html#modifymember
       * @private
       * @method _converse.ChatRoom#setAffiliations
       * @param { Object[] } members
       * @param { string } members[].jid - The JID of the user whose affiliation will change
       * @param { Array } members[].affiliation - The new affiliation for this user
       * @param { string } [members[].reason] - An optional reason for the affiliation change
       * @returns { Promise }
       */
      setAffiliations(members) {
        const affiliations = [...new Set(members.map(m => m.affiliation))];
        return Promise.all(affiliations.map(a => this.setAffiliation(a, members)));
      },

      /**
       * Send an IQ stanza to modify an occupant's role
       * @private
       * @method _converse.ChatRoom#setRole
       * @param { _converse.ChatRoomOccupant } occupant
       * @param { String } role
       * @param { String } reason
       * @param { function } onSuccess - callback for a succesful response
       * @param { function } onError - callback for an error response
       */
      setRole(occupant, role, reason, onSuccess, onError) {
        const item = $build("item", {
          'nick': occupant.get('nick'),
          role
        });
        const iq = converse_muc_$iq({
          'to': this.get('jid'),
          'type': 'set'
        }).c("query", {
          xmlns: converse_muc_Strophe.NS.MUC_ADMIN
        }).cnode(item.node);

        if (reason !== null) {
          iq.c("reason", reason);
        }

        return converse_core_api.sendIQ(iq).then(onSuccess).catch(onError);
      },

      /**
       * @private
       * @method _converse.ChatRoom#getOccupant
       * @param { String } nickname_or_jid - The nickname or JID of the occupant to be returned
       * @returns { _converse.ChatRoomOccupant }
       */
      getOccupant(nickname_or_jid) {
        return utils_form.isValidJID(nickname_or_jid) ? this.getOccupantByJID(nickname_or_jid) : this.getOccupantByNickname(nickname_or_jid);
      },

      /**
       * Return an array of occupant models that have the required role
       * @private
       * @method _converse.ChatRoom#getOccupantsWithRole
       * @param { String } role
       * @returns { _converse.ChatRoomOccupant[] }
       */
      getOccupantsWithRole(role) {
        return this.getOccupantsSortedBy('nick').filter(o => o.get('role') === role).map(item => {
          return {
            'jid': item.get('jid'),
            'nick': item.get('nick'),
            'role': item.get('role')
          };
        });
      },

      /**
       * Return an array of occupant models that have the required affiliation
       * @private
       * @method _converse.ChatRoom#getOccupantsWithAffiliation
       * @param { String } affiliation
       * @returns { _converse.ChatRoomOccupant[] }
       */
      getOccupantsWithAffiliation(affiliation) {
        return this.getOccupantsSortedBy('nick').filter(o => o.get('affiliation') === affiliation).map(item => {
          return {
            'jid': item.get('jid'),
            'nick': item.get('nick'),
            'affiliation': item.get('affiliation')
          };
        });
      },

      /**
       * Return an array of occupant models, sorted according to the passed-in attribute.
       * @private
       * @method _converse.ChatRoom#getOccupantsSortedBy
       * @param { String } attr - The attribute to sort the returned array by
       * @returns { _converse.ChatRoomOccupant[] }
       */
      getOccupantsSortedBy(attr) {
        return Array.from(this.occupants.models).sort((a, b) => a.get(attr) < b.get(attr) ? -1 : a.get(attr) > b.get(attr) ? 1 : 0);
      },

      /**
       * Sends an IQ stanza to the server, asking it for the relevant affiliation list .
       * Returns an array of {@link MemberListItem} objects, representing occupants
       * that have the given affiliation.
       * See: https://xmpp.org/extensions/xep-0045.html#modifymember
       * @private
       * @method _converse.ChatRoom#getAffiliationList
       * @param { ("admin"|"owner"|"member") } affiliation
       * @returns { Promise<MemberListItem[]> }
       */
      async getAffiliationList(affiliation) {
        const iq = converse_muc_$iq({
          to: this.get('jid'),
          type: "get"
        }).c("query", {
          xmlns: converse_muc_Strophe.NS.MUC_ADMIN
        }).c("item", {
          'affiliation': affiliation
        });
        const result = await converse_core_api.sendIQ(iq, null, false);

        if (result === null) {
          const err_msg = `Error: timeout while fetching ${affiliation} list for MUC ${this.get('jid')}`;
          const err = new Error(err_msg);
          headless_log.warn(err_msg);
          headless_log.warn(result);
          return err;
        }

        if (utils_form.isErrorStanza(result)) {
          const err_msg = `Error: not allowed to fetch ${affiliation} list for MUC ${this.get('jid')}`;
          const err = new Error(err_msg);
          headless_log.warn(err_msg);
          headless_log.warn(result);
          return err;
        }

        return utils_muc.parseMemberListIQ(result).filter(p => p).sort((a, b) => a.nick < b.nick ? -1 : a.nick > b.nick ? 1 : 0);
      },

      /**
       * Fetch the lists of users with the given affiliations.
       * Then compute the delta between those users and
       * the passed in members, and if it exists, send the delta
       * to the XMPP server to update the member list.
       * @private
       * @method _converse.ChatRoom#updateMemberLists
       * @param { object } members - Map of member jids and affiliations.
       * @returns { Promise }
       *  A promise which is resolved once the list has been
       *  updated or once it's been established there's no need
       *  to update the list.
       */
      async updateMemberLists(members) {
        const all_affiliations = ['member', 'admin', 'owner'];
        const aff_lists = await Promise.all(all_affiliations.map(a => this.getAffiliationList(a)));
        const old_members = aff_lists.reduce((acc, val) => utils_form.isErrorObject(val) ? acc : [...val, ...acc], []);
        await this.setAffiliations(utils_muc.computeAffiliationsDelta(true, false, members, old_members));
        await this.occupants.fetchMembers();
      },

      /**
       * Given a nick name, save it to the model state, otherwise, look
       * for a server-side reserved nickname or default configured
       * nickname and if found, persist that to the model state.
       * @private
       * @method _converse.ChatRoom#getAndPersistNickname
       * @returns { Promise<string> } A promise which resolves with the nickname
       */
      async getAndPersistNickname(nick) {
        nick = nick || this.get('nick') || (await this.getReservedNick()) || converse_core_converse.getDefaultMUCNickname();

        if (nick) {
          this.save({
            nick
          }, {
            'silent': true
          });
        }

        return nick;
      },

      /**
       * Use service-discovery to ask the XMPP server whether
       * this user has a reserved nickname for this groupchat.
       * If so, we'll use that, otherwise we render the nickname form.
       * @private
       * @method _converse.ChatRoom#getReservedNick
       * @returns { Promise<string> } A promise which resolves with the reserved nick or null
       */
      async getReservedNick() {
        const stanza = converse_muc_$iq({
          'to': this.get('jid'),
          'from': converse_core_converse.connection.jid,
          'type': "get"
        }).c("query", {
          'xmlns': converse_muc_Strophe.NS.DISCO_INFO,
          'node': 'x-roomuser-item'
        });
        const result = await converse_core_api.sendIQ(stanza, null, false);

        if (utils_form.isErrorObject(result)) {
          throw result;
        }

        const identity_el = result.querySelector('query[node="x-roomuser-item"] identity');
        return identity_el ? identity_el.getAttribute('name') : null;
      },

      async registerNickname() {
        // See https://xmpp.org/extensions/xep-0045.html#register
        const nick = this.get('nick');
        const jid = this.get('jid');
        let iq, err_msg;

        try {
          iq = await converse_core_api.sendIQ(converse_muc_$iq({
            'to': jid,
            'from': converse_core_converse.connection.jid,
            'type': 'get'
          }).c('query', {
            'xmlns': converse_muc_Strophe.NS.MUC_REGISTER
          }));
        } catch (e) {
          if (converse_muc_sizzle(`not-allowed[xmlns="${converse_muc_Strophe.NS.STANZAS}"]`, e).length) {
            err_msg = __("You're not allowed to register yourself in this groupchat.");
          } else if (converse_muc_sizzle(`registration-required[xmlns="${converse_muc_Strophe.NS.STANZAS}"]`, e).length) {
            err_msg = __("You're not allowed to register in this groupchat because it's members-only.");
          }

          headless_log.error(e);
          return err_msg;
        }

        const required_fields = converse_muc_sizzle('field required', iq).map(f => f.parentElement);

        if (required_fields.length > 1 && required_fields[0].getAttribute('var') !== 'muc#register_roomnick') {
          return headless_log.error(`Can't register the user register in the groupchat ${jid} due to the required fields`);
        }

        try {
          await converse_core_api.sendIQ(converse_muc_$iq({
            'to': jid,
            'from': converse_core_converse.connection.jid,
            'type': 'set'
          }).c('query', {
            'xmlns': converse_muc_Strophe.NS.MUC_REGISTER
          }).c('x', {
            'xmlns': converse_muc_Strophe.NS.XFORM,
            'type': 'submit'
          }).c('field', {
            'var': 'FORM_TYPE'
          }).c('value').t('http://jabber.org/protocol/muc#register').up().up().c('field', {
            'var': 'muc#register_roomnick'
          }).c('value').t(nick));
        } catch (e) {
          if (converse_muc_sizzle(`service-unavailable[xmlns="${converse_muc_Strophe.NS.STANZAS}"]`, e).length) {
            err_msg = __("Can't register your nickname in this groupchat, it doesn't support registration.");
          } else if (converse_muc_sizzle(`bad-request[xmlns="${converse_muc_Strophe.NS.STANZAS}"]`, e).length) {
            err_msg = __("Can't register your nickname in this groupchat, invalid data form supplied.");
          }

          headless_log.error(err_msg);
          headless_log.error(e);
          return err_msg;
        }
      },

      /**
       * Given a presence stanza, update the occupant model based on its contents.
       * @private
       * @method _converse.ChatRoom#updateOccupantsOnPresence
       * @param { XMLElement } pres - The presence stanza
       */
      updateOccupantsOnPresence(pres) {
        var _occupant$attributes, _occupant$attributes2;

        const data = utils_stanza.parseMUCPresence(pres);

        if (data.type === 'error' || !data.jid && !data.nick) {
          return true;
        }

        const occupant = this.occupants.findOccupant(data); // Destroy an unavailable occupant if this isn't a nick change operation and if they're not affiliated

        if (data.type === 'unavailable' && occupant && !data.states.includes(converse.MUC_NICK_CHANGED_CODE) && !['admin', 'owner', 'member'].includes(data['affiliation'])) {
          // Before destroying we set the new data, so that we can show the disconnection message
          occupant.set(data);
          occupant.destroy();
          return;
        }

        const jid = data.jid || '';
        const attributes = Object.assign(data, {
          'jid': converse_muc_Strophe.getBareJidFromJid(jid) || (occupant === null || occupant === void 0 ? void 0 : (_occupant$attributes = occupant.attributes) === null || _occupant$attributes === void 0 ? void 0 : _occupant$attributes.jid),
          'resource': converse_muc_Strophe.getResourceFromJid(jid) || (occupant === null || occupant === void 0 ? void 0 : (_occupant$attributes2 = occupant.attributes) === null || _occupant$attributes2 === void 0 ? void 0 : _occupant$attributes2.resource)
        });

        if (occupant) {
          occupant.save(attributes);
        } else {
          this.occupants.create(attributes);
        }
      },

      fetchFeaturesIfConfigurationChanged(stanza) {
        // 104: configuration change
        // 170: logging enabled
        // 171: logging disabled
        // 172: room no longer anonymous
        // 173: room now semi-anonymous
        // 174: room now fully anonymous
        const codes = ['104', '170', '171', '172', '173', '174'];

        if (converse_muc_sizzle('status', stanza).filter(e => codes.includes(e.getAttribute('status'))).length) {
          this.refreshDiscoInfo();
        }
      },

      /**
       * Given two JIDs, which can be either user JIDs or MUC occupant JIDs,
       * determine whether they belong to the same user.
       * @private
       * @method _converse.ChatRoom#isSameUser
       * @param { String } jid1
       * @param { String } jid2
       * @returns { Boolean }
       */
      isSameUser(jid1, jid2) {
        const bare_jid1 = converse_muc_Strophe.getBareJidFromJid(jid1);
        const bare_jid2 = converse_muc_Strophe.getBareJidFromJid(jid2);
        const resource1 = converse_muc_Strophe.getResourceFromJid(jid1);
        const resource2 = converse_muc_Strophe.getResourceFromJid(jid2);

        if (utils_form.isSameBareJID(jid1, jid2)) {
          if (bare_jid1 === this.get('jid')) {
            // MUC JIDs
            return resource1 === resource2;
          } else {
            return true;
          }
        } else {
          const occupant1 = bare_jid1 === this.get('jid') ? this.occupants.findOccupant({
            'nick': resource1
          }) : this.occupants.findOccupant({
            'jid': bare_jid1
          });
          const occupant2 = bare_jid2 === this.get('jid') ? this.occupants.findOccupant({
            'nick': resource2
          }) : this.occupants.findOccupant({
            'jid': bare_jid2
          });
          return occupant1 === occupant2;
        }
      },

      async isSubjectHidden() {
        const jids = await converse_core_api.user.settings.get('mucs_with_hidden_subject', []);
        return jids.includes(this.get('jid'));
      },

      async toggleSubjectHiddenState() {
        const muc_jid = this.get('jid');
        const jids = await converse_core_api.user.settings.get('mucs_with_hidden_subject', []);

        if (jids.includes(this.get('jid'))) {
          converse_core_api.user.settings.set('mucs_with_hidden_subject', jids.filter(jid => jid !== muc_jid));
        } else {
          converse_core_api.user.settings.set('mucs_with_hidden_subject', [...jids, muc_jid]);
        }
      },

      /**
       * Handle a possible subject change and return `true` if so.
       * @private
       * @method _converse.ChatRoom#handleSubjectChange
       * @param { object } attrs - Attributes representing a received
       *  message, as returned by {@link st.parseMUCMessage}
       */
      async handleSubjectChange(attrs) {
        if (typeof attrs.subject === 'string' && !attrs.thread && !attrs.message) {
          // https://xmpp.org/extensions/xep-0045.html#subject-mod
          // -----------------------------------------------------
          // The subject is changed by sending a message of type "groupchat" to the <room@service>,
          // where the <message/> MUST contain a <subject/> element that specifies the new subject but
          // MUST NOT contain a <body/> element (or a <thread/> element).
          const subject = attrs.subject;
          const author = attrs.nick;
          utils_form.safeSave(this, {
            'subject': {
              author,
              'text': attrs.subject || ''
            }
          });

          if (!attrs.is_delayed && author) {
            const message = subject ? __('Topic set by %1$s', author) : __('Topic cleared by %1$s', author);
            const prev_msg = this.messages.last();

            if ((prev_msg === null || prev_msg === void 0 ? void 0 : prev_msg.get('nick')) !== attrs.nick || (prev_msg === null || prev_msg === void 0 ? void 0 : prev_msg.get('type')) !== 'info' || (prev_msg === null || prev_msg === void 0 ? void 0 : prev_msg.get('message')) !== message) {
              this.createMessage({
                message,
                'nick': attrs.nick,
                'type': 'info'
              });
            }

            if (await this.isSubjectHidden()) {
              this.toggleSubjectHiddenState();
            }
          }

          return true;
        }

        return false;
      },

      /**
       * Set the subject for this {@link _converse.ChatRoom}
       * @private
       * @method _converse.ChatRoom#setSubject
       * @param { String } value
       */
      setSubject(value = '') {
        converse_core_api.send(converse_muc_$msg({
          to: this.get('jid'),
          from: converse_core_converse.connection.jid,
          type: "groupchat"
        }).c("subject", {
          xmlns: "jabber:client"
        }).t(value).tree());
      },

      /**
       * Is this a chat state notification that can be ignored,
       * because it's old or because it's from us.
       * @private
       * @method _converse.ChatRoom#ignorableCSN
       * @param { Object } attrs - The message attributes
       */
      ignorableCSN(attrs) {
        return attrs.chat_state && !attrs.body && (attrs.is_delayed || this.isOwnMessage(attrs));
      },

      /**
       * Determines whether the message is from ourselves by checking
       * the `from` attribute. Doesn't check the `type` attribute.
       * @private
       * @method _converse.ChatRoom#isOwnMessage
       * @param { Object|XMLElement|_converse.Message } msg
       * @returns { boolean }
       */
      isOwnMessage(msg) {
        let from;

        if (lodash_es_isElement(msg)) {
          from = msg.getAttribute('from');
        } else if (msg instanceof converse_core_converse.Message) {
          from = msg.get('from');
        } else {
          from = msg.from;
        }

        return converse_muc_Strophe.getResourceFromJid(from) == this.get('nick');
      },

      getUpdatedMessageAttributes(message, attrs) {
        const new_attrs = converse_core_converse.ChatBox.prototype.getUpdatedMessageAttributes.call(this, message, attrs);

        if (this.isOwnMessage(attrs)) {
          const stanza_id_keys = Object.keys(attrs).filter(k => k.startsWith('stanza_id'));
          Object.assign(new_attrs, lodash_es_pick(attrs, stanza_id_keys));

          if (!message.get('received')) {
            new_attrs.received = new Date().toISOString();
          }
        }

        return new_attrs;
      },

      /**
       * Send a MUC-0410 MUC Self-Ping stanza to room to determine
       * whether we're still joined.
       * @async
       * @private
       * @method _converse.ChatRoom#isJoined
       * @returns {Promise<boolean>}
       */
      async isJoined() {
        const jid = this.get('jid');
        const ping = converse_muc_$iq({
          'to': `${jid}/${this.get('nick')}`,
          'type': "get"
        }).c("ping", {
          'xmlns': converse_muc_Strophe.NS.PING
        });

        try {
          await converse_core_api.sendIQ(ping);
        } catch (e) {
          if (e === null) {
            headless_log.warn(`isJoined: Timeout error while checking whether we're joined to MUC: ${jid}`);
          } else {
            headless_log.warn(`isJoined: Apparently we're no longer connected to MUC: ${jid}`);
          }

          return false;
        }

        return true;
      },

      /**
       * Check whether we're still joined and re-join if not
       * @async
       * @private
       * @method _converse.ChatRoom#rejoinIfNecessary
       */
      async rejoinIfNecessary() {
        if (!(await this.isJoined())) {
          this.rejoin();
          return true;
        }
      },

      /**
       * @private
       * @method _converse.ChatRoom#shouldShowErrorMessage
       * @returns {Promise<boolean>}
       */
      async shouldShowErrorMessage(attrs) {
        if (attrs['error_condition'] === 'not-acceptable' && (await this.rejoinIfNecessary())) {
          return false;
        }

        return converse_core_converse.ChatBox.prototype.shouldShowErrorMessage.call(this, attrs);
      },

      /**
       * Looks whether we already have a moderation message for this
       * incoming message. If so, it's considered "dangling" because
       * it probably hasn't been applied to anything yet, given that
       * the relevant message is only coming in now.
       * @private
       * @method _converse.ChatRoom#findDanglingModeration
       * @param { object } attrs - Attributes representing a received
       *  message, as returned by {@link st.parseMUCMessage}
       * @returns { _converse.ChatRoomMessage }
       */
      findDanglingModeration(attrs) {
        if (!this.messages.length) {
          return null;
        } // Only look for dangling moderation if there are newer
        // messages than this one, since moderation come after.


        if (this.messages.last().get('time') > attrs.time) {
          // Search from latest backwards
          const messages = Array.from(this.messages.models);
          const stanza_id = attrs[`stanza_id ${this.get('jid')}`];

          if (!stanza_id) {
            return null;
          }

          messages.reverse();
          return messages.find(({
            attributes
          }) => attributes.moderated === 'retracted' && attributes.moderated_id === stanza_id && attributes.moderated_by);
        }
      },

      /**
       * Handles message moderation based on the passed in attributes.
       * @private
       * @method _converse.ChatRoom#handleModeration
       * @param { object } attrs - Attributes representing a received
       *  message, as returned by {@link st.parseMUCMessage}
       * @returns { Boolean } Returns `true` or `false` depending on
       *  whether a message was moderated or not.
       */
      async handleModeration(attrs) {
        const MODERATION_ATTRIBUTES = ['editable', 'moderated', 'moderated_by', 'moderated_id', 'moderation_reason'];

        if (attrs.moderated === 'retracted') {
          const query = {};
          const key = `stanza_id ${this.get('jid')}`;
          query[key] = attrs.moderated_id;
          const message = this.messages.findWhere(query);

          if (!message) {
            attrs['dangling_moderation'] = true;
            await this.createMessage(attrs);
            return true;
          }

          message.save(lodash_es_pick(attrs, MODERATION_ATTRIBUTES));
          return true;
        } else {
          // Check if we have dangling moderation message
          const message = this.findDanglingModeration(attrs);

          if (message) {
            const moderation_attrs = lodash_es_pick(message.attributes, MODERATION_ATTRIBUTES);
            const new_attrs = Object.assign({
              'dangling_moderation': false
            }, attrs, moderation_attrs);
            delete new_attrs['id']; // Delete id, otherwise a new cache entry gets created

            message.save(new_attrs);
            return true;
          }
        }

        return false;
      },

      /**
       * @param {String} actor - The nickname of the actor that caused the notification
       * @param {String|Array<String>} states - The state or states representing the type of notificcation
       */
      removeNotification(actor, states) {
        const actors_per_state = this.notifications.toJSON();
        states = Array.isArray(states) ? states : [states];
        states.forEach(state => {
          const existing_actors = Array.from(actors_per_state[state] || []);

          if (existing_actors.includes(actor)) {
            const idx = existing_actors.indexOf(actor);
            existing_actors.splice(idx, 1);
            this.notifications.set(state, Array.from(existing_actors));
          }
        });
      },

      /**
       * Update the notifications model by adding the passed in nickname
       * to the array of nicknames that all match a particular state.
       *
       * Removes the nickname from any other states it might be associated with.
       *
       * The state can be a XEP-0085 Chat State or a XEP-0045 join/leave
       * state.
       * @param {String} actor - The nickname of the actor that causes the notification
       * @param {String} state - The state representing the type of notificcation
       */
      updateNotifications(actor, state) {
        const actors_per_state = this.notifications.toJSON();
        const existing_actors = actors_per_state[state] || [];

        if (existing_actors.includes(actor)) {
          return;
        }

        const reducer = (out, s) => {
          if (s === state) {
            out[s] = [...existing_actors, actor];
          } else {
            out[s] = (actors_per_state[s] || []).filter(a => a !== actor);
          }

          return out;
        };

        const actors_per_chat_state = converse.CHAT_STATES.reduce(reducer, {});
        const actors_per_traffic_state = converse.MUC_TRAFFIC_STATES.reduce(reducer, {});
        const actors_per_role_change = converse.MUC_ROLE_CHANGES.reduce(reducer, {});
        this.notifications.set(Object.assign(actors_per_chat_state, actors_per_traffic_state, actors_per_role_change));
        window.setTimeout(() => this.removeNotification(actor, state), 10000);
      },

      /**
       * Handler for all MUC messages sent to this groupchat. This method
       * shouldn't be called directly, instead {@link _converse.ChatRoom#queueMessage}
       * should be called.
       * @private
       * @method _converse.ChatRoom#onMessage
       * @param { MessageAttributes } attrs - A promise which resolves to the message attributes.
       */
      async onMessage(attrs) {
        attrs = await attrs;

        if (utils_form.isErrorObject(attrs)) {
          attrs.stanza && headless_log.error(attrs.stanza);
          return headless_log.error(attrs.message);
        }

        const message = this.getDuplicateMessage(attrs);

        if (message) {
          return this.updateMessage(message, attrs);
        } else if (attrs.is_valid_receipt_request || attrs.is_marker || this.ignorableCSN(attrs)) {
          return;
        }

        if ((await this.handleRetraction(attrs)) || (await this.handleModeration(attrs)) || (await this.handleSubjectChange(attrs))) {
          return this.removeNotification(attrs.nick, ['composing', 'paused']);
        }

        this.setEditable(attrs, attrs.time);

        if (attrs['chat_state']) {
          this.updateNotifications(attrs.nick, attrs.chat_state);
        }

        if (utils_form.shouldCreateGroupchatMessage(attrs)) {
          const msg = this.handleCorrection(attrs) || (await this.createMessage(attrs));
          this.removeNotification(attrs.nick, ['composing', 'paused']);
          this.handleUnreadMessage(msg);
        }
      },

      handleModifyError(pres) {
        var _pres$querySelector;

        const text = (_pres$querySelector = pres.querySelector('error text')) === null || _pres$querySelector === void 0 ? void 0 : _pres$querySelector.textContent;

        if (text) {
          if (this.session.get('connection_status') === converse.ROOMSTATUS.CONNECTING) {
            this.setDisconnectionMessage(text);
          } else {
            const attrs = {
              'type': 'error',
              'message': text,
              'is_ephemeral': true
            };
            this.createMessage(attrs);
          }
        }
      },

      /**
       * Handle a presence stanza that disconnects the user from the MUC
       * @param { XMLElement } stanza
       */
      handleDisconnection(stanza) {
        var _item$querySelector;

        const is_self = stanza.querySelector("status[code='110']") !== null;
        const x = converse_muc_sizzle(`x[xmlns="${converse_muc_Strophe.NS.MUC_USER}"]`, stanza).pop();

        if (!x) {
          return;
        }

        const codes = converse_muc_sizzle('status', x).map(s => s.getAttribute('code'));
        const disconnection_codes = lodash_es_intersection(codes, Object.keys(converse_core_converse.muc.disconnect_messages));
        const disconnected = is_self && disconnection_codes.length > 0;

        if (!disconnected) {
          return;
        } // By using querySelector we assume here there is
        // one <item> per <x xmlns='http://jabber.org/protocol/muc#user'>
        // element. This appears to be a safe assumption, since
        // each <x/> element pertains to a single user.


        const item = x.querySelector('item');
        const reason = item ? (_item$querySelector = item.querySelector('reason')) === null || _item$querySelector === void 0 ? void 0 : _item$querySelector.textContent : undefined;
        const actor = item ? lodash_es_invoke(item.querySelector('actor'), 'getAttribute', 'nick') : undefined;
        const message = converse_core_converse.muc.disconnect_messages[disconnection_codes[0]];
        this.setDisconnectionMessage(message, reason, actor);
      },

      getActionInfoMessage(code, nick, actor) {
        if (code === '301') {
          return actor ? __("%1$s has been banned by %2$s", nick, actor) : __("%1$s has been banned", nick);
        } else if (code === '303') {
          return __("%1$s\'s nickname has changed", nick);
        } else if (code === '307') {
          return actor ? __("%1$s has been kicked out by %2$s", nick, actor) : __("%1$s has been kicked out", nick);
        } else if (code === '321') {
          return __("%1$s has been removed because of an affiliation change", nick);
        } else if (code === '322') {
          return __("%1$s has been removed for not being a member", nick);
        }
      },

      createAffiliationChangeMessage(occupant) {
        const previous_affiliation = occupant._previousAttributes.affiliation;

        if (!previous_affiliation) {
          // If no previous affiliation was set, then we don't
          // interpret this as an affiliation change.
          // For example, if muc_send_probes is true, then occupants
          // are created based on incoming messages, in which case
          // we don't yet know the affiliation
          return;
        }

        const current_affiliation = occupant.get('affiliation');

        if (previous_affiliation === 'admin') {
          this.createMessage({
            'type': 'info',
            'message': __("%1$s is no longer an admin of this groupchat", occupant.get('nick'))
          });
        } else if (previous_affiliation === 'owner') {
          this.createMessage({
            'type': 'info',
            'message': __("%1$s is no longer an owner of this groupchat", occupant.get('nick'))
          });
        } else if (previous_affiliation === 'outcast') {
          this.createMessage({
            'type': 'info',
            'message': __("%1$s is no longer banned from this groupchat", occupant.get('nick'))
          });
        }

        if (current_affiliation === 'none' && previous_affiliation === 'member') {
          this.createMessage({
            'type': 'info',
            'message': __("%1$s is no longer a member of this groupchat", occupant.get('nick'))
          });
        }

        if (current_affiliation === 'member') {
          this.createMessage({
            'type': 'info',
            'message': __("%1$s is now a member of this groupchat", occupant.get('nick'))
          });
        } else if (current_affiliation === 'admin' || current_affiliation == 'owner') {
          // For example: AppleJack is now an (admin|owner) of this groupchat
          this.createMessage({
            'type': 'info',
            'message': __('%1$s is now an %2$s of this groupchat', occupant.get('nick'), current_affiliation)
          });
        }
      },

      createRoleChangeMessage(occupant, changed) {
        if (changed === "none" || occupant.changed.affiliation) {
          // We don't inform of role changes if they accompany affiliation changes.
          return;
        }

        const previous_role = occupant._previousAttributes.role;

        if (previous_role === 'moderator') {
          this.updateNotifications(occupant.get('nick'), 'deop');
        } else if (previous_role === 'visitor') {
          this.updateNotifications(occupant.get('nick'), 'voice');
        }

        if (occupant.get('role') === 'visitor') {
          this.updateNotifications(occupant.get('nick'), 'mute');
        } else if (occupant.get('role') === 'moderator') {
          if (!['owner', 'admin'].includes(occupant.get('affiliation'))) {
            // Oly show this message if the user isn't already
            // an admin or owner, otherwise this isn't new information.
            this.updateNotifications(occupant.get('nick'), 'op');
          }
        }
      },

      /**
       * Create an info message based on a received MUC status code
       * @private
       * @method _converse.ChatRoom#createInfoMessage
       * @param { string } code - The MUC status code
       * @param { XMLElement } stanza - The original stanza that contains the code
       * @param { Boolean } is_self - Whether this stanza refers to our own presence
       */
      createInfoMessage(code, stanza, is_self) {
        const data = {
          'type': 'info'
        };

        if (code === '110' || code === '100' && !is_self) {
          return;
        } else if (code in converse_core_converse.muc.info_messages) {
          data.message = converse_core_converse.muc.info_messages[code];
        } else if (!is_self && ACTION_INFO_CODES.includes(code)) {
          var _item$querySelector2, _item$querySelector3;

          const nick = converse_muc_Strophe.getResourceFromJid(stanza.getAttribute('from'));
          const item = converse_muc_sizzle(`x[xmlns="${converse_muc_Strophe.NS.MUC_USER}"] item`, stanza).pop();
          data.actor = item ? (_item$querySelector2 = item.querySelector('actor')) === null || _item$querySelector2 === void 0 ? void 0 : _item$querySelector2.getAttribute('nick') : undefined;
          data.reason = item ? (_item$querySelector3 = item.querySelector('reason')) === null || _item$querySelector3 === void 0 ? void 0 : _item$querySelector3.textContent : undefined;
          data.message = this.getActionInfoMessage(code, nick, data.actor);
        } else if (is_self && code in converse_core_converse.muc.new_nickname_messages) {
          // XXX: Side-effect of setting the nick. Should ideally be refactored out of this method
          let nick;

          if (is_self && code === "210") {
            nick = converse_muc_Strophe.getResourceFromJid(stanza.getAttribute('from'));
          } else if (is_self && code === "303") {
            nick = converse_muc_sizzle(`x[xmlns="${converse_muc_Strophe.NS.MUC_USER}"] item`, stanza).pop().getAttribute('nick');
          }

          this.save('nick', nick);
          data.message = __(converse_core_converse.muc.new_nickname_messages[code], nick);
        }

        if (data.message) {
          if (code === "201" && this.messages.findWhere(data)) {
            return;
          } else if (code in converse_core_converse.muc.info_messages && this.messages.length && this.messages.pop().get('message') === data.message) {
            // XXX: very naive duplication checking
            return;
          }

          this.createMessage(data);
        }
      },

      /**
       * Create info messages based on a received presence or message stanza
       * @private
       * @method _converse.ChatRoom#createInfoMessages
       * @param { XMLElement } stanza
       */
      createInfoMessages(stanza) {
        const codes = converse_muc_sizzle(`x[xmlns="${converse_muc_Strophe.NS.MUC_USER}"] status`, stanza).map(s => s.getAttribute('code'));

        if (codes.includes('333') && codes.includes('307')) {
          // See: https://github.com/xsf/xeps/pull/969/files#diff-ac5113766e59219806793c1f7d967f1bR4966
          codes.splice(codes.indexOf('307'), 1);
        }

        const is_self = codes.includes('110');
        codes.forEach(code => this.createInfoMessage(code, stanza, is_self));
      },

      setDisconnectionMessage(message, reason, actor) {
        this.save({
          'disconnection_message': message,
          'disconnection_reason': reason,
          'disconnection_actor': actor
        });
        this.session.save({
          'connection_status': converse.ROOMSTATUS.DISCONNECTED
        });
      },

      onNicknameClash(presence) {
        if (converse_core_api.settings.get('muc_nickname_from_jid')) {
          const nick = presence.getAttribute('from').split('/')[1];

          if (nick === converse_core_converse.getDefaultMUCNickname()) {
            this.join(nick + '-2');
          } else {
            const del = nick.lastIndexOf("-");
            const num = nick.substring(del + 1, nick.length);
            this.join(nick.substring(0, del + 1) + String(Number(num) + 1));
          }
        } else {
          this.save({
            'nickname_validation_message': __("The nickname you chose is reserved or " + "currently in use, please choose a different one.")
          });
          this.session.save({
            'connection_status': converse.ROOMSTATUS.NICKNAME_REQUIRED
          });
        }
      },

      /**
       * Parses a <presence> stanza with type "error" and sets the proper
       * `connection_status` value for this {@link _converse.ChatRoom} as
       * well as any additional output that can be shown to the user.
       * @private
       * @param { XMLElement } stanza - The presence stanza
       */
      onErrorPresence(stanza) {
        var _sizzle$pop;

        const error = stanza.querySelector('error');
        const error_type = error.getAttribute('type');
        const reason = (_sizzle$pop = converse_muc_sizzle(`text[xmlns="${converse_muc_Strophe.NS.STANZAS}"]`, error).pop()) === null || _sizzle$pop === void 0 ? void 0 : _sizzle$pop.textContent;

        if (error_type === 'modify') {
          this.handleModifyError(stanza);
        } else if (error_type === 'auth') {
          if (converse_muc_sizzle(`not-authorized[xmlns="${converse_muc_Strophe.NS.STANZAS}"]`, error).length) {
            this.save({
              'password_validation_message': reason || __("Password incorrect")
            });
            this.session.save({
              'connection_status': converse.ROOMSTATUS.PASSWORD_REQUIRED
            });
          }

          if (error.querySelector('registration-required')) {
            const message = __('You are not on the member list of this groupchat.');

            this.setDisconnectionMessage(message, reason);
          } else if (error.querySelector('forbidden')) {
            const message = __('You have been banned from this groupchat.');

            this.setDisconnectionMessage(message, reason);
          }
        } else if (error_type === 'cancel') {
          if (error.querySelector('not-allowed')) {
            const message = __('You are not allowed to create new groupchats.');

            this.setDisconnectionMessage(message, reason);
          } else if (error.querySelector('not-acceptable')) {
            const message = __("Your nickname doesn't conform to this groupchat's policies.");

            this.setDisconnectionMessage(message, reason);
          } else if (converse_muc_sizzle(`gone[xmlns="${converse_muc_Strophe.NS.STANZAS}"]`, error).length) {
            var _sizzle$pop2;

            const moved_jid = (_sizzle$pop2 = converse_muc_sizzle(`gone[xmlns="${converse_muc_Strophe.NS.STANZAS}"]`, error).pop()) === null || _sizzle$pop2 === void 0 ? void 0 : _sizzle$pop2.textContent.replace(/^xmpp:/, '').replace(/\?join$/, '');
            this.save({
              moved_jid,
              'destroyed_reason': reason
            });
            this.session.save({
              'connection_status': converse.ROOMSTATUS.DESTROYED
            });
          } else if (error.querySelector('conflict')) {
            this.onNicknameClash(stanza);
          } else if (error.querySelector('item-not-found')) {
            const message = __("This groupchat does not (yet) exist.");

            this.setDisconnectionMessage(message, reason);
          } else if (error.querySelector('service-unavailable')) {
            const message = __("This groupchat has reached its maximum number of participants.");

            this.setDisconnectionMessage(message, reason);
          } else if (error.querySelector('remote-server-not-found')) {
            const message = __("Remote server not found");

            const feedback = reason ? __('The explanation given is: "%1$s".', reason) : undefined;
            this.setDisconnectionMessage(message, feedback);
          }
        }
      },

      /**
       * Handles all MUC presence stanzas.
       * @private
       * @method _converse.ChatRoom#onPresence
       * @param { XMLElement } stanza
       */
      onPresence(stanza) {
        if (stanza.getAttribute('type') === 'error') {
          return this.onErrorPresence(stanza);
        }

        this.createInfoMessages(stanza);

        if (stanza.querySelector("status[code='110']")) {
          this.onOwnPresence(stanza);

          if (this.getOwnRole() !== 'none' && this.session.get('connection_status') === converse.ROOMSTATUS.CONNECTING) {
            this.session.save('connection_status', converse.ROOMSTATUS.CONNECTED);
          }
        } else {
          this.updateOccupantsOnPresence(stanza);
        }
      },

      /**
       * Handles a received presence relating to the current user.
       *
       * For locked groupchats (which are by definition "new"), the
       * groupchat will either be auto-configured or created instantly
       * (with default config) or a configuration groupchat will be
       * rendered.
       *
       * If the groupchat is not locked, then the groupchat will be
       * auto-configured only if applicable and if the current
       * user is the groupchat's owner.
       * @private
       * @method _converse.ChatRoom#onOwnPresence
       * @param { XMLElement } pres - The stanza
       */
      onOwnPresence(stanza) {
        if (stanza.getAttribute('type') !== 'unavailable') {
          const old_status = this.session.get('connection_status');

          if (old_status !== converse.ROOMSTATUS.ENTERED) {
            // Set connection_status before creating the occupant, but
            // only trigger afterwards, so that plugins can access the
            // occupant in their event handlers.
            this.session.save('connection_status', converse.ROOMSTATUS.ENTERED, {
              'silent': true
            });
            this.updateOccupantsOnPresence(stanza);
            this.session.trigger('change:connection_status', this.session, old_status);
          } else {
            this.updateOccupantsOnPresence(stanza);
          }
        } else {
          this.updateOccupantsOnPresence(stanza);
        }

        if (stanza.getAttribute('type') === 'unavailable') {
          this.handleDisconnection(stanza);
        } else {
          const locked_room = stanza.querySelector("status[code='201']");

          if (locked_room) {
            if (this.get('auto_configure')) {
              this.autoConfigureChatRoom().then(() => this.refreshDiscoInfo());
            } else if (converse_core_api.settings.get('muc_instant_rooms')) {
              // Accept default configuration
              this.sendConfiguration().then(() => this.refreshDiscoInfo());
            } else {
              /**
               * Triggered when a new room has been created which first needs to be configured
               * and when `auto_configure` is set to `false`.
               * Used by `_converse.ChatRoomView` in order to know when to render the
               * configuration form for a new room.
               * @event _converse.ChatRoom#configurationNeeded
               * @example _converse.api.listen.on('configurationNeeded', () => { ... });
               */
              this.trigger('configurationNeeded');
              return; // We haven't yet entered the groupchat, so bail here.
            }
          } else if (!this.features.get('fetched')) {
            // The features for this groupchat weren't fetched.
            // That must mean it's a new groupchat without locking
            // (in which case Prosody doesn't send a 201 status),
            // otherwise the features would have been fetched in
            // the "initialize" method already.
            if (this.getOwnAffiliation() === 'owner' && this.get('auto_configure')) {
              this.autoConfigureChatRoom().then(() => this.refreshDiscoInfo());
            } else {
              this.getDiscoInfo();
            }
          }
        }

        this.session.save({
          'connection_status': converse.ROOMSTATUS.ENTERED
        });
      },

      /**
       * Returns a boolean to indicate whether the current user
       * was mentioned in a message.
       * @private
       * @method _converse.ChatRoom#isUserMentioned
       * @param { String } - The text message
       */
      isUserMentioned(message) {
        const nick = this.get('nick');

        if (message.get('references').length) {
          const mentions = message.get('references').filter(ref => ref.type === 'mention').map(ref => ref.value);
          return mentions.includes(nick);
        } else {
          return new RegExp(`\\b${nick}\\b`).test(message.get('message'));
        }
      },

      /* Given a newly received message, update the unread counter if necessary.
       * @private
       * @method _converse.ChatRoom#handleUnreadMessage
       * @param { XMLElement } - The <messsage> stanza
       */
      handleUnreadMessage(message) {
        if (!(message !== null && message !== void 0 && message.get('body'))) {
          return;
        }

        if (utils_form.isNewMessage(message)) {
          if (this.isHidden()) {
            const settings = {
              'num_unread_general': this.get('num_unread_general') + 1
            };

            if (this.get('num_unread_general') === 0) {
              settings['first_unread_id'] = message.get('id');
            }

            if (this.isUserMentioned(message)) {
              settings.num_unread = this.get('num_unread') + 1;
            }

            this.save(settings);
          } else {
            this.sendMarkerForMessage(message);
          }
        }
      },

      clearUnreadMsgCounter() {
        if (this.get('num_unread_general') > 0 || this.get('num_unread') > 0) {
          this.sendMarkerForMessage(this.messages.last());
        }

        utils_form.safeSave(this, {
          'num_unread': 0,
          'num_unread_general': 0
        });
      }

    });
    /**
     * Represents a participant in a MUC
     * @class
     * @namespace _converse.ChatRoomOccupant
     * @memberOf _converse
     */

    converse_core_converse.ChatRoomOccupant = model_Model.extend({
      defaults: {
        'hats': [],
        'show': 'offline',
        'states': []
      },

      initialize(attributes) {
        this.set(Object.assign({
          'id': utils_form.getUniqueId()
        }, attributes));
        this.on('change:image_hash', this.onAvatarChanged, this);
      },

      onAvatarChanged() {
        const hash = this.get('image_hash');
        const vcards = [];

        if (this.get('jid')) {
          vcards.push(converse_core_converse.vcards.findWhere({
            'jid': this.get('jid')
          }));
        }

        vcards.push(converse_core_converse.vcards.findWhere({
          'jid': this.get('from')
        }));
        vcards.filter(v => v).forEach(vcard => {
          if (hash && vcard.get('image_hash') !== hash) {
            converse_core_api.vcard.update(vcard, true);
          }
        });
      },

      getDisplayName() {
        return this.get('nick') || this.get('jid');
      },

      isMember() {
        return ['admin', 'owner', 'member'].includes(this.get('affiliation'));
      },

      isModerator() {
        return ['admin', 'owner'].includes(this.get('affiliation')) || this.get('role') === 'moderator';
      },

      isSelf() {
        return this.get('states').includes('110');
      }

    });
    /**
     * A list of {@link _converse.ChatRoomOccupant} instances, representing participants in a MUC.
     * @class
     * @namespace _converse.ChatRoomOccupants
     * @memberOf _converse
     */

    converse_core_converse.ChatRoomOccupants = Collection.extend({
      model: converse_core_converse.ChatRoomOccupant,

      comparator(occupant1, occupant2) {
        const role1 = occupant1.get('role') || 'none';
        const role2 = occupant2.get('role') || 'none';

        if (MUC_ROLE_WEIGHTS[role1] === MUC_ROLE_WEIGHTS[role2]) {
          const nick1 = occupant1.getDisplayName().toLowerCase();
          const nick2 = occupant2.getDisplayName().toLowerCase();
          return nick1 < nick2 ? -1 : nick1 > nick2 ? 1 : 0;
        } else {
          return MUC_ROLE_WEIGHTS[role1] < MUC_ROLE_WEIGHTS[role2] ? -1 : 1;
        }
      },

      getAutoFetchedAffiliationLists() {
        const affs = converse_core_api.settings.get('muc_fetch_members');
        return Array.isArray(affs) ? affs : affs ? ['member', 'admin', 'owner'] : [];
      },

      async fetchMembers() {
        const affiliations = this.getAutoFetchedAffiliationLists();

        if (affiliations.length === 0) {
          return;
        }

        const aff_lists = await Promise.all(affiliations.map(a => this.chatroom.getAffiliationList(a)));
        const new_members = aff_lists.reduce((acc, val) => utils_form.isErrorObject(val) ? acc : [...val, ...acc], []);
        const known_affiliations = affiliations.filter(a => !utils_form.isErrorObject(aff_lists[affiliations.indexOf(a)]));
        const new_jids = new_members.map(m => m.jid).filter(m => m !== undefined);
        const new_nicks = new_members.map(m => !m.jid && m.nick || undefined).filter(m => m !== undefined);
        const removed_members = this.filter(m => {
          return known_affiliations.includes(m.get('affiliation')) && !new_nicks.includes(m.get('nick')) && !new_jids.includes(m.get('jid'));
        });
        removed_members.forEach(occupant => {
          if (occupant.get('jid') === converse_core_converse.bare_jid) {
            return;
          }

          if (occupant.get('show') === 'offline') {
            occupant.destroy();
          } else {
            occupant.save('affiliation', null);
          }
        });
        new_members.forEach(attrs => {
          const occupant = attrs.jid ? this.findOccupant({
            'jid': attrs.jid
          }) : this.findOccupant({
            'nick': attrs.nick
          });

          if (occupant) {
            occupant.save(attrs);
          } else {
            this.create(attrs);
          }
        });
        /**
         * Triggered once the member lists for this MUC have been fetched and processed.
         * @event _converse#membersFetched
         * @example _converse.api.listen.on('membersFetched', () => { ... });
         */

        converse_core_api.trigger('membersFetched');
      },

      /**
       * @typedef { Object} OccupantData
       * @property { String } [jid]
       * @property { String } [nick]
       */

      /**
       * Try to find an existing occupant based on the passed in
       * data object.
       *
       * If we have a JID, we use that as lookup variable,
       * otherwise we use the nick. We don't always have both,
       * but should have at least one or the other.
       * @private
       * @method _converse.ChatRoomOccupants#findOccupant
       * @param { OccupantData } data
       */
      findOccupant(data) {
        const jid = converse_muc_Strophe.getBareJidFromJid(data.jid);
        return jid && this.findWhere({
          jid
        }) || this.findWhere({
          'nick': data.nick
        });
      }

    });
    converse_core_converse.RoomsPanelModel = model_Model.extend({
      defaults: function () {
        return {
          'muc_domain': converse_core_api.settings.get('muc_domain'),
          'nick': converse_core_converse.getDefaultMUCNickname()
        };
      },

      setDomain(jid) {
        if (!converse_core_api.settings.get('locked_muc_domain')) {
          this.save('muc_domain', converse_muc_Strophe.getDomainFromJid(jid));
        }
      }

    });
    /**
     * A direct MUC invitation to join a groupchat has been received
     * See XEP-0249: Direct MUC invitations.
     * @private
     * @method _converse.ChatRoom#onDirectMUCInvitation
     * @param { XMLElement } message - The message stanza containing the invitation.
     */

    converse_core_converse.onDirectMUCInvitation = async function (message) {
      const x_el = converse_muc_sizzle('x[xmlns="jabber:x:conference"]', message).pop(),
            from = converse_muc_Strophe.getBareJidFromJid(message.getAttribute('from')),
            room_jid = x_el.getAttribute('jid'),
            reason = x_el.getAttribute('reason');
      let result;

      if (converse_core_api.settings.get('auto_join_on_invite')) {
        result = true;
      } else {
        // Invite request might come from someone not your roster list
        let contact = converse_core_converse.roster.get(from);

        contact = contact ? contact.getDisplayName() : from;

        if (!reason) {
          result = confirm(__("%1$s has invited you to join a groupchat: %2$s", contact, room_jid));
        } else {
          result = confirm(__('%1$s has invited you to join a groupchat: %2$s, and left the following reason: "%3$s"', contact, room_jid, reason));
        }
      }

      if (result === true) {
        const chatroom = await openChatRoom(room_jid, {
          'password': x_el.getAttribute('password')
        });

        if (chatroom.session.get('connection_status') === converse.ROOMSTATUS.DISCONNECTED) {
          converse_core_converse.chatboxes.get(room_jid).rejoin();
        }
      }
    };

    if (converse_core_api.settings.get('allow_muc_invitations')) {
      const registerDirectInvitationHandler = function () {
        converse_core_converse.connection.addHandler(message => {
          converse_core_converse.onDirectMUCInvitation(message);

          return true;
        }, 'jabber:x:conference', 'message');
      };

      converse_core_api.listen.on('connected', registerDirectInvitationHandler);
      converse_core_api.listen.on('reconnected', registerDirectInvitationHandler);
    }
    /* Automatically join groupchats, based on the
     * "auto_join_rooms" configuration setting, which is an array
     * of strings (groupchat JIDs) or objects (with groupchat JID and other settings).
     */


    async function autoJoinRooms() {
      await Promise.all(converse_core_api.settings.get('auto_join_rooms').map(muc => {
        if (typeof muc === 'string') {
          if (converse_core_converse.chatboxes.where({
            'jid': muc
          }).length) {
            return Promise.resolve();
          }

          return converse_core_api.rooms.open(muc);
        } else if (lodash_es_isObject(muc)) {
          return converse_core_api.rooms.open(muc.jid, { ...muc
          });
        } else {
          headless_log.error('Invalid muc criteria specified for "auto_join_rooms"');
          return Promise.resolve();
        }
      }));
      /**
       * Triggered once any rooms that have been configured to be automatically joined,
       * specified via the _`auto_join_rooms` setting, have been entered.
       * @event _converse#roomsAutoJoined
       * @example _converse.api.listen.on('roomsAutoJoined', () => { ... });
       * @example _converse.api.waitUntil('roomsAutoJoined').then(() => { ... });
       */

      converse_core_api.trigger('roomsAutoJoined');
    }

    async function onWindowStateChanged(data) {
      if (data.state === 'visible' && converse_core_api.connection.connected()) {
        const rooms = await converse_core_api.rooms.get();
        rooms.forEach(room => room.rejoinIfNecessary());
      }
    }
    /************************ BEGIN Event Handlers ************************/


    converse_core_api.listen.on('beforeTearDown', () => {
      const groupchats = converse_core_converse.chatboxes.where({
        'type': converse_core_converse.CHATROOMS_TYPE
      });

      groupchats.forEach(muc => utils_form.safeSave(muc.session, {
        'connection_status': converse.ROOMSTATUS.DISCONNECTED
      }));
    });
    converse_core_api.listen.on('windowStateChanged', onWindowStateChanged);
    converse_core_api.listen.on('addClientFeatures', () => {
      if (converse_core_api.settings.get('allow_muc')) {
        converse_core_api.disco.own.features.add(converse_muc_Strophe.NS.MUC);
      }

      if (converse_core_api.settings.get('allow_muc_invitations')) {
        converse_core_api.disco.own.features.add('jabber:x:conference'); // Invites
      }
    });
    converse_core_api.listen.on('chatBoxesFetched', autoJoinRooms);
    converse_core_api.listen.on('beforeResourceBinding', () => {
      converse_core_converse.connection.addHandler(stanza => {
        const muc_jid = converse_muc_Strophe.getBareJidFromJid(stanza.getAttribute('from'));

        if (!converse_core_converse.chatboxes.get(muc_jid)) {
          converse_core_api.waitUntil('chatBoxesFetched').then(async () => {
            const muc = converse_core_converse.chatboxes.get(muc_jid);

            if (muc) {
              await muc.initialized;
              muc.message_handler.run(stanza);
            }
          });
        }

        return true;
      }, null, 'message', 'groupchat');
    });

    function disconnectChatRooms() {
      /* When disconnecting, mark all groupchats as
       * disconnected, so that they will be properly entered again
       * when fetched from session storage.
       */
      return converse_core_converse.chatboxes.filter(m => m.get('type') === converse_core_converse.CHATROOMS_TYPE).forEach(m => m.session.save({
        'connection_status': converse.ROOMSTATUS.DISCONNECTED
      }));
    }

    converse_core_api.listen.on('disconnected', disconnectChatRooms);
    converse_core_api.listen.on('statusInitialized', () => {
      window.addEventListener(converse_core_converse.unloadevent, () => {
        const using_websocket = converse_core_api.connection.isType('websocket');

        if (using_websocket && (!converse_core_api.settings.get('enable_smacks') || !converse_core_converse.session.get('smacks_stream_id'))) {
          // For non-SMACKS websocket connections, or non-resumeable
          // connections, we disconnect all chatrooms when the page unloads.
          // See issue #1111
          disconnectChatRooms();
        }
      });
    });
    /************************ END Event Handlers ************************/

    /************************ BEGIN API ************************/

    converse.env.muc_utils = utils_muc; // We extend the default converse.js API to add methods specific to MUC groupchats.

    Object.assign(converse_core_api, {
      /**
       * The "rooms" namespace groups methods relevant to chatrooms
       * (aka groupchats).
       *
       * @namespace api.rooms
       * @memberOf api
       */
      rooms: {
        /**
         * Creates a new MUC chatroom (aka groupchat)
         *
         * Similar to {@link api.rooms.open}, but creates
         * the chatroom in the background (i.e. doesn't cause a view to open).
         *
         * @method api.rooms.create
         * @param {(string[]|string)} jid|jids The JID or array of
         *     JIDs of the chatroom(s) to create
         * @param {object} [attrs] attrs The room attributes
         * @returns {Promise} Promise which resolves with the Model representing the chat.
         */
        create(jids, attrs = {}) {
          attrs = typeof attrs === 'string' ? {
            'nick': attrs
          } : attrs || {};

          if (!attrs.nick && converse_core_api.settings.get('muc_nickname_from_jid')) {
            attrs.nick = converse_muc_Strophe.getNodeFromJid(converse_core_converse.bare_jid);
          }

          if (jids === undefined) {
            throw new TypeError('rooms.create: You need to provide at least one JID');
          } else if (typeof jids === 'string') {
            return converse_core_api.rooms.get(utils_form.getJIDFromURI(jids), attrs, true);
          }

          return jids.map(jid => converse_core_api.rooms.get(utils_form.getJIDFromURI(jid), attrs, true));
        },

        /**
         * Opens a MUC chatroom (aka groupchat)
         *
         * Similar to {@link api.chats.open}, but for groupchats.
         *
         * @method api.rooms.open
         * @param {string} jid The room JID or JIDs (if not specified, all
         *     currently open rooms will be returned).
         * @param {string} attrs A map  containing any extra room attributes.
         * @param {string} [attrs.nick] The current user's nickname for the MUC
         * @param {boolean} [attrs.auto_configure] A boolean, indicating
         *     whether the room should be configured automatically or not.
         *     If set to `true`, then it makes sense to pass in configuration settings.
         * @param {object} [attrs.roomconfig] A map of configuration settings to be used when the room gets
         *     configured automatically. Currently it doesn't make sense to specify
         *     `roomconfig` values if `auto_configure` is set to `false`.
         *     For a list of configuration values that can be passed in, refer to these values
         *     in the [XEP-0045 MUC specification](https://xmpp.org/extensions/xep-0045.html#registrar-formtype-owner).
         *     The values should be named without the `muc#roomconfig_` prefix.
         * @param {boolean} [attrs.minimized] A boolean, indicating whether the room should be opened minimized or not.
         * @param {boolean} [attrs.bring_to_foreground] A boolean indicating whether the room should be
         *     brought to the foreground and therefore replace the currently shown chat.
         *     If there is no chat currently open, then this option is ineffective.
         * @param {Boolean} [force=false] - By default, a minimized
         *   room won't be maximized (in `overlayed` view mode) and in
         *   `fullscreen` view mode a newly opened room won't replace
         *   another chat already in the foreground.
         *   Set `force` to `true` if you want to force the room to be
         *   maximized or shown.
         * @returns {Promise} Promise which resolves with the Model representing the chat.
         *
         * @example
         * this.api.rooms.open('group@muc.example.com')
         *
         * @example
         * // To return an array of rooms, provide an array of room JIDs:
         * api.rooms.open(['group1@muc.example.com', 'group2@muc.example.com'])
         *
         * @example
         * // To setup a custom nickname when joining the room, provide the optional nick argument:
         * api.rooms.open('group@muc.example.com', {'nick': 'mycustomnick'})
         *
         * @example
         * // For example, opening a room with a specific default configuration:
         * api.rooms.open(
         *     'myroom@conference.example.org',
         *     { 'nick': 'coolguy69',
         *       'auto_configure': true,
         *       'roomconfig': {
         *           'changesubject': false,
         *           'membersonly': true,
         *           'persistentroom': true,
         *           'publicroom': true,
         *           'roomdesc': 'Comfy room for hanging out',
         *           'whois': 'anyone'
         *       }
         *     }
         * );
         */
        async open(jids, attrs = {}, force = false) {
          await converse_core_api.waitUntil('chatBoxesFetched');

          if (jids === undefined) {
            const err_msg = 'rooms.open: You need to provide at least one JID';
            headless_log.error(err_msg);
            throw new TypeError(err_msg);
          } else if (typeof jids === 'string') {
            const room = await converse_core_api.rooms.get(jids, attrs, true);
            room && room.maybeShow(force);
            return room;
          } else {
            const rooms = await Promise.all(jids.map(jid => converse_core_api.rooms.get(jid, attrs, true)));
            rooms.forEach(r => r.maybeShow(force));
            return rooms;
          }
        },

        /**
         * Fetches the object representing a MUC chatroom (aka groupchat)
         *
         * @method api.rooms.get
         * @param {string} [jid] The room JID (if not specified, all rooms will be returned).
         * @param {object} [attrs] A map containing any extra room attributes For example, if you want
         *     to specify a nickname and password, use `{'nick': 'bloodninja', 'password': 'secret'}`.
         * @param {boolean} create A boolean indicating whether the room should be created
         *     if not found (default: `false`)
         * @returns { Promise<_converse.ChatRoom> }
         * @example
         * api.waitUntil('roomsAutoJoined').then(() => {
         *     const create_if_not_found = true;
         *     api.rooms.get(
         *         'group@muc.example.com',
         *         {'nick': 'dread-pirate-roberts'},
         *         create_if_not_found
         *     )
         * });
         */
        async get(jids, attrs = {}, create = false) {
          async function _get(jid) {
            jid = utils_form.getJIDFromURI(jid);
            let model = await converse_core_api.chatboxes.get(jid);

            if (!model && create) {
              model = await converse_core_api.chatboxes.create(jid, attrs, converse_core_converse.ChatRoom);
            } else {
              model = model && model.get('type') === converse_core_converse.CHATROOMS_TYPE ? model : null;

              if (model && Object.keys(attrs).length) {
                model.save(attrs);
              }
            }

            return model;
          }

          if (jids === undefined) {
            const chats = await converse_core_api.chatboxes.get();
            return chats.filter(c => c.get('type') === converse_core_converse.CHATROOMS_TYPE);
          } else if (typeof jids === 'string') {
            return _get(jids);
          }

          return Promise.all(jids.map(jid => _get(jid)));
        }

      }
    });
    /************************ END API ************************/
  }

});
// CONCATENATED MODULE: ./src/headless/converse-bookmarks.js
/**
 * @module converse-bookmarks
 * @description
 * Converse.js plugin which adds views for bookmarks specified in XEP-0048.
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */





const {
  Strophe: converse_bookmarks_Strophe,
  $iq: converse_bookmarks_$iq,
  sizzle: converse_bookmarks_sizzle
} = converse.env;
const converse_bookmarks_u = converse.env.utils;
converse_bookmarks_Strophe.addNamespace('BOOKMARKS', 'storage:bookmarks');

function handleBookmarksPush(message) {
  if (converse_bookmarks_sizzle(`event[xmlns="${converse_bookmarks_Strophe.NS.PUBSUB}#event"] items[node="${converse_bookmarks_Strophe.NS.BOOKMARKS}"]`, message).length) {
    converse_core_api.waitUntil('bookmarksInitialized').then(() => converse_core_converse.bookmarks.createBookmarksFromStanza(message)).catch(e => headless_log.fatal(e));
  }

  return true;
}

converse.plugins.add('converse-bookmarks', {
  /* Plugin dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin.
   *
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found. By default it's
   * false, which means these plugins are only loaded opportunistically.
   *
   * NB: These plugins need to have already been loaded via require.js.
   */
  dependencies: ["converse-chatboxes", "converse-muc"],
  overrides: {
    // Overrides mentioned here will be picked up by converse.js's
    // plugin architecture they will replace existing methods on the
    // relevant objects or classes.
    //
    // New functions which don't exist yet can also be added.
    ChatRoom: {
      getDisplayName() {
        const {
          _converse
        } = this.__super__;

        if (this.get('bookmarked') && _converse.bookmarks) {
          const bookmark = _converse.bookmarks.findWhere({
            'jid': this.get('jid')
          });

          if (bookmark) {
            return bookmark.get('name');
          }
        }

        return this.__super__.getDisplayName.apply(this, arguments);
      },

      getAndPersistNickname(nick) {
        const {
          _converse
        } = this.__super__;
        nick = nick || _converse.getNicknameFromBookmark(this.get('jid'));
        return this.__super__.getAndPersistNickname.call(this, nick);
      }

    }
  },

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    const {
      __
    } = converse_core_converse; // Configuration values for this plugin
    // ====================================
    // Refer to docs/source/configuration.rst for explanations of these
    // configuration settings.

    converse_core_api.settings.extend({
      allow_bookmarks: true,
      allow_public_bookmarks: false,
      muc_respect_autojoin: true
    });
    converse_core_api.promises.add('bookmarksInitialized');
    /**
      * Check if the user has a bookmark with a saved nickanme
      * for this groupchat and return it.
      * @private
      * @method _converse#getNicknameFromBookmark
      */

    converse_core_converse.getNicknameFromBookmark = function (jid) {
      if (!converse_core_converse.bookmarks || !converse_core_api.settings.get('allow_bookmarks')) {
        return null;
      }

      const bookmark = converse_core_converse.bookmarks.findWhere({
        'jid': jid
      });

      if (bookmark) {
        return bookmark.get('nick');
      }
    };

    converse_core_converse.Bookmark = model_Model.extend({
      idAttribute: 'jid',

      getDisplayName() {
        return converse_bookmarks_Strophe.xmlunescape(this.get('name'));
      }

    });
    converse_core_converse.Bookmarks = Collection.extend({
      model: converse_core_converse.Bookmark,
      comparator: item => item.get('name').toLowerCase(),

      initialize() {
        this.on('add', bm => this.openBookmarkedRoom(bm).then(bm => this.markRoomAsBookmarked(bm)).catch(e => headless_log.fatal(e)));
        this.on('remove', this.markRoomAsUnbookmarked, this);
        this.on('remove', this.sendBookmarkStanza, this);
        const cache_key = `converse.room-bookmarks${converse_core_converse.bare_jid}`;
        this.fetched_flag = cache_key + 'fetched';
        this.browserStorage = converse_core_converse.createStore(cache_key);
      },

      async openBookmarkedRoom(bookmark) {
        if (converse_core_api.settings.get('muc_respect_autojoin') && bookmark.get('autojoin')) {
          const groupchat = await converse_core_api.rooms.create(bookmark.get('jid'), {
            'nick': bookmark.get('nick')
          });
          groupchat.maybeShow();
        }

        return bookmark;
      },

      fetchBookmarks() {
        const deferred = converse_bookmarks_u.getResolveablePromise();

        if (window.sessionStorage.getItem(this.fetched_flag)) {
          this.fetch({
            'success': () => deferred.resolve(),
            'error': () => deferred.resolve()
          });
        } else {
          this.fetchBookmarksFromServer(deferred);
        }

        return deferred;
      },

      createBookmark(options) {
        this.create(options);
        this.sendBookmarkStanza().catch(iq => this.onBookmarkError(iq, options));
      },

      sendBookmarkStanza() {
        const stanza = converse_bookmarks_$iq({
          'type': 'set',
          'from': converse_core_converse.connection.jid
        }).c('pubsub', {
          'xmlns': converse_bookmarks_Strophe.NS.PUBSUB
        }).c('publish', {
          'node': converse_bookmarks_Strophe.NS.BOOKMARKS
        }).c('item', {
          'id': 'current'
        }).c('storage', {
          'xmlns': converse_bookmarks_Strophe.NS.BOOKMARKS
        });
        this.forEach(model => {
          stanza.c('conference', {
            'name': model.get('name'),
            'autojoin': model.get('autojoin'),
            'jid': model.get('jid')
          }).c('nick').t(model.get('nick')).up().up();
        });
        stanza.up().up().up();
        stanza.c('publish-options').c('x', {
          'xmlns': converse_bookmarks_Strophe.NS.XFORM,
          'type': 'submit'
        }).c('field', {
          'var': 'FORM_TYPE',
          'type': 'hidden'
        }).c('value').t('http://jabber.org/protocol/pubsub#publish-options').up().up().c('field', {
          'var': 'pubsub#persist_items'
        }).c('value').t('true').up().up().c('field', {
          'var': 'pubsub#access_model'
        }).c('value').t('whitelist');
        return converse_core_api.sendIQ(stanza);
      },

      onBookmarkError(iq, options) {
        headless_log.error("Error while trying to add bookmark");
        headless_log.error(iq);
        converse_core_api.alert('error', __('Error'), [__("Sorry, something went wrong while trying to save your bookmark.")]);
        this.findWhere({
          'jid': options.jid
        }).destroy();
      },

      fetchBookmarksFromServer(deferred) {
        const stanza = converse_bookmarks_$iq({
          'from': converse_core_converse.connection.jid,
          'type': 'get'
        }).c('pubsub', {
          'xmlns': converse_bookmarks_Strophe.NS.PUBSUB
        }).c('items', {
          'node': converse_bookmarks_Strophe.NS.BOOKMARKS
        });
        converse_core_api.sendIQ(stanza).then(iq => this.onBookmarksReceived(deferred, iq)).catch(iq => this.onBookmarksReceivedError(deferred, iq));
      },

      markRoomAsBookmarked(bookmark) {
        const groupchat = converse_core_converse.chatboxes.get(bookmark.get('jid'));

        if (groupchat !== undefined) {
          groupchat.save('bookmarked', true);
        }
      },

      markRoomAsUnbookmarked(bookmark) {
        const groupchat = converse_core_converse.chatboxes.get(bookmark.get('jid'));

        if (groupchat !== undefined) {
          groupchat.save('bookmarked', false);
        }
      },

      createBookmarksFromStanza(stanza) {
        const xmlns = converse_bookmarks_Strophe.NS.BOOKMARKS;
        const sel = `items[node="${xmlns}"] item storage[xmlns="${xmlns}"] conference`;
        converse_bookmarks_sizzle(sel, stanza).forEach(el => {
          var _el$querySelector;

          const jid = el.getAttribute('jid');
          const bookmark = this.get(jid);
          const attrs = {
            'jid': jid,
            'name': el.getAttribute('name') || jid,
            'autojoin': el.getAttribute('autojoin') === 'true',
            'nick': ((_el$querySelector = el.querySelector('nick')) === null || _el$querySelector === void 0 ? void 0 : _el$querySelector.textContent) || ''
          };
          bookmark ? bookmark.save(attrs) : this.create(attrs);
        });
      },

      onBookmarksReceived(deferred, iq) {
        this.createBookmarksFromStanza(iq);
        window.sessionStorage.setItem(this.fetched_flag, true);

        if (deferred !== undefined) {
          return deferred.resolve();
        }
      },

      onBookmarksReceivedError(deferred, iq) {
        if (iq === null) {
          headless_log.error('Error: timeout while fetching bookmarks');
          converse_core_api.alert('error', __('Timeout Error'), [__("The server did not return your bookmarks within the allowed time. " + "You can reload the page to request them again.")]);
        } else if (deferred) {
          if (iq.querySelector('error[type="cancel"] item-not-found')) {
            // Not an exception, the user simply doesn't have any bookmarks.
            window.sessionStorage.setItem(this.fetched_flag, true);
            return deferred.resolve();
          } else {
            headless_log.error('Error while fetching bookmarks');
            headless_log.error(iq);
            return deferred.reject(new Error("Could not fetch bookmarks"));
          }
        } else {
          headless_log.error('Error while fetching bookmarks');
          headless_log.error(iq);
        }
      },

      getUnopenedBookmarks() {
        return this.filter(b => !converse_core_converse.chatboxes.get(b.get('jid')));
      }

    });
    converse_core_converse.BookmarksList = model_Model.extend({
      defaults: {
        "toggle-state": converse_core_converse.OPENED
      }
    });

    converse_core_converse.checkBookmarksSupport = async function () {
      const identity = await converse_core_api.disco.getIdentity('pubsub', 'pep', converse_core_converse.bare_jid);

      if (converse_core_converse.allow_public_bookmarks) {
        return !!identity;
      } else {
        return converse_core_api.disco.supports(converse_bookmarks_Strophe.NS.PUBSUB + '#publish-options', converse_core_converse.bare_jid);
      }
    };

    const initBookmarks = async function () {
      if (!converse_core_api.settings.get('allow_bookmarks')) {
        return;
      }

      if (await converse_core_converse.checkBookmarksSupport()) {
        converse_core_converse.bookmarks = new converse_core_converse.Bookmarks();
        await converse_core_converse.bookmarks.fetchBookmarks();
        /**
         * Triggered once the _converse.Bookmarks collection
         * has been created and cached bookmarks have been fetched.
         * @event _converse#bookmarksInitialized
         * @example _converse.api.listen.on('bookmarksInitialized', () => { ... });
         */

        converse_core_api.trigger('bookmarksInitialized');
      }
    };

    converse_core_api.listen.on('addClientFeatures', () => {
      if (converse_core_api.settings.get('allow_bookmarks')) {
        converse_core_api.disco.own.features.add(converse_bookmarks_Strophe.NS.BOOKMARKS + '+notify');
      }
    });
    converse_core_api.listen.on('clearSession', () => {
      if (converse_core_converse.bookmarks !== undefined) {
        converse_core_converse.bookmarks.clearStore({
          'silent': true
        });

        window.sessionStorage.removeItem(converse_core_converse.bookmarks.fetched_flag);
        delete converse_core_converse.bookmarks;
      }
    });
    converse_core_api.listen.on('reconnected', initBookmarks);
    converse_core_api.listen.on('connected', async () => {
      // Add a handler for bookmarks pushed from other connected clients
      const {
        connection
      } = converse_core_converse;
      connection.addHandler(handleBookmarksPush, null, 'message', 'headline', null, converse_core_converse.bare_jid);
      await Promise.all([converse_core_api.waitUntil('chatBoxesFetched')]);
      initBookmarks();
    });
  }

});
// EXTERNAL MODULE: ./node_modules/strophe.js/src/bosh.js
var bosh = __webpack_require__(152);

// CONCATENATED MODULE: ./src/headless/converse-bosh.js
/**
 * @module converse-bosh
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description Converse.js plugin which add support for XEP-0206: XMPP Over BOSH
 */




const {
  Strophe: converse_bosh_Strophe
} = converse.env;
const BOSH_SESSION_ID = 'converse.bosh-session';
converse.plugins.add('converse-bosh', {
  enabled() {
    return !converse_core_converse.api.settings.get("blacklisted_plugins").includes('converse-bosh');
  },

  initialize() {
    converse_core_api.settings.extend({
      bosh_service_url: undefined,
      prebind_url: null
    });

    async function initBOSHSession() {
      const id = BOSH_SESSION_ID;

      if (!converse_core_converse.bosh_session) {
        converse_core_converse.bosh_session = new model_Model({
          id
        });
        converse_core_converse.bosh_session.browserStorage = converse_core_converse.createStore(id, "session");
        await new Promise(resolve => converse_core_converse.bosh_session.fetch({
          'success': resolve,
          'error': resolve
        }));
      }

      if (converse_core_converse.jid) {
        if (converse_core_converse.bosh_session.get('jid') !== converse_core_converse.jid) {
          const jid = await converse_core_converse.setUserJID(converse_core_converse.jid);

          converse_core_converse.bosh_session.clear({
            'silent': true
          });

          converse_core_converse.bosh_session.save({
            jid
          });
        }
      } else {
        // Keepalive
        const jid = converse_core_converse.bosh_session.get('jid');

        jid && (await converse_core_converse.setUserJID(jid));
      }

      return converse_core_converse.bosh_session;
    }

    converse_core_converse.startNewPreboundBOSHSession = function () {
      if (!converse_core_api.settings.get('prebind_url')) {
        throw new Error("startNewPreboundBOSHSession: If you use prebind then you MUST supply a prebind_url");
      }

      const xhr = new XMLHttpRequest();
      xhr.open('GET', converse_core_api.settings.get('prebind_url'), true);
      xhr.setRequestHeader('Accept', 'application/json, text/javascript');

      xhr.onload = async function () {
        if (xhr.status >= 200 && xhr.status < 400) {
          const data = JSON.parse(xhr.responseText);
          const jid = await converse_core_converse.setUserJID(data.jid);

          converse_core_converse.connection.attach(jid, data.sid, data.rid, converse_core_converse.connection.onConnectStatusChanged);
        } else {
          xhr.onerror();
        }
      };

      xhr.onerror = function () {
        delete converse_core_converse.connection;
        /**
         * Triggered when fetching prebind tokens failed
         * @event _converse#noResumeableBOSHSession
         * @type { _converse }
         * @example _converse.api.listen.on('noResumeableBOSHSession', _converse => { ... });
         */

        converse_core_api.trigger('noResumeableBOSHSession', converse_core_converse);
      };

      xhr.send();
    };

    converse_core_converse.restoreBOSHSession = async function () {
      const jid = (await initBOSHSession()).get('jid');

      if (jid && converse_core_converse.connection._proto instanceof converse_bosh_Strophe.Bosh) {
        try {
          converse_core_converse.connection.restore(jid, converse_core_converse.connection.onConnectStatusChanged);

          return true;
        } catch (e) {
          !converse_core_converse.isTestEnv() && headless_log.warn("Could not restore session for jid: " + jid + " Error message: " + e.message);
          return false;
        }
      }

      return false;
    };
    /************************ BEGIN Event Handlers ************************/


    converse_core_api.listen.on('clearSession', () => {
      if (converse_core_converse.bosh_session === undefined) {
        // Remove manually, even if we don't have the corresponding
        // model, to avoid trying to reconnect to a stale BOSH session
        const id = BOSH_SESSION_ID;
        sessionStorage.removeItem(id);
        sessionStorage.removeItem(`${id}-${id}`);
      } else {
        converse_core_converse.bosh_session.destroy();

        delete converse_core_converse.bosh_session;
      }
    });
    converse_core_api.listen.on('setUserJID', () => {
      if (converse_core_converse.bosh_session !== undefined) {
        converse_core_converse.bosh_session.save({
          'jid': converse_core_converse.jid
        });
      }
    });
    converse_core_api.listen.on('addClientFeatures', () => converse_core_api.disco.own.features.add(converse_bosh_Strophe.NS.BOSH));
    /************************ END Event Handlers ************************/

    /************************ BEGIN API ************************/

    Object.assign(converse_core_api, {
      /**
       * This namespace lets you access the BOSH tokens
       *
       * @namespace api.tokens
       * @memberOf api
       */
      tokens: {
        /**
         * @method api.tokens.get
         * @param {string} [id] The type of token to return ('rid' or 'sid').
         * @returns 'string' A token, either the RID or SID token depending on what's asked for.
         * @example _converse.api.tokens.get('rid');
         */
        get(id) {
          if (converse_core_converse.connection === undefined) {
            return null;
          }

          if (id.toLowerCase() === 'rid') {
            return converse_core_converse.connection.rid || converse_core_converse.connection._proto.rid;
          } else if (id.toLowerCase() === 'sid') {
            return converse_core_converse.connection.sid || converse_core_converse.connection._proto.sid;
          }
        }

      }
    });
    /************************ end api ************************/
  }

});
// EXTERNAL MODULE: ./node_modules/strophe.js/src/sha1.js
var sha1 = __webpack_require__(6);

// CONCATENATED MODULE: ./src/headless/converse-caps.js
/**
 * @module converse-caps
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */


const {
  Strophe: converse_caps_Strophe,
  $build: converse_caps_$build
} = converse.env;
converse_caps_Strophe.addNamespace('CAPS', "http://jabber.org/protocol/caps");

function propertySort(array, property) {
  return array.sort((a, b) => {
    return a[property] > b[property] ? -1 : 1;
  });
}

function generateVerificationString(_converse) {
  const identities = _converse.api.disco.own.identities.get();

  const features = _converse.api.disco.own.features.get();

  if (identities.length > 1) {
    propertySort(identities, "category");
    propertySort(identities, "type");
    propertySort(identities, "lang");
  }

  let S = identities.reduce((result, id) => {
    var _id$lang;

    return `${result}${id.category}/${id.type}/${(_id$lang = id === null || id === void 0 ? void 0 : id.lang) !== null && _id$lang !== void 0 ? _id$lang : ''}/${id.name}<`;
  }, "");
  features.sort();
  S = features.reduce((result, feature) => `${result}${feature}<`, S);
  return sha1["a" /* default */].b64_sha1(S);
}

function createCapsNode(_converse) {
  return converse_caps_$build("c", {
    'xmlns': converse_caps_Strophe.NS.CAPS,
    'hash': "sha-1",
    'node': "https://conversejs.org",
    'ver': generateVerificationString(_converse)
  }).nodeTree;
}

converse.plugins.add('converse-caps', {
  overrides: {
    // Overrides mentioned here will be picked up by converse.js's
    // plugin architecture they will replace existing methods on the
    // relevant objects or classes.
    XMPPStatus: {
      constructPresence() {
        const presence = this.__super__.constructPresence.apply(this, arguments);

        presence.root().cnode(createCapsNode(this.__super__._converse));
        return presence;
      }

    }
  }
});
// CONCATENATED MODULE: ./src/headless/converse-carbons.js
/**
 * @module converse-carbons
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description Implements support for XEP-0280 Message Carbons
 */



/* Ask the XMPP server to enable Message Carbons
 * See XEP-0280 https://xmpp.org/extensions/xep-0280.html#enabling
 */

function enableCarbons(reconnecting) {
  var _converse$session2;

  if (reconnecting) {
    var _converse$session;

    (_converse$session = converse_core_converse.session) === null || _converse$session === void 0 ? void 0 : _converse$session.set({
      'carbons_enabled': false
    });
  }

  if (!converse_core_api.settings.get("message_carbons") || (_converse$session2 = converse_core_converse.session) !== null && _converse$session2 !== void 0 && _converse$session2.get('carbons_enabled')) {
    return;
  }

  const carbons_iq = new strophe["e" /* Strophe */].Builder('iq', {
    'from': converse_core_converse.connection.jid,
    'id': 'enablecarbons',
    'type': 'set'
  }).c('enable', {
    xmlns: strophe["e" /* Strophe */].NS.CARBONS
  });

  converse_core_converse.connection.addHandler(iq => {
    if (iq.querySelectorAll('error').length > 0) {
      headless_log.warn('An error occurred while trying to enable message carbons.');
    } else {
      converse_core_converse.session.set({
        'carbons_enabled': true
      });

      headless_log.debug('Message carbons have been enabled.');
    }

    converse_core_converse.session.save(); // Gather multiple sets into one save

  }, null, "iq", null, "enablecarbons");

  converse_core_converse.connection.send(carbons_iq);
}

converse.plugins.add('converse-carbons', {
  initialize() {
    converse_core_api.settings.extend({
      message_carbons: true
    });
    converse_core_api.listen.on('afterResourceBinding', enableCarbons);
  }

});
// CONCATENATED MODULE: ./src/headless/converse-chatboxes.js
/**
 * @module converse-chatboxes
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */




const {
  Strophe: converse_chatboxes_Strophe
} = converse.env;
converse_chatboxes_Strophe.addNamespace('MESSAGE_CORRECT', 'urn:xmpp:message-correct:0');
converse_chatboxes_Strophe.addNamespace('RECEIPTS', 'urn:xmpp:receipts');
converse_chatboxes_Strophe.addNamespace('REFERENCE', 'urn:xmpp:reference:0');
converse_chatboxes_Strophe.addNamespace('MARKERS', 'urn:xmpp:chat-markers:0');
converse.plugins.add('converse-chatboxes', {
  dependencies: ["converse-emoji", "converse-roster", "converse-vcard"],

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    converse_core_api.promises.add(['chatBoxesFetched', 'chatBoxesInitialized', 'privateChatsAutoJoined']);
    converse_core_converse.ChatBoxes = Collection.extend({
      comparator: 'time_opened',

      model(attrs, options) {
        return new converse_core_converse.ChatBox(attrs, options);
      },

      onChatBoxesFetched(collection) {
        collection.filter(c => !c.isValid()).forEach(c => c.destroy());
        /**
         * Triggered once all chat boxes have been recreated from the browser cache
         * @event _converse#chatBoxesFetched
         * @type { object }
         * @property { _converse.ChatBox | _converse.ChatRoom } chatbox
         * @property { XMLElement } stanza
         * @example _converse.api.listen.on('chatBoxesFetched', obj => { ... });
         * @example _converse.api.waitUntil('chatBoxesFetched').then(() => { ... });
         */

        converse_core_api.trigger('chatBoxesFetched');
      },

      onConnected(reconnecting) {
        if (reconnecting) {
          return;
        }

        this.browserStorage = converse_core_converse.createStore(`converse.chatboxes-${converse_core_converse.bare_jid}`);
        this.fetch({
          'add': true,
          'success': c => this.onChatBoxesFetched(c)
        });
      }

    });

    async function createChatBox(jid, attrs, Model) {
      jid = converse_chatboxes_Strophe.getBareJidFromJid(jid.toLowerCase());
      Object.assign(attrs, {
        'jid': jid,
        'id': jid
      });
      let chatbox;

      try {
        chatbox = new Model(attrs, {
          'collection': converse_core_converse.chatboxes
        });
      } catch (e) {
        headless_log.error(e);
        return null;
      }

      await chatbox.initialized;

      if (!chatbox.isValid()) {
        chatbox.destroy();
        return null;
      }

      converse_core_converse.chatboxes.add(chatbox);

      return chatbox;
    }
    /************************ BEGIN Event Handlers ************************/


    converse_core_api.listen.on('addClientFeatures', () => {
      converse_core_api.disco.own.features.add(converse_chatboxes_Strophe.NS.MESSAGE_CORRECT);
      converse_core_api.disco.own.features.add(converse_chatboxes_Strophe.NS.HTTPUPLOAD);
      converse_core_api.disco.own.features.add(converse_chatboxes_Strophe.NS.OUTOFBAND);
    });
    converse_core_api.listen.on('pluginsInitialized', () => {
      converse_core_converse.chatboxes = new converse_core_converse.ChatBoxes();
      /**
       * Triggered once the _converse.ChatBoxes collection has been initialized.
       * @event _converse#chatBoxesInitialized
       * @example _converse.api.listen.on('chatBoxesInitialized', () => { ... });
       * @example _converse.api.waitUntil('chatBoxesInitialized').then(() => { ... });
       */

      converse_core_api.trigger('chatBoxesInitialized');
    });
    converse_core_api.listen.on('presencesInitialized', reconnecting => converse_core_converse.chatboxes.onConnected(reconnecting));
    converse_core_api.listen.on('reconnected', () => converse_core_converse.chatboxes.forEach(m => m.onReconnection()));
    /************************ END Event Handlers ************************/

    /************************ BEGIN API ************************/

    Object.assign(converse_core_api, {
      /**
       * The "chatboxes" namespace.
       *
       * @namespace api.chatboxes
       * @memberOf api
       */
      chatboxes: {
        /**
         * @method api.chats.create
         * @param { String|String[] } jids - A JID or array of JIDs
         * @param { Object } [attrs] An object containing configuration attributes
         * @param { Model } model - The type of chatbox that should be created
         */
        async create(jids = [], attrs = {}, model) {
          await converse_core_api.waitUntil('chatBoxesFetched');

          if (typeof jids === 'string') {
            return createChatBox(jids, attrs, model);
          } else {
            return Promise.all(jids.map(jid => createChatBox(jid, attrs, model)));
          }
        },

        /**
         * @method api.chats.get
         * @param { String|String[] } jids - A JID or array of JIDs
         */
        async get(jids) {
          await converse_core_api.waitUntil('chatBoxesFetched');

          if (jids === undefined) {
            return converse_core_converse.chatboxes.models;
          } else if (typeof jids === 'string') {
            return converse_core_converse.chatboxes.get(jids.toLowerCase());
          } else {
            jids = jids.map(j => j.toLowerCase());
            return converse_core_converse.chatboxes.models.filter(m => jids.includes(m.get('jid')));
          }
        }

      }
    });
    /************************ END API ************************/
  }

});
// CONCATENATED MODULE: ./src/headless/converse-headlines.js
/**
 * @module converse-headlines
 * @copyright 2020, the Converse.js contributors
 * @description XEP-0045 Multi-User Chat Views
 */


converse.plugins.add('converse-headlines', {
  /* Plugin dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin.
   *
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found. By default it's
   * false, which means these plugins are only loaded opportunistically.
   *
   * NB: These plugins need to have already been loaded via require.js.
   */
  dependencies: ["converse-chat"],
  overrides: {
    // Overrides mentioned here will be picked up by converse.js's
    // plugin architecture they will replace existing methods on the
    // relevant objects or classes.
    //
    // New functions which don't exist yet can also be added.
    ChatBoxes: {
      model(attrs, options) {
        const {
          _converse
        } = this.__super__;

        if (attrs.type == _converse.HEADLINES_TYPE) {
          return new _converse.HeadlinesBox(attrs, options);
        } else {
          return this.__super__.model.apply(this, arguments);
        }
      }

    }
  },

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */

    /**
     * Shows headline messages
     * @class
     * @namespace _converse.HeadlinesBox
     * @memberOf _converse
     */
    converse_core_converse.HeadlinesBox = converse_core_converse.ChatBox.extend({
      defaults() {
        return {
          'bookmarked': false,
          'hidden': ['mobile', 'fullscreen'].includes(converse_core_api.settings.get("view_mode")),
          'message_type': 'headline',
          'num_unread': 0,
          'time_opened': this.get('time_opened') || new Date().getTime(),
          'type': converse_core_converse.HEADLINES_TYPE
        };
      },

      async initialize() {
        this.set({
          'box_id': `box-${this.get('jid')}`
        });
        this.initMessages();
        await this.fetchMessages();
        /**
         * Triggered once a {@link _converse.HeadlinesBox} has been created and initialized.
         * @event _converse#headlinesBoxInitialized
         * @type { _converse.HeadlinesBox }
         * @example _converse.api.listen.on('headlinesBoxInitialized', model => { ... });
         */

        converse_core_api.trigger('headlinesBoxInitialized', this);
      }

    });

    async function onHeadlineMessage(stanza) {
      // Handler method for all incoming messages of type "headline".
      if (utils_stanza.isHeadline(stanza) || utils_stanza.isServerMessage(stanza)) {
        const from_jid = stanza.getAttribute('from');

        if (from_jid.includes('@') && !converse_core_converse.roster.get(from_jid) && !converse_core_api.settings.get("allow_non_roster_messaging")) {
          return;
        }

        if (stanza.querySelector('body') === null) {
          // Avoid creating a chat box if we have nothing to show inside it.
          return;
        }

        const chatbox = converse_core_converse.chatboxes.create({
          'id': from_jid,
          'jid': from_jid,
          'type': converse_core_converse.HEADLINES_TYPE,
          'from': from_jid
        });

        const attrs = await utils_stanza.parseMessage(stanza, converse_core_converse);
        await chatbox.createMessage(attrs);
        converse_core_api.trigger('message', {
          chatbox,
          stanza,
          attrs
        });
      }
    }
    /************************ BEGIN Event Handlers ************************/


    function registerHeadlineHandler() {
      converse_core_converse.connection.addHandler(message => onHeadlineMessage(message) || true, null, 'message');
    }

    converse_core_api.listen.on('connected', registerHeadlineHandler);
    converse_core_api.listen.on('reconnected', registerHeadlineHandler);
    /************************ END Event Handlers ************************/

    /************************ BEGIN API ************************/

    Object.assign(converse_core_api, {
      /**
       * The "headlines" namespace, which is used for headline-channels
       * which are read-only channels containing messages of type
       * "headline".
       *
       * @namespace api.headlines
       * @memberOf api
       */
      headlines: {
        /**
         * Retrieves a headline-channel or all headline-channels.
         *
         * @method api.headlines.get
         * @param {String|String[]} jids - e.g. 'buddy@example.com' or ['buddy1@example.com', 'buddy2@example.com']
         * @param {Object} [attrs] - Attributes to be set on the _converse.ChatBox model.
         * @param {Boolean} [create=false] - Whether the chat should be created if it's not found.
         * @returns { Promise<_converse.HeadlinesBox> }
         */
        async get(jids, attrs = {}, create = false) {
          async function _get(jid) {
            let model = await converse_core_api.chatboxes.get(jid);

            if (!model && create) {
              model = await converse_core_api.chatboxes.create(jid, attrs, converse_core_converse.HeadlinesBox);
            } else {
              model = model && model.get('type') === converse_core_converse.HEADLINES_TYPE ? model : null;

              if (model && Object.keys(attrs).length) {
                model.save(attrs);
              }
            }

            return model;
          }

          if (jids === undefined) {
            const chats = await converse_core_api.chatboxes.get();
            return chats.filter(c => c.get('type') === converse_core_converse.HEADLINES_TYPE);
          } else if (typeof jids === 'string') {
            return _get(jids);
          }

          return Promise.all(jids.map(jid => _get(jid)));
        }

      }
    });
    /************************ END API ************************/
  }

});
// CONCATENATED MODULE: ./src/headless/converse-rsm.js
/**
 * @module converse-rsm
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description XEP-0059 Result Set Management
 *   Some code taken from the Strophe RSM plugin, licensed under the MIT License
 *   Copyright 2006-2017 Strophe (https://github.com/strophe/strophejs)
 */


const {
  Strophe: converse_rsm_Strophe,
  $build: converse_rsm_$build
} = converse.env;
converse_rsm_Strophe.addNamespace('RSM', 'http://jabber.org/protocol/rsm');
/**
 * @typedef { Object } RSMQueryParameters
 * [XEP-0059 RSM](https://xmpp.org/extensions/xep-0059.html) Attributes that can be used to filter query results
 * @property { String } [after] - The XEP-0359 stanza ID of a message after which messages should be returned. Implies forward paging.
 * @property { String } [before] - The XEP-0359 stanza ID of a message before which messages should be returned. Implies backward paging.
 * @property { Integer } [index=0] - The index of the results page to return.
 * @property { Integer } [max] - The maximum number of items to return.
 */

const RSM_QUERY_PARAMETERS = ['after', 'before', 'index', 'max'];

const converse_rsm_toNumber = v => Number(v);

const converse_rsm_toString = v => v.toString();

const RSM_TYPES = {
  'after': converse_rsm_toString,
  'before': converse_rsm_toString,
  'count': converse_rsm_toNumber,
  'first': converse_rsm_toString,
  'index': converse_rsm_toNumber,
  'last': converse_rsm_toString,
  'max': converse_rsm_toNumber
};

const isUndefined = x => typeof x === 'undefined'; // This array contains both query attributes and response attributes


const RSM_ATTRIBUTES = Object.keys(RSM_TYPES);
/**
 * Instances of this class are used to page through query results according to XEP-0059 Result Set Management
 * @class RSM
 */

class converse_rsm_RSM {
  static getQueryParameters(options = {}) {
    return lodash_es_pick(options, RSM_QUERY_PARAMETERS);
  }

  static parseXMLResult(set) {
    const result = {};

    for (var i = 0; i < RSM_ATTRIBUTES.length; i++) {
      const attr = RSM_ATTRIBUTES[i];
      const elem = set.getElementsByTagName(attr)[0];

      if (!isUndefined(elem) && elem !== null) {
        result[attr] = RSM_TYPES[attr](converse_rsm_Strophe.getText(elem));

        if (attr == 'first') {
          result.index = RSM_TYPES['index'](elem.getAttribute('index'));
        }
      }
    }

    return result;
  }
  /**
   * Create a new RSM instance
   * @param { Object } options - Configuration options
   * @constructor
   */


  constructor(options = {}) {
    this.query = converse_rsm_RSM.getQueryParameters(options);
    this.result = options.xml ? converse_rsm_RSM.parseXMLResult(options.xml) : {};
  }
  /**
   * Returns a `<set>` XML element that confirms to XEP-0059 Result Set Management.
   * The element is constructed based on the { @link module:converse-rsm~RSMQueryParameters }
   * that are set on this RSM instance.
   * @returns { XMLElement }
   */


  toXML() {
    const xml = converse_rsm_$build('set', {
      xmlns: converse_rsm_Strophe.NS.RSM
    });

    const reducer = (xml, a) => !isUndefined(this.query[a]) ? xml.c(a).t((this.query[a] || '').toString()).up() : xml;

    return RSM_QUERY_PARAMETERS.reduce(reducer, xml).tree();
  }

  next(max, before) {
    const options = Object.assign({}, this.query, {
      after: this.result.last,
      before,
      max
    });
    return new converse_rsm_RSM(options);
  }

  previous(max, after) {
    const options = Object.assign({}, this.query, {
      after,
      before: this.result.first,
      max
    });
    return new converse_rsm_RSM(options);
  }

}
converse_core_converse.RSM_ATTRIBUTES = RSM_ATTRIBUTES;
converse_core_converse.RSM = converse_rsm_RSM;
// CONCATENATED MODULE: ./src/headless/converse-mam.js
/**
 * @module converse-mam
 * @description XEP-0313 Message Archive Management
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */







const {
  Strophe: converse_mam_Strophe,
  $iq: converse_mam_$iq,
  dayjs
} = converse.env;
const {
  NS: converse_mam_NS
} = converse_mam_Strophe;
const converse_mam_u = converse.env.utils;
/**
 * The MUC utils object. Contains utility functions related to multi-user chat.
 * @mixin MAMEnabledChat
 */

const MAMEnabledChat = {
  /**
   * Fetches messages that might have been archived *after*
   * the last archived message in our local cache.
   * @private
   */
  fetchNewestMessages() {
    if (this.disable_mam) {
      return;
    }

    const most_recent_msg = this.getMostRecentMessage(); // if clear_messages_on_reconnection is true, than any recent messages
    // must have been received *after* connection and we instead must query
    // for earlier messages

    if (most_recent_msg && !converse_core_api.settings.get('clear_messages_on_reconnection')) {
      const stanza_id = most_recent_msg.get(`stanza_id ${this.get('jid')}`);

      if (stanza_id) {
        this.fetchArchivedMessages({
          'after': stanza_id
        }, 'forwards');
      } else {
        this.fetchArchivedMessages({
          'start': most_recent_msg.get('time')
        }, 'forwards');
      }
    } else {
      this.fetchArchivedMessages({
        'before': ''
      });
    }
  },

  async handleMAMResult(result, query, options, page_direction) {
    await converse_core_api.emojis.initialize();

    const is_muc = this.get('type') === converse_core_converse.CHATROOMS_TYPE;

    result.messages = result.messages.map(s => is_muc ? utils_stanza.parseMUCMessage(s, this, converse_core_converse) : utils_stanza.parseMessage(s, converse_core_converse));
    /**
     * Synchronous event which allows listeners to first do some
     * work based on the MAM result before calling the handlers here.
     * @event _converse#MAMResult
     */

    const data = {
      query,
      'chatbox': this,
      'messages': result.messages
    };
    await converse_core_api.trigger('MAMResult', data, {
      'synchronous': true
    });
    result.messages.forEach(m => this.queueMessage(m));

    if (result.error) {
      const event_id = result.error.retry_event_id = converse_mam_u.getUniqueId();
      converse_core_api.listen.once(event_id, () => this.fetchArchivedMessages(options, page_direction));
      this.createMessageFromError(result.error);
    }
  },

  /**
   * Fetch XEP-0313 archived messages based on the passed in criteria.
   * @private
   * @param { Object } options
   * @param { integer } [options.max] - The maximum number of items to return.
   *  Defaults to "archived_messages_page_size"
   * @param { string } [options.after] - The XEP-0359 stanza ID of a message
   *  after which messages should be returned. Implies forward paging.
   * @param { string } [options.before] - The XEP-0359 stanza ID of a message
   *  before which messages should be returned. Implies backward paging.
   * @param { string } [options.end] - A date string in ISO-8601 format,
   *  before which messages should be returned. Implies backward paging.
   * @param { string } [options.start] - A date string in ISO-8601 format,
   *  after which messages should be returned. Implies forward paging.
   * @param { string } [options.with] - The JID of the entity with
   *  which messages were exchanged.
   * @param { boolean } [options.groupchat] - True if archive in groupchat.
   * @param { ('forwards'|'backwards')} [page_direction] - Determines whether this function should
   *  recursively page through the entire result set if a limited number of results were returned.
   */
  async fetchArchivedMessages(options = {}, page_direction) {
    if (this.disable_mam) {
      return;
    }

    const is_muc = this.get('type') === converse_core_converse.CHATROOMS_TYPE;

    const mam_jid = is_muc ? this.get('jid') : converse_core_converse.bare_jid;

    if (!(await converse_core_api.disco.supports(converse_mam_NS.MAM, mam_jid))) {
      return;
    }

    const max = converse_core_api.settings.get('archived_messages_page_size');
    const query = Object.assign({
      'groupchat': is_muc,
      'max': max,
      'with': this.get('jid')
    }, options);
    const result = await converse_core_api.archive.query(query);
    await this.handleMAMResult(result, query, options, page_direction);

    if (page_direction && result.rsm && !result.complete) {
      if (page_direction === 'forwards') {
        options = result.rsm.next(max, options.before).query;
      } else if (page_direction === 'backwards') {
        options = result.rsm.previous(max, options.after).query;
      }

      return this.fetchArchivedMessages(options, page_direction);
    } else {// TODO: Add a special kind of message which will
      // render as a link to fetch further messages, either
      // to fetch older messages or to fill in a gap.
    }
  }

};
converse.plugins.add('converse-mam', {
  dependencies: ['converse-disco', 'converse-muc'],

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by Converse.js's plugin machinery.
     */
    converse_core_api.settings.extend({
      archived_messages_page_size: '50',
      message_archiving: undefined,
      // Supported values are 'always', 'never', 'roster' (https://xmpp.org/extensions/xep-0313.html#prefs)
      message_archiving_timeout: 20000 // Time (in milliseconds) to wait before aborting MAM request

    });
    Object.assign(converse_core_converse.ChatBox.prototype, MAMEnabledChat);

    converse_core_converse.onMAMError = function (iq) {
      if (iq !== null && iq !== void 0 && iq.querySelectorAll('feature-not-implemented').length) {
        headless_log.warn(`Message Archive Management (XEP-0313) not supported by ${iq.getAttribute('from')}`);
      } else {
        headless_log.error(`Error while trying to set archiving preferences for ${iq.getAttribute('from')}.`);
        headless_log.error(iq);
      }
    };

    converse_core_converse.onMAMPreferences = function (iq, feature) {
      /* Handle returned IQ stanza containing Message Archive
       * Management (XEP-0313) preferences.
       *
       * XXX: For now we only handle the global default preference.
       * The XEP also provides for per-JID preferences, which is
       * currently not supported in converse.js.
       *
       * Per JID preferences will be set in chat boxes, so it'll
       * probbaly be handled elsewhere in any case.
       */
      const preference = sizzle_default()(`prefs[xmlns="${converse_mam_NS.MAM}"]`, iq).pop();
      const default_pref = preference.getAttribute('default');

      if (default_pref !== converse_core_api.settings.get('message_archiving')) {
        const stanza = converse_mam_$iq({
          'type': 'set'
        }).c('prefs', {
          'xmlns': converse_mam_NS.MAM,
          'default': converse_core_api.settings.get('message_archiving')
        });
        Array.from(preference.children).forEach(child => stanza.cnode(child).up()); // XXX: Strictly speaking, the server should respond with the updated prefs
        // (see example 18: https://xmpp.org/extensions/xep-0313.html#config)
        // but Prosody doesn't do this, so we don't rely on it.

        converse_core_api.sendIQ(stanza).then(() => feature.save({
          'preferences': {
            'default': converse_core_api.settings.get('message_archiving')
          }
        })).catch(converse_core_converse.onMAMError);
      } else {
        feature.save({
          'preferences': {
            'default': converse_core_api.settings.get('message_archiving')
          }
        });
      }
    };

    function getMAMPrefsFromFeature(feature) {
      const prefs = feature.get('preferences') || {};

      if (feature.get('var') !== converse_mam_NS.MAM || converse_core_api.settings.get('message_archiving') === undefined) {
        return;
      }

      if (prefs['default'] !== converse_core_api.settings.get('message_archiving')) {
        converse_core_api.sendIQ(converse_mam_$iq({
          'type': 'get'
        }).c('prefs', {
          'xmlns': converse_mam_NS.MAM
        })).then(iq => converse_core_converse.onMAMPreferences(iq, feature)).catch(converse_core_converse.onMAMError);
      }
    }

    function preMUCJoinMAMFetch(room) {
      if (!converse_core_api.settings.get('muc_show_logs_before_join') || !room.features.get('mam_enabled') || room.get('prejoin_mam_fetched')) {
        return;
      }

      room.fetchNewestMessages();
      room.save({
        'prejoin_mam_fetched': true
      });
    }
    /************************ BEGIN Event Handlers ************************/


    converse_core_api.listen.on('addClientFeatures', () => converse_core_api.disco.own.features.add(converse_mam_NS.MAM));
    converse_core_api.listen.on('serviceDiscovered', getMAMPrefsFromFeature);
    converse_core_api.listen.on('chatRoomViewInitialized', view => {
      if (converse_core_api.settings.get('muc_show_logs_before_join')) {
        preMUCJoinMAMFetch(view.model); // If we want to show MAM logs before entering the MUC, we need
        // to be informed once it's clear that this MUC supports MAM.

        view.model.features.on('change:mam_enabled', () => preMUCJoinMAMFetch(view.model));
      }
    });
    converse_core_api.listen.on('enteredNewRoom', room => room.features.get('mam_enabled') && room.fetchNewestMessages());
    converse_core_api.listen.on('chatReconnected', chat => {
      // XXX: For MUCs, we listen to enteredNewRoom instead
      if (chat.get('type') === converse_core_converse.PRIVATE_CHAT_TYPE) {
        chat.fetchNewestMessages();
      }
    });
    converse_core_api.listen.on('afterMessagesFetched', chat => {
      // XXX: We don't want to query MAM every time this is triggered
      // since it's not necessary when the chat is restored from cache.
      // (given that BOSH or SMACKS will ensure that you get messages
      // sent during the reload).
      // With MUCs we can listen for `enteredNewRoom`.
      if (chat.get('type') === converse_core_converse.PRIVATE_CHAT_TYPE && !converse_core_converse.connection.restored) {
        chat.fetchNewestMessages();
      }
    });
    /************************ END Event Handlers **************************/

    /************************ BEGIN API ************************/

    Object.assign(converse_core_api, {
      /**
       * The [XEP-0313](https://xmpp.org/extensions/xep-0313.html) Message Archive Management API
       *
       * Enables you to query an XMPP server for archived messages.
       *
       * See also the [message-archiving](/docs/html/configuration.html#message-archiving)
       * option in the configuration settings section, which you'll
       * usually want to use in conjunction with this API.
       *
       * @namespace _converse.api.archive
       * @memberOf _converse.api
       */
      archive: {
        /**
         * @typedef { module:converse-rsm~RSMQueryParameters } MAMFilterParameters
         * Filter parameters which can be used to filter a MAM XEP-0313 archive
         * @property { String } [end] - A date string in ISO-8601 format, before which messages should be returned. Implies backward paging.
         * @property { String } [start] - A date string in ISO-8601 format, after which messages should be returned. Implies forward paging.
         * @property { String } [with] - A JID against which to match messages, according to either their `to` or `from` attributes.
         *     An item in a MUC archive matches if the publisher of the item matches the JID.
         *     If `with` is omitted, all messages that match the rest of the query will be returned, regardless of to/from
         *     addresses of each message.
         */

        /**
         * The options that can be passed in to the { @link _converse.api.archive.query } method
         * @typedef { module:converse-mam~MAMFilterParameters } ArchiveQueryOptions
         * @property { Boolean } [groupchat=false] - Whether the MAM archive is for a groupchat.
         */

        /**
         * Query for archived messages.
         *
         * The options parameter can also be an instance of
         * RSM to enable easy querying between results pages.
         *
         * @method _converse.api.archive.query
         * @param { module:converse-mam~ArchiveQueryOptions } options - An object containing query parameters
         * @throws {Error} An error is thrown if the XMPP server responds with an error.
         * @returns { Promise<module:converse-mam~MAMQueryResult> } A promise which resolves
         *     to a { @link module:converse-mam~MAMQueryResult } object.
         *
         * @example
         * // Requesting all archived messages
         * // ================================
         * //
         * // The simplest query that can be made is to simply not pass in any parameters.
         * // Such a query will return all archived messages for the current user.
         *
         * let result;
         * try {
         *     result = await api.archive.query();
         * } catch (e) {
         *     // The query was not successful, perhaps inform the user?
         *     // The IQ stanza returned by the XMPP server is passed in, so that you
         *     // may inspect it and determine what the problem was.
         * }
         * // Do something with the messages, like showing them in your webpage.
         * result.messages.forEach(m => this.showMessage(m));
         *
         * @example
         * // Requesting all archived messages for a particular contact or room
         * // =================================================================
         * //
         * // To query for messages sent between the current user and another user or room,
         * // the query options need to contain the the JID (Jabber ID) of the user or
         * // room under the  `with` key.
         *
         * // For a particular user
         * let result;
         * try {
         *    result = await api.archive.query({'with': 'john@doe.net'});
         * } catch (e) {
         *     // The query was not successful
         * }
         *
         * // For a particular room
         * let result;
         * try {
         *    result = await api.archive.query({'with': 'discuss@conference.doglovers.net', 'groupchat': true});
         * } catch (e) {
         *     // The query was not successful
         * }
         *
         * @example
         * // Requesting all archived messages before or after a certain date
         * // ===============================================================
         * //
         * // The `start` and `end` parameters are used to query for messages
         * // within a certain timeframe. The passed in date values may either be ISO8601
         * // formatted date strings, or JavaScript Date objects.
         *
         *  const options = {
         *      'with': 'john@doe.net',
         *      'start': '2010-06-07T00:00:00Z',
         *      'end': '2010-07-07T13:23:54Z'
         *  };
         * let result;
         * try {
         *    result = await api.archive.query(options);
         * } catch (e) {
         *     // The query was not successful
         * }
         *
         * @example
         * // Limiting the amount of messages returned
         * // ========================================
         * //
         * // The amount of returned messages may be limited with the `max` parameter.
         * // By default, the messages are returned from oldest to newest.
         *
         * // Return maximum 10 archived messages
         * let result;
         * try {
         *     result = await api.archive.query({'with': 'john@doe.net', 'max':10});
         * } catch (e) {
         *     // The query was not successful
         * }
         *
         * @example
         * // Paging forwards through a set of archived messages
         * // ==================================================
         * //
         * // When limiting the amount of messages returned per query, you might want to
         * // repeatedly make a further query to fetch the next batch of messages.
         * //
         * // To simplify this usecase for you, the callback method receives not only an array
         * // with the returned archived messages, but also a special RSM (*Result Set Management*)
         * // object which contains the query parameters you passed in, as well
         * // as two utility methods `next`, and `previous`.
         * //
         * // When you call one of these utility methods on the returned RSM object, and then
         * // pass the result into a new query, you'll receive the next or previous batch of
         * // archived messages. Please note, when calling these methods, pass in an integer
         * // to limit your results.
         *
         * const options = {'with': 'john@doe.net', 'max':10};
         * let result;
         * try {
         *     result = await api.archive.query(options);
         * } catch (e) {
         *     // The query was not successful
         * }
         * // Do something with the messages, like showing them in your webpage.
         * result.messages.forEach(m => this.showMessage(m));
         *
         * while (!result.complete) {
         *     try {
         *         result = await api.archive.query(Object.assign(options, rsm.next(10).query));
         *     } catch (e) {
         *         // The query was not successful
         *     }
         *     // Do something with the messages, like showing them in your webpage.
         *     result.messages.forEach(m => this.showMessage(m));
         * }
         *
         * @example
         * // Paging backwards through a set of archived messages
         * // ===================================================
         * //
         * // To page backwards through the archive, you need to know the UID of the message
         * // which you'd like to page backwards from and then pass that as value for the
         * // `before` parameter. If you simply want to page backwards from the most recent
         * // message, pass in the `before` parameter with an empty string value `''`.
         *
         * let result;
         * const options = {'before': '', 'max':5};
         * try {
         *     result = await api.archive.query(options);
         * } catch (e) {
         *     // The query was not successful
         * }
         * // Do something with the messages, like showing them in your webpage.
         * result.messages.forEach(m => this.showMessage(m));
         *
         * // Now we query again, to get the previous batch.
         * try {
         *      result = await api.archive.query(Object.assign(options, rsm.previous(5).query));
         * } catch (e) {
         *     // The query was not successful
         * }
         * // Do something with the messages, like showing them in your webpage.
         * result.messages.forEach(m => this.showMessage(m));
         *
         */
        async query(options) {
          if (!converse_core_api.connection.connected()) {
            throw new Error('Can\'t call `api.archive.query` before having established an XMPP session');
          }

          const attrs = {
            'type': 'set'
          };

          if (options && options.groupchat) {
            if (!options['with']) {
              throw new Error('You need to specify a "with" value containing ' + 'the chat room JID, when querying groupchat messages.');
            }

            attrs.to = options['with'];
          }

          const jid = attrs.to || converse_core_converse.bare_jid;
          const supported = await converse_core_api.disco.supports(converse_mam_NS.MAM, jid);

          if (!supported) {
            headless_log.warn(`Did not fetch MAM archive for ${jid} because it doesn't support ${converse_mam_NS.MAM}`);
            return {
              'messages': []
            };
          }

          const queryid = converse_mam_u.getUniqueId();
          const stanza = converse_mam_$iq(attrs).c('query', {
            'xmlns': converse_mam_NS.MAM,
            'queryid': queryid
          });

          if (options) {
            stanza.c('x', {
              'xmlns': converse_mam_NS.XFORM,
              'type': 'submit'
            }).c('field', {
              'var': 'FORM_TYPE',
              'type': 'hidden'
            }).c('value').t(converse_mam_NS.MAM).up().up();

            if (options['with'] && !options.groupchat) {
              stanza.c('field', {
                'var': 'with'
              }).c('value').t(options['with']).up().up();
            }

            ['start', 'end'].forEach(t => {
              if (options[t]) {
                const date = dayjs(options[t]);

                if (date.isValid()) {
                  stanza.c('field', {
                    'var': t
                  }).c('value').t(date.toISOString()).up().up();
                } else {
                  throw new TypeError(`archive.query: invalid date provided for: ${t}`);
                }
              }
            });
            stanza.up();
            const rsm = new converse_rsm_RSM(options);

            if (Object.keys(rsm.query).length) {
              stanza.cnode(rsm.toXML());
            }
          }

          const messages = [];

          const message_handler = converse_core_converse.connection.addHandler(stanza => {
            const result = sizzle_default()(`message > result[xmlns="${converse_mam_NS.MAM}"]`, stanza).pop();

            if (result === undefined || result.getAttribute('queryid') !== queryid) {
              return true;
            }

            const from = stanza.getAttribute('from') || converse_core_converse.bare_jid;

            if (options.groupchat) {
              if (from !== options['with']) {
                headless_log.warn(`Ignoring alleged groupchat MAM message from ${stanza.getAttribute('from')}`);
                return true;
              }
            } else if (from !== converse_core_converse.bare_jid) {
              headless_log.warn(`Ignoring alleged MAM message from ${stanza.getAttribute('from')}`);
              return true;
            }

            messages.push(stanza);
            return true;
          }, converse_mam_NS.MAM);

          let error;
          const iq_result = await converse_core_api.sendIQ(stanza, converse_core_api.settings.get('message_archiving_timeout'), false);

          if (iq_result === null) {
            const {
              __
            } = converse_core_converse;

            const err_msg = __("Timeout while trying to fetch archived messages.");

            headless_log.error(err_msg);
            error = new converse_core_converse.TimeoutError(err_msg);
            return {
              messages,
              error
            };
          } else if (converse_mam_u.isErrorStanza(iq_result)) {
            const {
              __
            } = converse_core_converse;

            const err_msg = __('An error occurred while querying for archived messages.');

            headless_log.error(err_msg);
            headless_log.error(iq_result);
            error = new Error(err_msg);
            return {
              messages,
              error
            };
          }

          converse_core_converse.connection.deleteHandler(message_handler);

          let rsm;
          const fin = iq_result && sizzle_default()(`fin[xmlns="${converse_mam_NS.MAM}"]`, iq_result).pop();
          const complete = (fin === null || fin === void 0 ? void 0 : fin.getAttribute('complete')) === 'true';
          const set = sizzle_default()(`set[xmlns="${converse_mam_NS.RSM}"]`, fin).pop();

          if (set) {
            rsm = new converse_rsm_RSM({ ...options,
              'xml': set
            });
          }
          /**
           * @typedef { Object } MAMQueryResult
           * @property { Array } messages
           * @property { RSM } [rsm] - An instance of { @link RSM }.
           *  You can call `next()` or `previous()` on this instance,
           *  to get the RSM query parameters for the next or previous
           *  page in the result set.
           * @property { Boolean } complete
           * @property { Error } [error]
           */


          return {
            messages,
            rsm,
            complete
          };
        }

      }
    });
    /************************ END API ************************/
  }

});
// CONCATENATED MODULE: ./src/headless/converse-ping.js
/**
 * @module converse-ping
 * @description
 * Converse.js plugin which add support for application-level pings
 * as specified in XEP-0199 XMPP Ping.
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */


const {
  Strophe: converse_ping_Strophe,
  $iq: converse_ping_$iq
} = converse.env;
const converse_ping_u = converse.env.utils;
converse_ping_Strophe.addNamespace('PING', "urn:xmpp:ping");
converse.plugins.add('converse-ping', {
  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    let lastStanzaDate;
    converse_core_api.settings.extend({
      ping_interval: 60 //in seconds

    });

    function pong(ping) {
      lastStanzaDate = new Date();
      const from = ping.getAttribute('from');
      const id = ping.getAttribute('id');
      const iq = converse_ping_$iq({
        type: 'result',
        to: from,
        id: id
      });

      converse_core_converse.connection.sendIQ(iq);

      return true;
    }

    function registerPongHandler() {
      if (converse_core_converse.connection.disco !== undefined) {
        converse_core_api.disco.own.features.add(converse_ping_Strophe.NS.PING);
      }

      return converse_core_converse.connection.addHandler(pong, converse_ping_Strophe.NS.PING, "iq", "get");
    }

    function registerPingHandler() {
      converse_core_converse.connection.addHandler(() => {
        if (converse_core_api.settings.get('ping_interval') > 0) {
          // Handler on each stanza, saves the received date
          // in order to ping only when needed.
          lastStanzaDate = new Date();
          return true;
        }
      });
    }

    setTimeout(() => {
      if (converse_core_api.settings.get('ping_interval') > 0) {
        const now = new Date();

        if (!lastStanzaDate) {
          lastStanzaDate = now;
        }

        if ((now - lastStanzaDate) / 1000 > converse_core_api.settings.get('ping_interval')) {
          return converse_core_api.ping();
        }

        return true;
      }
    }, 1000);
    /************************ BEGIN Event Handlers ************************/

    const onConnected = function () {
      // Wrapper so that we can spy on registerPingHandler in tests
      registerPongHandler();
      registerPingHandler();
    };

    converse_core_api.listen.on('connected', onConnected);
    converse_core_api.listen.on('reconnected', onConnected);

    function onWindowStateChanged(data) {
      if (data.state === 'visible' && converse_core_api.connection.connected()) {
        converse_core_api.ping(null, 5000);
      }
    }

    converse_core_api.listen.on('windowStateChanged', onWindowStateChanged);
    /************************ END Event Handlers ************************/

    /************************ BEGIN API ************************/

    Object.assign(converse_core_api, {
      /**
       * Pings the service represented by the passed in JID by sending an IQ stanza.
       * @private
       * @method api.ping
       * @param { String } [jid] - The JID of the service to ping
       * @param { Integer } [timeout] - The amount of time in
       *  milliseconds to wait for a response. The default is 10000;
       */
      async ping(jid, timeout) {
        // XXX: We could first check here if the server advertised that it supports PING.
        // However, some servers don't advertise while still responding to pings
        //
        // const feature = _converse.disco_entities[_converse.domain].features.findWhere({'var': Strophe.NS.PING});
        lastStanzaDate = new Date();
        jid = jid || converse_ping_Strophe.getDomainFromJid(converse_core_converse.bare_jid);

        if (converse_core_converse.connection) {
          const iq = converse_ping_$iq({
            'type': 'get',
            'to': jid,
            'id': converse_ping_u.getUniqueId('ping')
          }).c('ping', {
            'xmlns': converse_ping_Strophe.NS.PING
          });
          const result = await converse_core_api.sendIQ(iq, timeout || 10000, false);

          if (result === null) {
            headless_log.warn(`Timeout while pinging ${jid}`);

            if (jid === converse_ping_Strophe.getDomainFromJid(converse_core_converse.bare_jid)) {
              converse_core_api.connection.reconnect();
            }
          } else if (converse_ping_u.isErrorStanza(result)) {
            headless_log.error(`Error while pinging ${jid}`);
            headless_log.error(result);
          }

          return true;
        }

        return false;
      }

    });
  }

});
// CONCATENATED MODULE: ./src/headless/converse-pubsub.js
/**
 * @module converse-pubsub
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */



const {
  Strophe: converse_pubsub_Strophe,
  $iq: converse_pubsub_$iq
} = converse.env;
converse_pubsub_Strophe.addNamespace('PUBSUB_ERROR', converse_pubsub_Strophe.NS.PUBSUB + "#errors");
converse.plugins.add('converse-pubsub', {
  dependencies: ["converse-disco"],

  initialize() {
    /************************ BEGIN API ************************/
    // We extend the default converse.js API to add methods specific to MUC groupchats.
    Object.assign(converse_core_converse.api, {
      /**
       * The "pubsub" namespace groups methods relevant to PubSub
       *
       * @namespace _converse.api.pubsub
       * @memberOf _converse.api
       */
      'pubsub': {
        /**
         * Publshes an item to a PubSub node
         *
         * @method _converse.api.pubsub.publish
         * @param {string} jid The JID of the pubsub service where the node resides.
         * @param {string} node The node being published to
         * @param {Strophe.Builder} item The Strophe.Builder representation of the XML element being published
         * @param {object} options An object representing the publisher options
         *      (see https://xmpp.org/extensions/xep-0060.html#publisher-publish-options)
         * @param {boolean} strict_options Indicates whether the publisher
         *      options are a strict requirement or not. If they're NOT
         *      strict, then Converse will publish to the node even if
         *      the publish options precondication cannot be met.
         */
        async 'publish'(jid, node, item, options, strict_options = true) {
          const stanza = converse_pubsub_$iq({
            'from': converse_core_converse.bare_jid,
            'type': 'set',
            'to': jid
          }).c('pubsub', {
            'xmlns': converse_pubsub_Strophe.NS.PUBSUB
          }).c('publish', {
            'node': node
          }).cnode(item.tree()).up().up();

          if (options) {
            jid = jid || converse_core_converse.bare_jid;

            if (await converse_core_api.disco.supports(converse_pubsub_Strophe.NS.PUBSUB + '#publish-options', jid)) {
              stanza.c('publish-options').c('x', {
                'xmlns': converse_pubsub_Strophe.NS.XFORM,
                'type': 'submit'
              }).c('field', {
                'var': 'FORM_TYPE',
                'type': 'hidden'
              }).c('value').t(`${converse_pubsub_Strophe.NS.PUBSUB}#publish-options`).up().up();
              Object.keys(options).forEach(k => stanza.c('field', {
                'var': k
              }).c('value').t(options[k]).up().up());
            } else {
              headless_log.warn(`_converse.api.publish: ${jid} does not support #publish-options, ` + `so we didn't set them even though they were provided.`);
            }
          }

          try {
            await converse_core_api.sendIQ(stanza);
          } catch (iq) {
            if (iq instanceof Element && strict_options && iq.querySelector(`precondition-not-met[xmlns="${converse_pubsub_Strophe.NS.PUBSUB_ERROR}"]`)) {
              // The publish-options precondition couldn't be
              // met. We re-publish but without publish-options.
              const el = stanza.nodeTree;
              el.querySelector('publish-options').outerHTML = '';
              headless_log.warn(`PubSub: Republishing without publish options. ${el.outerHTML}`);
              await converse_core_api.sendIQ(el);
            } else {
              throw iq;
            }
          }
        }

      }
    });
    /************************ END API ************************/
  }

});
// CONCATENATED MODULE: ./node_modules/lodash-es/isNumber.js


/** `Object#toString` result references. */

var isNumber_numberTag = '[object Number]';
/**
 * Checks if `value` is classified as a `Number` primitive or object.
 *
 * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
 * classified as numbers, use the `_.isFinite` method.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a number, else `false`.
 * @example
 *
 * _.isNumber(3);
 * // => true
 *
 * _.isNumber(Number.MIN_VALUE);
 * // => true
 *
 * _.isNumber(Infinity);
 * // => true
 *
 * _.isNumber('3');
 * // => false
 */

function isNumber(value) {
  return typeof value == 'number' || lodash_es_isObjectLike(value) && _baseGetTag(value) == isNumber_numberTag;
}

/* harmony default export */ var lodash_es_isNumber = (isNumber);
// CONCATENATED MODULE: ./node_modules/lodash-es/isNaN.js

/**
 * Checks if `value` is `NaN`.
 *
 * **Note:** This method is based on
 * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
 * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
 * `undefined` and other non-number values.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
 * @example
 *
 * _.isNaN(NaN);
 * // => true
 *
 * _.isNaN(new Number(NaN));
 * // => true
 *
 * isNaN(undefined);
 * // => true
 *
 * _.isNaN(undefined);
 * // => false
 */

function isNaN_isNaN(value) {
  // An `NaN` primitive is the only value that is not equal to itself.
  // Perform the `toStringTag` check first to avoid errors with some
  // ActiveX objects in IE.
  return lodash_es_isNumber(value) && value != +value;
}

/* harmony default export */ var lodash_es_isNaN = (isNaN_isNaN);
// CONCATENATED MODULE: ./src/headless/converse-status.js
/**
 * @module converse-status
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */



const {
  Strophe: converse_status_Strophe,
  $build: converse_status_$build,
  $pres: converse_status_$pres
} = converse.env;
converse.plugins.add('converse-status', {
  initialize() {
    converse_core_api.settings.extend({
      auto_away: 0,
      // Seconds after which user status is set to 'away'
      auto_xa: 0,
      // Seconds after which user status is set to 'xa'
      csi_waiting_time: 0,
      // Support for XEP-0352. Seconds before client is considered idle and CSI is sent out.
      default_state: 'online',
      priority: 0
    });
    converse_core_api.promises.add(['statusInitialized']);
    converse_core_converse.XMPPStatus = model_Model.extend({
      defaults() {
        return {
          "status": converse_core_api.settings.get("default_state")
        };
      },

      initialize() {
        this.on('change', item => {
          if (!lodash_es_isObject(item.changed)) {
            return;
          }

          if ('status' in item.changed || 'status_message' in item.changed) {
            converse_core_api.user.presence.send(this.get('status'), null, this.get('status_message'));
          }
        });
      },

      getNickname() {
        return converse_core_converse.nickname;
      },

      getFullname() {
        // Gets overridden in converse-vcard
        return '';
      },

      constructPresence(type, to = null, status_message) {
        type = typeof type === 'string' ? type : this.get('status') || converse_core_api.settings.get("default_state");
        status_message = typeof status_message === 'string' ? status_message : this.get('status_message');
        let presence;
        const attrs = {
          to
        };

        if (type === 'unavailable' || type === 'probe' || type === 'error' || type === 'unsubscribe' || type === 'unsubscribed' || type === 'subscribe' || type === 'subscribed') {
          attrs['type'] = type;
          presence = converse_status_$pres(attrs);
        } else if (type === 'offline') {
          attrs['type'] = 'unavailable';
          presence = converse_status_$pres(attrs);
        } else if (type === 'online') {
          presence = converse_status_$pres(attrs);
        } else {
          presence = converse_status_$pres(attrs).c('show').t(type).up();
        }

        if (status_message) {
          presence.c('status').t(status_message).up();
        }

        const priority = converse_core_api.settings.get("priority");
        presence.c('priority').t(lodash_es_isNaN(Number(priority)) ? 0 : priority).up();

        if (converse_core_converse.idle) {
          const idle_since = new Date();
          idle_since.setSeconds(idle_since.getSeconds() - converse_core_converse.idle_seconds);
          presence.c('idle', {
            xmlns: converse_status_Strophe.NS.IDLE,
            since: idle_since.toISOString()
          });
        }

        return presence;
      }

    });
    /**
     * Send out a Client State Indication (XEP-0352)
     * @private
     * @method sendCSI
     * @memberOf _converse
     * @param { String } stat - The user's chat status
     */

    converse_core_converse.sendCSI = function (stat) {
      converse_core_api.send(converse_status_$build(stat, {
        xmlns: converse_status_Strophe.NS.CSI
      }));
      converse_core_converse.inactive = stat === converse_core_converse.INACTIVE ? true : false;
    };

    converse_core_converse.onUserActivity = function () {
      var _converse$connection;

      /* Resets counters and flags relating to CSI and auto_away/auto_xa */
      if (converse_core_converse.idle_seconds > 0) {
        converse_core_converse.idle_seconds = 0;
      }

      if (!((_converse$connection = converse_core_converse.connection) !== null && _converse$connection !== void 0 && _converse$connection.authenticated)) {
        // We can't send out any stanzas when there's no authenticated connection.
        // This can happen when the connection reconnects.
        return;
      }

      if (converse_core_converse.inactive) {
        converse_core_converse.sendCSI(converse_core_converse.ACTIVE);
      }

      if (converse_core_converse.idle) {
        converse_core_converse.idle = false;
        converse_core_api.user.presence.send();
      }

      if (converse_core_converse.auto_changed_status === true) {
        converse_core_converse.auto_changed_status = false; // XXX: we should really remember the original state here, and
        // then set it back to that...

        converse_core_converse.xmppstatus.set('status', converse_core_api.settings.get("default_state"));
      }
    };

    converse_core_converse.onEverySecond = function () {
      var _converse$connection2;

      /* An interval handler running every second.
       * Used for CSI and the auto_away and auto_xa features.
       */
      if (!((_converse$connection2 = converse_core_converse.connection) !== null && _converse$connection2 !== void 0 && _converse$connection2.authenticated)) {
        // We can't send out any stanzas when there's no authenticated connection.
        // This can happen when the connection reconnects.
        return;
      }

      const stat = converse_core_converse.xmppstatus.get('status');

      converse_core_converse.idle_seconds++;

      if (converse_core_api.settings.get("csi_waiting_time") > 0 && converse_core_converse.idle_seconds > converse_core_api.settings.get("csi_waiting_time") && !converse_core_converse.inactive) {
        converse_core_converse.sendCSI(converse_core_converse.INACTIVE);
      }

      if (converse_core_api.settings.get("idle_presence_timeout") > 0 && converse_core_converse.idle_seconds > converse_core_api.settings.get("idle_presence_timeout") && !converse_core_converse.idle) {
        converse_core_converse.idle = true;
        converse_core_api.user.presence.send();
      }

      if (converse_core_api.settings.get("auto_away") > 0 && converse_core_converse.idle_seconds > converse_core_api.settings.get("auto_away") && stat !== 'away' && stat !== 'xa' && stat !== 'dnd') {
        converse_core_converse.auto_changed_status = true;

        converse_core_converse.xmppstatus.set('status', 'away');
      } else if (converse_core_api.settings.get("auto_xa") > 0 && converse_core_converse.idle_seconds > converse_core_api.settings.get("auto_xa") && stat !== 'xa' && stat !== 'dnd') {
        converse_core_converse.auto_changed_status = true;

        converse_core_converse.xmppstatus.set('status', 'xa');
      }
    };

    converse_core_converse.registerIntervalHandler = function () {
      /* Set an interval of one second and register a handler for it.
       * Required for the auto_away, auto_xa and csi_waiting_time features.
       */
      if (converse_core_api.settings.get("auto_away") < 1 && converse_core_api.settings.get("auto_xa") < 1 && converse_core_api.settings.get("csi_waiting_time") < 1 && converse_core_api.settings.get("idle_presence_timeout") < 1) {
        // Waiting time of less then one second means features aren't used.
        return;
      }

      converse_core_converse.idle_seconds = 0;
      converse_core_converse.auto_changed_status = false; // Was the user's status changed by Converse?

      const {
        unloadevent
      } = converse_core_converse;
      window.addEventListener('click', converse_core_converse.onUserActivity);
      window.addEventListener('focus', converse_core_converse.onUserActivity);
      window.addEventListener('keypress', converse_core_converse.onUserActivity);
      window.addEventListener('mousemove', converse_core_converse.onUserActivity);
      window.addEventListener(unloadevent, converse_core_converse.onUserActivity, {
        'once': true,
        'passive': true
      });
      window.addEventListener(unloadevent, () => {
        var _converse$session;

        return (_converse$session = converse_core_converse.session) === null || _converse$session === void 0 ? void 0 : _converse$session.save('active', false);
      });
      converse_core_converse.everySecondTrigger = window.setInterval(converse_core_converse.onEverySecond, 1000);
    };

    converse_core_api.listen.on('presencesInitialized', reconnecting => {
      if (!reconnecting) {
        converse_core_converse.registerIntervalHandler();
      }
    });

    function onStatusInitialized(reconnecting) {
      /**
       * Triggered when the user's own chat status has been initialized.
       * @event _converse#statusInitialized
       * @example _converse.api.listen.on('statusInitialized', status => { ... });
       * @example _converse.api.waitUntil('statusInitialized').then(() => { ... });
       */
      converse_core_api.trigger('statusInitialized', reconnecting);
    }

    function initStatus(reconnecting) {
      // If there's no xmppstatus obj, then we were never connected to
      // begin with, so we set reconnecting to false.
      reconnecting = converse_core_converse.xmppstatus === undefined ? false : reconnecting;

      if (reconnecting) {
        onStatusInitialized(reconnecting);
      } else {
        const id = `converse.xmppstatus-${converse_core_converse.bare_jid}`;
        converse_core_converse.xmppstatus = new converse_core_converse.XMPPStatus({
          'id': id
        });
        converse_core_converse.xmppstatus.browserStorage = converse_core_converse.createStore(id, "session");

        converse_core_converse.xmppstatus.fetch({
          'success': () => onStatusInitialized(reconnecting),
          'error': () => onStatusInitialized(reconnecting),
          'silent': true
        });
      }
    }
    /************************ BEGIN Event Handlers ************************/


    converse_core_api.listen.on('clearSession', () => {
      if (converse_core_converse.shouldClearCache() && converse_core_converse.xmppstatus) {
        converse_core_converse.xmppstatus.destroy();

        delete converse_core_converse.xmppstatus;
        converse_core_api.promises.add(['statusInitialized']);
      }
    });
    converse_core_api.listen.on('connected', () => initStatus(false));
    converse_core_api.listen.on('reconnected', () => initStatus(true));
    /************************ END Event Handlers ************************/

    /************************ BEGIN API ************************/

    Object.assign(converse_core_converse.api.user, {
      /**
       * @namespace _converse.api.user.presence
       * @memberOf _converse.api.user
       */
      presence: {
        /**
         * Send out a presence stanza
         * @method _converse.api.user.presence.send
         * @param { String } type
         * @param { String } to
         * @param { String } [status] - An optional status message
         */
        async send(type, to, status) {
          await converse_core_api.waitUntil('statusInitialized');
          converse_core_api.send(converse_core_converse.xmppstatus.constructPresence(type, to, status));
        }

      },

      /**
       * Set and get the user's chat status, also called their *availability*.
       * @namespace _converse.api.user.status
       * @memberOf _converse.api.user
       */
      status: {
        /**
         * Return the current user's availability status.
         * @async
         * @method _converse.api.user.status.get
         * @example _converse.api.user.status.get();
         */
        async get() {
          await converse_core_api.waitUntil('statusInitialized');
          return converse_core_converse.xmppstatus.get('status');
        },

        /**
         * The user's status can be set to one of the following values:
         *
         * @async
         * @method _converse.api.user.status.set
         * @param {string} value The user's chat status (e.g. 'away', 'dnd', 'offline', 'online', 'unavailable' or 'xa')
         * @param {string} [message] A custom status message
         *
         * @example _converse.api.user.status.set('dnd');
         * @example _converse.api.user.status.set('dnd', 'In a meeting');
         */
        async set(value, message) {
          const data = {
            'status': value
          };

          if (!Object.keys(converse_core_converse.STATUS_WEIGHTS).includes(value)) {
            throw new Error('Invalid availability value. See https://xmpp.org/rfcs/rfc3921.html#rfc.section.2.2.2.1');
          }

          if (typeof message === 'string') {
            data.status_message = message;
          }

          await converse_core_api.waitUntil('statusInitialized');

          converse_core_converse.xmppstatus.save(data);
        },

        /**
         * Set and retrieve the user's custom status message.
         *
         * @namespace _converse.api.user.status.message
         * @memberOf _converse.api.user.status
         */
        message: {
          /**
           * @async
           * @method _converse.api.user.status.message.get
           * @returns {string} The status message
           * @example const message = _converse.api.user.status.message.get()
           */
          async get() {
            await converse_core_api.waitUntil('statusInitialized');
            return converse_core_converse.xmppstatus.get('status_message');
          },

          /**
           * @async
           * @method _converse.api.user.status.message.set
           * @param {string} status The status message
           * @example _converse.api.user.status.message.set('In a meeting');
           */
          async set(status) {
            await converse_core_api.waitUntil('statusInitialized');

            converse_core_converse.xmppstatus.save({
              status_message: status
            });
          }

        }
      }
    });
  }

});
// CONCATENATED MODULE: ./node_modules/lodash-es/propertyOf.js

/**
 * The opposite of `_.property`; this method creates a function that returns
 * the value at a given path of `object`.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Util
 * @param {Object} object The object to query.
 * @returns {Function} Returns the new accessor function.
 * @example
 *
 * var array = [0, 1, 2],
 *     object = { 'a': array, 'b': array, 'c': array };
 *
 * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
 * // => [2, 0]
 *
 * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
 * // => [2, 0]
 */

function propertyOf(object) {
  return function (path) {
    return object == null ? undefined : _baseGet(object, path);
  };
}

/* harmony default export */ var lodash_es_propertyOf = (propertyOf);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSum.js
/**
 * The base implementation of `_.sum` and `_.sumBy` without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} array The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {number} Returns the sum.
 */
function baseSum(array, iteratee) {
  var result,
      index = -1,
      length = array.length;

  while (++index < length) {
    var current = iteratee(array[index]);

    if (current !== undefined) {
      result = result === undefined ? current : result + current;
    }
  }

  return result;
}

/* harmony default export */ var _baseSum = (baseSum);
// CONCATENATED MODULE: ./node_modules/lodash-es/sum.js


/**
 * Computes the sum of the values in `array`.
 *
 * @static
 * @memberOf _
 * @since 3.4.0
 * @category Math
 * @param {Array} array The array to iterate over.
 * @returns {number} Returns the sum.
 * @example
 *
 * _.sum([4, 2, 8, 6]);
 * // => 20
 */

function sum(array) {
  return array && array.length ? _baseSum(array, lodash_es_identity) : 0;
}

/* harmony default export */ var lodash_es_sum = (sum);
// CONCATENATED MODULE: ./src/headless/converse-roster.js
/**
 * @module converse-roster
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */






const {
  Strophe: converse_roster_Strophe,
  $iq: converse_roster_$iq,
  $pres: converse_roster_$pres,
  dayjs: converse_roster_dayjs,
  sizzle: converse_roster_sizzle
} = converse.env;
const converse_roster_u = converse.env.utils;
converse.plugins.add('converse-roster', {
  dependencies: ['converse-status'],

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    const {
      __
    } = converse_core_converse;
    converse_core_api.settings.extend({
      'allow_contact_requests': true,
      'auto_subscribe': false,
      'synchronize_availability': true
    });
    converse_core_api.promises.add(['cachedRoster', 'roster', 'rosterContactsFetched', 'rosterGroupsFetched', 'rosterInitialized']);
    converse_core_converse.HEADER_CURRENT_CONTACTS = __('My contacts');
    converse_core_converse.HEADER_PENDING_CONTACTS = __('Pending contacts');
    converse_core_converse.HEADER_REQUESTING_CONTACTS = __('Contact requests');
    converse_core_converse.HEADER_UNGROUPED = __('Ungrouped');
    converse_core_converse.HEADER_UNREAD = __('New messages');
    const HEADER_WEIGHTS = {};
    HEADER_WEIGHTS[converse_core_converse.HEADER_UNREAD] = 0;
    HEADER_WEIGHTS[converse_core_converse.HEADER_REQUESTING_CONTACTS] = 1;
    HEADER_WEIGHTS[converse_core_converse.HEADER_CURRENT_CONTACTS] = 2;
    HEADER_WEIGHTS[converse_core_converse.HEADER_UNGROUPED] = 3;
    HEADER_WEIGHTS[converse_core_converse.HEADER_PENDING_CONTACTS] = 4;

    converse_core_converse.registerPresenceHandler = function () {
      converse_core_converse.unregisterPresenceHandler();

      converse_core_converse.presence_ref = converse_core_converse.connection.addHandler(presence => {
        converse_core_converse.roster.presenceHandler(presence);

        return true;
      }, null, 'presence', null);
    };
    /**
     * Reject or cancel another user's subscription to our presence updates.
     * @method rejectPresenceSubscription
     * @private
     * @memberOf _converse
     * @param { String } jid - The Jabber ID of the user whose subscription is being canceled
     * @param { String } message - An optional message to the user
     */


    converse_core_converse.rejectPresenceSubscription = function (jid, message) {
      const pres = converse_roster_$pres({
        to: jid,
        type: "unsubscribed"
      });

      if (message && message !== "") {
        pres.c("status").t(message);
      }

      converse_core_api.send(pres);
    };

    converse_core_converse.sendInitialPresence = function () {
      if (converse_core_converse.send_initial_presence) {
        converse_core_api.user.presence.send();
      }
    };
    /**
     * Fetch all the roster groups, and then the roster contacts.
     * Emit an event after fetching is done in each case.
     * @private
     * @method _converse.populateRoster
     * @param { Bool } ignore_cache - If set to to true, the local cache
     *      will be ignored it's guaranteed that the XMPP server
     *      will be queried for the roster.
     */


    converse_core_converse.populateRoster = async function (ignore_cache = false) {
      if (ignore_cache) {
        converse_core_converse.send_initial_presence = true;
      }

      try {
        await converse_core_converse.rostergroups.fetchRosterGroups();
        /**
         * Triggered once roster groups have been fetched. Used by the
         * `converse-rosterview.js` plugin to know when it can start alphabetically
         * position roster groups.
         * @event _converse#rosterGroupsFetched
         * @example _converse.api.listen.on('rosterGroupsFetched', () => { ... });
         * @example _converse.api.waitUntil('rosterGroupsFetched').then(() => { ... });
         */

        converse_core_api.trigger('rosterGroupsFetched');
        await converse_core_converse.roster.fetchRosterContacts();
        converse_core_api.trigger('rosterContactsFetched');
      } catch (reason) {
        headless_log.error(reason);
      } finally {
        converse_core_converse.sendInitialPresence();
      }
    };

    const Resource = model_Model.extend({
      'idAttribute': 'name'
    });
    const Resources = Collection.extend({
      'model': Resource
    });
    converse_core_converse.Presence = model_Model.extend({
      defaults: {
        'show': 'offline'
      },

      initialize() {
        this.resources = new Resources();
        const id = `converse.identities-${this.get('jid')}`;
        this.resources.browserStorage = converse_core_converse.createStore(id, "session");
        this.listenTo(this.resources, 'update', this.onResourcesChanged);
        this.listenTo(this.resources, 'change', this.onResourcesChanged);
      },

      onResourcesChanged() {
        var _hpr$attributes;

        const hpr = this.getHighestPriorityResource();
        const show = (hpr === null || hpr === void 0 ? void 0 : (_hpr$attributes = hpr.attributes) === null || _hpr$attributes === void 0 ? void 0 : _hpr$attributes.show) || 'offline';

        if (this.get('show') !== show) {
          this.save({
            'show': show
          });
        }
      },

      /**
       * Return the resource with the highest priority.
       * If multiple resources have the same priority, take the latest one.
       * @private
       */
      getHighestPriorityResource() {
        return this.resources.sortBy(r => `${r.get('priority')}-${r.get('timestamp')}`).reverse()[0];
      },

      /**
       * Adds a new resource and it's associated attributes as taken
       * from the passed in presence stanza.
       * Also updates the presence if the resource has higher priority (and is newer).
       * @private
       * @param { XMLElement } presence: The presence stanza
       */
      addResource(presence) {
        const jid = presence.getAttribute('from'),
              name = converse_roster_Strophe.getResourceFromJid(jid),
              delay = converse_roster_sizzle(`delay[xmlns="${converse_roster_Strophe.NS.DELAY}"]`, presence).pop(),
              priority = lodash_es_propertyOf(presence.querySelector('priority'))('textContent') || 0,
              resource = this.resources.get(name),
              settings = {
          'name': name,
          'priority': lodash_es_isNaN(parseInt(priority, 10)) ? 0 : parseInt(priority, 10),
          'show': lodash_es_propertyOf(presence.querySelector('show'))('textContent') || 'online',
          'timestamp': delay ? converse_roster_dayjs(delay.getAttribute('stamp')).toISOString() : new Date().toISOString()
        };

        if (resource) {
          resource.save(settings);
        } else {
          this.resources.create(settings);
        }
      },

      /**
       * Remove the passed in resource from the resources map.
       * Also redetermines the presence given that there's one less
       * resource.
       * @private
       * @param { string } name: The resource name
       */
      removeResource(name) {
        const resource = this.resources.get(name);

        if (resource) {
          resource.destroy();
        }
      }

    });
    converse_core_converse.Presences = Collection.extend({
      model: converse_core_converse.Presence
    });
    /**
     * @class
     * @namespace _converse.RosterContact
     * @memberOf _converse
     */

    converse_core_converse.RosterContact = model_Model.extend({
      defaults: {
        'chat_state': undefined,
        'image': converse_core_converse.DEFAULT_IMAGE,
        'image_type': converse_core_converse.DEFAULT_IMAGE_TYPE,
        'num_unread': 0,
        'status': undefined
      },

      async initialize(attributes) {
        this.initialized = converse_roster_u.getResolveablePromise();
        this.setPresence();
        const {
          jid
        } = attributes;
        const bare_jid = converse_roster_Strophe.getBareJidFromJid(jid).toLowerCase();
        attributes.jid = bare_jid;
        this.set(Object.assign({
          'groups': [],
          'id': bare_jid,
          'jid': bare_jid,
          'user_id': converse_roster_Strophe.getNodeFromJid(jid)
        }, attributes));
        /**
         * When a contact's presence status has changed.
         * The presence status is either `online`, `offline`, `dnd`, `away` or `xa`.
         * @event _converse#contactPresenceChanged
         * @type { _converse.RosterContact }
         * @example _converse.api.listen.on('contactPresenceChanged', contact => { ... });
         */

        this.listenTo(this.presence, 'change:show', () => converse_core_api.trigger('contactPresenceChanged', this));
        this.listenTo(this.presence, 'change:show', () => this.trigger('presenceChanged'));
        /**
         * Synchronous event which provides a hook for further initializing a RosterContact
         * @event _converse#rosterContactInitialized
         * @param { _converse.RosterContact } contact
         */

        await converse_core_api.trigger('rosterContactInitialized', this, {
          'Synchronous': true
        });
        this.initialized.resolve();
      },

      setPresence() {
        const jid = this.get('jid');
        this.presence = converse_core_converse.presences.findWhere({
          'jid': jid
        }) || converse_core_converse.presences.create({
          'jid': jid
        });
      },

      openChat() {
        const attrs = this.attributes;
        converse_core_api.chats.open(attrs.jid, attrs, true);
      },

      /**
       * Return a string of tab-separated values that are to be used when
       * matching against filter text.
       *
       * The goal is to be able to filter against the VCard fullname,
       * roster nickname and JID.
       * @returns { String } Lower-cased, tab-separated values
       */
      getFilterCriteria() {
        const nick = this.get('nickname');
        const jid = this.get('jid');
        let criteria = this.getDisplayName();
        criteria = !criteria.includes(jid) ? criteria.concat(`   ${jid}`) : criteria;
        criteria = !criteria.includes(nick) ? criteria.concat(`   ${nick}`) : criteria;
        return criteria.toLowerCase();
      },

      getDisplayName() {
        // Gets overridden in converse-vcard where the fullname is may be returned
        if (this.get('nickname')) {
          return this.get('nickname');
        } else {
          return this.get('jid');
        }
      },

      getFullname() {
        // Gets overridden in converse-vcard where the fullname may be returned
        return this.get('jid');
      },

      /**
       * Send a presence subscription request to this roster contact
       * @private
       * @method _converse.RosterContacts#subscribe
       * @param { String } message - An optional message to explain the
       *      reason for the subscription request.
       */
      subscribe(message) {
        const pres = converse_roster_$pres({
          to: this.get('jid'),
          type: "subscribe"
        });

        if (message && message !== "") {
          pres.c("status").t(message).up();
        }

        const nick = converse_core_converse.xmppstatus.getNickname() || converse_core_converse.xmppstatus.getFullname();

        if (nick) {
          pres.c('nick', {
            'xmlns': converse_roster_Strophe.NS.NICK
          }).t(nick).up();
        }

        converse_core_api.send(pres);
        this.save('ask', "subscribe"); // ask === 'subscribe' Means we have asked to subscribe to them.

        return this;
      },

      /**
       * Upon receiving the presence stanza of type "subscribed",
       * the user SHOULD acknowledge receipt of that subscription
       * state notification by sending a presence stanza of type
       * "subscribe" to the contact
       * @private
       * @method _converse.RosterContacts#ackSubscribe
       */
      ackSubscribe() {
        converse_core_api.send(converse_roster_$pres({
          'type': 'subscribe',
          'to': this.get('jid')
        }));
      },

      /**
       * Upon receiving the presence stanza of type "unsubscribed",
       * the user SHOULD acknowledge receipt of that subscription state
       * notification by sending a presence stanza of type "unsubscribe"
       * this step lets the user's server know that it MUST no longer
       * send notification of the subscription state change to the user.
       * @private
       * @method _converse.RosterContacts#ackUnsubscribe
       * @param { String } jid - The Jabber ID of the user who is unsubscribing
       */
      ackUnsubscribe() {
        converse_core_api.send(converse_roster_$pres({
          'type': 'unsubscribe',
          'to': this.get('jid')
        }));
        this.removeFromRoster();
        this.destroy();
      },

      /**
       * Unauthorize this contact's presence subscription
       * @private
       * @method _converse.RosterContacts#unauthorize
       * @param { String } message - Optional message to send to the person being unauthorized
       */
      unauthorize(message) {
        converse_core_converse.rejectPresenceSubscription(this.get('jid'), message);

        return this;
      },

      /**
       * Authorize presence subscription
       * @private
       * @method _converse.RosterContacts#authorize
       * @param { String } message - Optional message to send to the person being authorized
       */
      authorize(message) {
        const pres = converse_roster_$pres({
          'to': this.get('jid'),
          'type': "subscribed"
        });

        if (message && message !== "") {
          pres.c("status").t(message);
        }

        converse_core_api.send(pres);
        return this;
      },

      /**
       * Instruct the XMPP server to remove this contact from our roster
       * @private
       * @method _converse.RosterContacts#
       * @returns { Promise }
       */
      removeFromRoster() {
        const iq = converse_roster_$iq({
          type: 'set'
        }).c('query', {
          xmlns: converse_roster_Strophe.NS.ROSTER
        }).c('item', {
          jid: this.get('jid'),
          subscription: "remove"
        });
        return converse_core_api.sendIQ(iq);
      }

    });
    /**
     * @class
     * @namespace _converse.RosterContacts
     * @memberOf _converse
     */

    converse_core_converse.RosterContacts = Collection.extend({
      model: converse_core_converse.RosterContact,

      comparator(contact1, contact2) {
        // Groups are sorted alphabetically, ignoring case.
        // However, Ungrouped, Requesting Contacts and Pending Contacts
        // appear last and in that order.
        const status1 = contact1.presence.get('show') || 'offline';
        const status2 = contact2.presence.get('show') || 'offline';

        if (converse_core_converse.STATUS_WEIGHTS[status1] === converse_core_converse.STATUS_WEIGHTS[status2]) {
          const name1 = contact1.getDisplayName().toLowerCase();
          const name2 = contact2.getDisplayName().toLowerCase();
          return name1 < name2 ? -1 : name1 > name2 ? 1 : 0;
        } else {
          return converse_core_converse.STATUS_WEIGHTS[status1] < converse_core_converse.STATUS_WEIGHTS[status2] ? -1 : 1;
        }
      },

      onConnected() {
        // Called as soon as the connection has been established
        // (either after initial login, or after reconnection).
        // Use the opportunity to register stanza handlers.
        this.registerRosterHandler();
        this.registerRosterXHandler();
      },

      registerRosterHandler() {
        // Register a handler for roster IQ "set" stanzas, which update
        // roster contacts.
        converse_core_converse.connection.addHandler(iq => {
          converse_core_converse.roster.onRosterPush(iq);

          return true;
        }, converse_roster_Strophe.NS.ROSTER, 'iq', "set");
      },

      registerRosterXHandler() {
        // Register a handler for RosterX message stanzas, which are
        // used to suggest roster contacts to a user.
        let t = 0;

        converse_core_converse.connection.addHandler(function (msg) {
          window.setTimeout(function () {
            converse_core_converse.connection.flush();

            converse_core_converse.roster.subscribeToSuggestedItems.bind(converse_core_converse.roster)(msg);
          }, t);
          t += msg.querySelectorAll('item').length * 250;
          return true;
        }, converse_roster_Strophe.NS.ROSTERX, 'message', null);
      },

      /**
       * Fetches the roster contacts, first by trying the browser cache,
       * and if that's empty, then by querying the XMPP server.
       * @private
       * @returns {promise} Promise which resolves once the contacts have been fetched.
       */
      async fetchRosterContacts() {
        const result = await new Promise((resolve, reject) => {
          this.fetch({
            'add': true,
            'silent': true,
            'success': resolve,
            'error': (c, e) => reject(e)
          });
        });

        if (converse_roster_u.isErrorObject(result)) {
          headless_log.error(result); // Force a full roster refresh

          converse_core_converse.session.set('roster_cached', false);

          this.data.save('version', undefined);
        }

        if (converse_core_converse.session.get('roster_cached')) {
          /**
           * The contacts roster has been retrieved from the local cache (`sessionStorage`).
           * @event _converse#cachedRoster
           * @type { _converse.RosterContacts }
           * @example _converse.api.listen.on('cachedRoster', (items) => { ... });
           * @example _converse.api.waitUntil('cachedRoster').then(items => { ... });
           */
          converse_core_api.trigger('cachedRoster', result);
        } else {
          converse_core_converse.send_initial_presence = true;
          return converse_core_converse.roster.fetchFromServer();
        }
      },

      subscribeToSuggestedItems(msg) {
        Array.from(msg.querySelectorAll('item')).forEach(item => {
          if (item.getAttribute('action') === 'add') {
            converse_core_converse.roster.addAndSubscribe(item.getAttribute('jid'), converse_core_converse.xmppstatus.getNickname() || converse_core_converse.xmppstatus.getFullname());
          }
        });
        return true;
      },

      isSelf(jid) {
        return converse_roster_u.isSameBareJID(jid, converse_core_converse.connection.jid);
      },

      /**
       * Add a roster contact and then once we have confirmation from
       * the XMPP server we subscribe to that contact's presence updates.
       * @private
       * @method _converse.RosterContacts#addAndSubscribe
       * @param { String } jid - The Jabber ID of the user being added and subscribed to.
       * @param { String } name - The name of that user
       * @param { Array.String } groups - Any roster groups the user might belong to
       * @param { String } message - An optional message to explain the reason for the subscription request.
       * @param { Object } attributes - Any additional attributes to be stored on the user's model.
       */
      async addAndSubscribe(jid, name, groups, message, attributes) {
        const contact = await this.addContactToRoster(jid, name, groups, attributes);

        if (contact instanceof converse_core_converse.RosterContact) {
          contact.subscribe(message);
        }
      },

      /**
       * Send an IQ stanza to the XMPP server to add a new roster contact.
       * @private
       * @method _converse.RosterContacts#sendContactAddIQ
       * @param { String } jid - The Jabber ID of the user being added
       * @param { String } name - The name of that user
       * @param { Array.String } groups - Any roster groups the user might belong to
       * @param { Function } callback - A function to call once the IQ is returned
       * @param { Function } errback - A function to call if an error occurred
       */
      sendContactAddIQ(jid, name, groups) {
        name = name ? name : null;
        const iq = converse_roster_$iq({
          'type': 'set'
        }).c('query', {
          'xmlns': converse_roster_Strophe.NS.ROSTER
        }).c('item', {
          jid,
          name
        });
        groups.forEach(g => iq.c('group').t(g).up());
        return converse_core_api.sendIQ(iq);
      },

      /**
       * Adds a RosterContact instance to _converse.roster and
       * registers the contact on the XMPP server.
       * Returns a promise which is resolved once the XMPP server has responded.
       * @private
       * @method _converse.RosterContacts#addContactToRoster
       * @param { String } jid - The Jabber ID of the user being added and subscribed to.
       * @param { String } name - The name of that user
       * @param { Array.String } groups - Any roster groups the user might belong to
       * @param { Object } attributes - Any additional attributes to be stored on the user's model.
       */
      async addContactToRoster(jid, name, groups, attributes) {
        await converse_core_api.waitUntil('rosterContactsFetched');
        groups = groups || [];

        try {
          await this.sendContactAddIQ(jid, name, groups);
        } catch (e) {
          headless_log.error(e);
          alert(__('Sorry, there was an error while trying to add %1$s as a contact.', name || jid));
          return e;
        }

        return this.create(Object.assign({
          'ask': undefined,
          'nickname': name,
          groups,
          jid,
          'requesting': false,
          'subscription': 'none'
        }, attributes), {
          'sort': false
        });
      },

      async subscribeBack(bare_jid, presence) {
        const contact = this.get(bare_jid);

        if (contact instanceof converse_core_converse.RosterContact) {
          contact.authorize().subscribe();
        } else {
          var _sizzle$pop;

          // Can happen when a subscription is retried or roster was deleted
          const nickname = ((_sizzle$pop = converse_roster_sizzle(`nick[xmlns="${converse_roster_Strophe.NS.NICK}"]`, presence).pop()) === null || _sizzle$pop === void 0 ? void 0 : _sizzle$pop.textContent) || null;
          const contact = await this.addContactToRoster(bare_jid, nickname, [], {
            'subscription': 'from'
          });

          if (contact instanceof converse_core_converse.RosterContact) {
            contact.authorize().subscribe();
          }
        }
      },

      getNumOnlineContacts() {
        const ignored = ['offline', 'unavailable'];
        return lodash_es_sum(this.models.filter(m => !ignored.includes(m.presence.get('show'))));
      },

      /**
       * Handle roster updates from the XMPP server.
       * See: https://xmpp.org/rfcs/rfc6121.html#roster-syntax-actions-push
       * @private
       * @method _converse.RosterContacts#onRosterPush
       * @param { XMLElement } IQ - The IQ stanza received from the XMPP server.
       */
      onRosterPush(iq) {
        const id = iq.getAttribute('id');
        const from = iq.getAttribute('from');

        if (from && from !== converse_core_converse.bare_jid) {
          // https://tools.ietf.org/html/rfc6121#page-15
          //
          // A receiving client MUST ignore the stanza unless it has no 'from'
          // attribute (i.e., implicitly from the bare JID of the user's
          // account) or it has a 'from' attribute whose value matches the
          // user's bare JID <user@domainpart>.
          headless_log.warn(`Ignoring roster illegitimate roster push message from ${iq.getAttribute('from')}`);
          return;
        }

        converse_core_api.send(converse_roster_$iq({
          type: 'result',
          id,
          from: converse_core_converse.connection.jid
        }));
        const query = converse_roster_sizzle(`query[xmlns="${converse_roster_Strophe.NS.ROSTER}"]`, iq).pop();
        this.data.save('version', query.getAttribute('ver'));
        const items = converse_roster_sizzle(`item`, query);

        if (items.length > 1) {
          headless_log.error(iq);
          throw new Error('Roster push query may not contain more than one "item" element.');
        }

        if (items.length === 0) {
          headless_log.warn(iq);
          headless_log.warn('Received a roster push stanza without an "item" element.');
          return;
        }

        this.updateContact(items.pop());
        /**
         * When the roster receives a push event from server (i.e. new entry in your contacts roster).
         * @event _converse#rosterPush
         * @type { XMLElement }
         * @example _converse.api.listen.on('rosterPush', iq => { ... });
         */

        converse_core_api.trigger('rosterPush', iq);
        return;
      },

      rosterVersioningSupported() {
        return converse_core_api.disco.stream.getFeature('ver', 'urn:xmpp:features:rosterver') && this.data.get('version');
      },

      /**
       * Fetch the roster from the XMPP server
       * @private
       * @emits _converse#roster
       * @returns {promise}
       */
      async fetchFromServer() {
        const stanza = converse_roster_$iq({
          'type': 'get',
          'id': converse_roster_u.getUniqueId('roster')
        }).c('query', {
          xmlns: converse_roster_Strophe.NS.ROSTER
        });

        if (this.rosterVersioningSupported()) {
          stanza.attrs({
            'ver': this.data.get('version')
          });
        }

        const iq = await converse_core_api.sendIQ(stanza, null, false);

        if (iq.getAttribute('type') !== 'error') {
          const query = converse_roster_sizzle(`query[xmlns="${converse_roster_Strophe.NS.ROSTER}"]`, iq).pop();

          if (query) {
            const items = converse_roster_sizzle(`item`, query);
            items.forEach(item => this.updateContact(item));
            this.data.save('version', query.getAttribute('ver'));
          }
        } else if (!converse_roster_u.isServiceUnavailableError(iq)) {
          // Some unknown error happened, so we will try to fetch again if the page reloads.
          headless_log.error(iq);
          headless_log.error("Error while trying to fetch roster from the server");
          return;
        }

        converse_core_converse.session.save('roster_cached', true);
        /**
         * When the roster has been received from the XMPP server.
         * See also the `cachedRoster` event further up, which gets called instead of
         * `roster` if its already in `sessionStorage`.
         * @event _converse#roster
         * @type { XMLElement }
         * @example _converse.api.listen.on('roster', iq => { ... });
         * @example _converse.api.waitUntil('roster').then(iq => { ... });
         */


        converse_core_api.trigger('roster', iq);
      },

      /* Update or create RosterContact models based on the given `item` XML
       * node received in the resulting IQ stanza from the server.
       * @private
       * @param { XMLElement } item
       */
      updateContact(item) {
        const jid = item.getAttribute('jid');
        const contact = this.get(jid);
        const subscription = item.getAttribute("subscription");
        const ask = item.getAttribute("ask");
        const groups = Array.from(item.getElementsByTagName('group')).map(e => e.textContent);

        if (!contact) {
          if (subscription === "none" && ask === null || subscription === "remove") {
            return; // We're lazy when adding contacts.
          }

          this.create({
            'ask': ask,
            'nickname': item.getAttribute("name"),
            'groups': groups,
            'jid': jid,
            'subscription': subscription
          }, {
            sort: false
          });
        } else {
          if (subscription === "remove") {
            return contact.destroy();
          } // We only find out about requesting contacts via the
          // presence handler, so if we receive a contact
          // here, we know they aren't requesting anymore.
          // see docs/DEVELOPER.rst


          contact.save({
            'subscription': subscription,
            'ask': ask,
            'nickname': item.getAttribute("name"),
            'requesting': null,
            'groups': groups
          });
        }
      },

      createRequestingContact(presence) {
        var _sizzle$pop2;

        const bare_jid = converse_roster_Strophe.getBareJidFromJid(presence.getAttribute('from'));
        const nickname = ((_sizzle$pop2 = converse_roster_sizzle(`nick[xmlns="${converse_roster_Strophe.NS.NICK}"]`, presence).pop()) === null || _sizzle$pop2 === void 0 ? void 0 : _sizzle$pop2.textContent) || null;
        const user_data = {
          'jid': bare_jid,
          'subscription': 'none',
          'ask': null,
          'requesting': true,
          'nickname': nickname
        };
        /**
         * Triggered when someone has requested to subscribe to your presence (i.e. to be your contact).
         * @event _converse#contactRequest
         * @type { _converse.RosterContact }
         * @example _converse.api.listen.on('contactRequest', contact => { ... });
         */

        converse_core_api.trigger('contactRequest', this.create(user_data));
      },

      handleIncomingSubscription(presence) {
        const jid = presence.getAttribute('from'),
              bare_jid = converse_roster_Strophe.getBareJidFromJid(jid),
              contact = this.get(bare_jid);

        if (!converse_core_api.settings.get('allow_contact_requests')) {
          converse_core_converse.rejectPresenceSubscription(jid, __("This client does not allow presence subscriptions"));
        }

        if (converse_core_api.settings.get('auto_subscribe')) {
          if (!contact || contact.get('subscription') !== 'to') {
            this.subscribeBack(bare_jid, presence);
          } else {
            contact.authorize();
          }
        } else {
          if (contact) {
            if (contact.get('subscription') !== 'none') {
              contact.authorize();
            } else if (contact.get('ask') === "subscribe") {
              contact.authorize();
            }
          } else {
            this.createRequestingContact(presence);
          }
        }
      },

      handleOwnPresence(presence) {
        const jid = presence.getAttribute('from'),
              resource = converse_roster_Strophe.getResourceFromJid(jid),
              presence_type = presence.getAttribute('type');

        if (converse_core_converse.connection.jid !== jid && presence_type !== 'unavailable' && (converse_core_api.settings.get('synchronize_availability') === true || converse_core_api.settings.get('synchronize_availability') === resource)) {
          // Another resource has changed its status and
          // synchronize_availability option set to update,
          // we'll update ours as well.
          const show = lodash_es_propertyOf(presence.querySelector('show'))('textContent') || 'online';

          converse_core_converse.xmppstatus.save({
            'status': show
          }, {
            'silent': true
          });

          const status_message = lodash_es_propertyOf(presence.querySelector('status'))('textContent');

          if (status_message) {
            converse_core_converse.xmppstatus.save({
              'status_message': status_message
            });
          }
        }

        if (converse_core_converse.jid === jid && presence_type === 'unavailable') {
          // XXX: We've received an "unavailable" presence from our
          // own resource. Apparently this happens due to a
          // Prosody bug, whereby we send an IQ stanza to remove
          // a roster contact, and Prosody then sends
          // "unavailable" globally, instead of directed to the
          // particular user that's removed.
          //
          // Here is the bug report: https://prosody.im/issues/1121
          //
          // I'm not sure whether this might legitimately happen
          // in other cases.
          //
          // As a workaround for now we simply send our presence again,
          // otherwise we're treated as offline.
          converse_core_api.user.presence.send();
        }
      },

      presenceHandler(presence) {
        const presence_type = presence.getAttribute('type');

        if (presence_type === 'error') {
          return true;
        }

        const jid = presence.getAttribute('from'),
              bare_jid = converse_roster_Strophe.getBareJidFromJid(jid);

        if (this.isSelf(bare_jid)) {
          return this.handleOwnPresence(presence);
        } else if (converse_roster_sizzle(`query[xmlns="${converse_roster_Strophe.NS.MUC}"]`, presence).length) {
          return; // Ignore MUC
        }

        const status_message = lodash_es_propertyOf(presence.querySelector('status'))('textContent'),
              contact = this.get(bare_jid);

        if (contact && status_message !== contact.get('status')) {
          contact.save({
            'status': status_message
          });
        }

        if (presence_type === 'subscribed' && contact) {
          contact.ackSubscribe();
        } else if (presence_type === 'unsubscribed' && contact) {
          contact.ackUnsubscribe();
        } else if (presence_type === 'unsubscribe') {
          return;
        } else if (presence_type === 'subscribe') {
          this.handleIncomingSubscription(presence);
        } else if (presence_type === 'unavailable' && contact) {
          const resource = converse_roster_Strophe.getResourceFromJid(jid);
          contact.presence.removeResource(resource);
        } else if (contact) {
          // presence_type is undefined
          contact.presence.addResource(presence);
        }
      }

    });
    converse_core_converse.RosterGroup = model_Model.extend({
      initialize(attributes) {
        this.set(Object.assign({
          description: __('Click to hide these contacts'),
          state: converse_core_converse.OPENED
        }, attributes)); // Collection of contacts belonging to this group.

        this.contacts = new converse_core_converse.RosterContacts();
      }

    });
    /**
     * @class
     * @namespace _converse.RosterGroups
     * @memberOf _converse
     */

    converse_core_converse.RosterGroups = Collection.extend({
      model: converse_core_converse.RosterGroup,

      comparator(a, b) {
        a = a.get('name');
        b = b.get('name');
        const WEIGHTS = HEADER_WEIGHTS;
        const special_groups = Object.keys(HEADER_WEIGHTS);
        const a_is_special = special_groups.includes(a);
        const b_is_special = special_groups.includes(b);

        if (!a_is_special && !b_is_special) {
          return a.toLowerCase() < b.toLowerCase() ? -1 : a.toLowerCase() > b.toLowerCase() ? 1 : 0;
        } else if (a_is_special && b_is_special) {
          return WEIGHTS[a] < WEIGHTS[b] ? -1 : WEIGHTS[a] > WEIGHTS[b] ? 1 : 0;
        } else if (!a_is_special && b_is_special) {
          const a_header = converse_core_converse.HEADER_CURRENT_CONTACTS;
          return WEIGHTS[a_header] < WEIGHTS[b] ? -1 : WEIGHTS[a_header] > WEIGHTS[b] ? 1 : 0;
        } else if (a_is_special && !b_is_special) {
          const b_header = converse_core_converse.HEADER_CURRENT_CONTACTS;
          return WEIGHTS[a] < WEIGHTS[b_header] ? -1 : WEIGHTS[a] > WEIGHTS[b_header] ? 1 : 0;
        }
      },

      /**
       * Fetches all the roster groups from sessionStorage.
       * @private
       * @method _converse.RosterGroups#fetchRosterGroups
       * @returns { Promise } - A promise which resolves once the groups have been fetched.
       */
      fetchRosterGroups() {
        return new Promise(success => {
          this.fetch({
            success,
            // We need to first have all groups before
            // we can start positioning them, so we set
            // 'silent' to true.
            silent: true
          });
        });
      }

    });

    converse_core_converse.unregisterPresenceHandler = function () {
      if (converse_core_converse.presence_ref !== undefined) {
        converse_core_converse.connection.deleteHandler(converse_core_converse.presence_ref);

        delete converse_core_converse.presence_ref;
      }
    };
    /******************** Event Handlers ********************/


    function updateUnreadCounter(chatbox) {
      const contact = converse_core_converse.roster && converse_core_converse.roster.findWhere({
        'jid': chatbox.get('jid')
      });

      if (contact !== undefined) {
        contact.save({
          'num_unread': chatbox.get('num_unread')
        });
      }
    }

    converse_core_api.listen.on('chatBoxesInitialized', () => {
      converse_core_converse.chatboxes.on('change:num_unread', updateUnreadCounter);

      converse_core_converse.chatboxes.on('add', chatbox => {
        if (chatbox.get('type') === converse_core_converse.PRIVATE_CHAT_TYPE) {
          chatbox.setRosterContact(chatbox.get('jid'));
        }
      });
    });
    converse_core_api.listen.on('beforeTearDown', () => converse_core_converse.unregisterPresenceHandler());
    converse_core_api.waitUntil('rosterContactsFetched').then(() => {
      converse_core_converse.roster.on('add', contact => {
        /* When a new contact is added, check if we already have a
         * chatbox open for it, and if so attach it to the chatbox.
         */
        const chatbox = converse_core_converse.chatboxes.findWhere({
          'jid': contact.get('jid')
        });

        if (chatbox) {
          chatbox.setRosterContact(contact.get('jid'));
        }
      });
    });

    async function clearPresences() {
      converse_core_converse.presences && (await converse_core_converse.presences.clearStore());
    }

    converse_core_api.listen.on('streamResumptionFailed', () => converse_core_converse.session.set('roster_cached', false));
    converse_core_api.listen.on('clearSession', async () => {
      await clearPresences();

      if (converse_core_converse.shouldClearCache()) {
        if (converse_core_converse.rostergroups) {
          await converse_core_converse.rostergroups.clearStore();
          delete converse_core_converse.rostergroups;
        }

        if (converse_core_converse.roster) {
          lodash_es_invoke(converse_core_converse, 'roster.data.destroy');
          await converse_core_converse.roster.clearStore();
          delete converse_core_converse.roster;
        }
      }
    });
    converse_core_api.listen.on('statusInitialized', async reconnecting => {
      if (reconnecting) {
        // When reconnecting and not resuming a previous session,
        // we clear all cached presence data, since it might be stale
        // and we'll receive new presence updates
        !converse_core_converse.connection.hasResumed() && (await clearPresences());
      } else {
        converse_core_converse.presences = new converse_core_converse.Presences();
        const id = `converse.presences-${converse_core_converse.bare_jid}`;
        converse_core_converse.presences.browserStorage = converse_core_converse.createStore(id, "session"); // We might be continuing an existing session, so we fetch
        // cached presence data.

        converse_core_converse.presences.fetch();
      }
      /**
       * Triggered once the _converse.Presences collection has been
       * initialized and its cached data fetched.
       * Returns a boolean indicating whether this event has fired due to
       * Converse having reconnected.
       * @event _converse#presencesInitialized
       * @type { bool }
       * @example _converse.api.listen.on('presencesInitialized', reconnecting => { ... });
       */


      converse_core_api.trigger('presencesInitialized', reconnecting);
    });

    async function initRoster() {
      // Initialize the Bakcbone collections that represent the contats
      // roster and the roster groups.
      await converse_core_api.waitUntil('VCardsInitialized');
      converse_core_converse.roster = new converse_core_converse.RosterContacts();
      let id = `converse.contacts-${converse_core_converse.bare_jid}`;
      converse_core_converse.roster.browserStorage = converse_core_converse.createStore(id);
      converse_core_converse.roster.data = new model_Model();
      id = `converse-roster-model-${converse_core_converse.bare_jid}`;
      converse_core_converse.roster.data.id = id;
      converse_core_converse.roster.data.browserStorage = converse_core_converse.createStore(id);

      converse_core_converse.roster.data.fetch();

      id = `converse.roster.groups${converse_core_converse.bare_jid}`;
      converse_core_converse.rostergroups = new converse_core_converse.RosterGroups();
      converse_core_converse.rostergroups.browserStorage = converse_core_converse.createStore(id);
      /**
       * Triggered once the `_converse.RosterContacts` and `_converse.RosterGroups` have
       * been created, but not yet populated with data.
       * This event is useful when you want to create views for these collections.
       * @event _converse#chatBoxMaximized
       * @example _converse.api.listen.on('rosterInitialized', () => { ... });
       * @example _converse.api.waitUntil('rosterInitialized').then(() => { ... });
       */

      converse_core_api.trigger('rosterInitialized');
    }

    converse_core_api.listen.on('presencesInitialized', async reconnecting => {
      if (reconnecting) {
        /**
         * Similar to `rosterInitialized`, but instead pertaining to reconnection.
         * This event indicates that the roster and its groups are now again
         * available after Converse.js has reconnected.
         * @event _converse#rosterReadyAfterReconnection
         * @example _converse.api.listen.on('rosterReadyAfterReconnection', () => { ... });
         */
        converse_core_api.trigger('rosterReadyAfterReconnection');
      } else {
        await initRoster();
      }

      converse_core_converse.roster.onConnected();

      converse_core_converse.registerPresenceHandler();

      converse_core_converse.populateRoster(!converse_core_converse.connection.restored);
    });
    /************************ API ************************/
    // API methods only available to plugins

    Object.assign(converse_core_converse.api, {
      /**
       * @namespace _converse.api.contacts
       * @memberOf _converse.api
       */
      contacts: {
        /**
         * This method is used to retrieve roster contacts.
         *
         * @method _converse.api.contacts.get
         * @params {(string[]|string)} jid|jids The JID or JIDs of
         *      the contacts to be returned.
         * @returns {promise} Promise which resolves with the
         *  _converse.RosterContact (or an array of them) representing the contact.
         *
         * @example
         * // Fetch a single contact
         * _converse.api.listen.on('rosterContactsFetched', function () {
         *     const contact = await _converse.api.contacts.get('buddy@example.com')
         *     // ...
         * });
         *
         * @example
         * // To get multiple contacts, pass in an array of JIDs:
         * _converse.api.listen.on('rosterContactsFetched', function () {
         *     const contacts = await _converse.api.contacts.get(
         *         ['buddy1@example.com', 'buddy2@example.com']
         *     )
         *     // ...
         * });
         *
         * @example
         * // To return all contacts, simply call ``get`` without any parameters:
         * _converse.api.listen.on('rosterContactsFetched', function () {
         *     const contacts = await _converse.api.contacts.get();
         *     // ...
         * });
         */
        async get(jids) {
          await converse_core_api.waitUntil('rosterContactsFetched');

          const _getter = jid => converse_core_converse.roster.get(converse_roster_Strophe.getBareJidFromJid(jid));

          if (jids === undefined) {
            jids = converse_core_converse.roster.pluck('jid');
          } else if (typeof jids === 'string') {
            return _getter(jids);
          }

          return jids.map(_getter);
        },

        /**
         * Add a contact.
         *
         * @method _converse.api.contacts.add
         * @param {string} jid The JID of the contact to be added
         * @param {string} [name] A custom name to show the user by in the roster
         * @example
         *     _converse.api.contacts.add('buddy@example.com')
         * @example
         *     _converse.api.contacts.add('buddy@example.com', 'Buddy')
         */
        async add(jid, name) {
          await converse_core_api.waitUntil('rosterContactsFetched');

          if (typeof jid !== 'string' || !jid.includes('@')) {
            throw new TypeError('contacts.add: invalid jid');
          }

          return converse_core_converse.roster.addAndSubscribe(jid, name);
        }

      }
    });
  }

});
// CONCATENATED MODULE: ./src/headless/converse-smacks.js
/**
 * @module converse-smacks
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description Converse.js plugin which adds support for XEP-0198: Stream Management
 */


const {
  Strophe: converse_smacks_Strophe
} = converse.env;
const converse_smacks_u = converse.env.utils;
converse_smacks_Strophe.addNamespace('SM', 'urn:xmpp:sm:3');

function isStreamManagementSupported() {
  if (converse_core_api.connection.isType('bosh') && !converse_core_converse.isTestEnv()) {
    return false;
  }

  return converse_core_api.disco.stream.getFeature('sm', converse_smacks_Strophe.NS.SM);
}

function handleAck(el) {
  if (!converse_core_converse.session.get('smacks_enabled')) {
    return true;
  }

  const handled = parseInt(el.getAttribute('h'), 10);

  const last_known_handled = converse_core_converse.session.get('num_stanzas_handled_by_server');

  const delta = handled - last_known_handled;

  if (delta < 0) {
    const err_msg = `New reported stanza count lower than previous. ` + `New: ${handled} - Previous: ${last_known_handled}`;
    headless_log.error(err_msg);
  }

  const unacked_stanzas = converse_core_converse.session.get('unacked_stanzas');

  if (delta > unacked_stanzas.length) {
    const err_msg = `Higher reported acknowledge count than unacknowledged stanzas. ` + `Reported Acknowledged Count: ${delta} -` + `Unacknowledged Stanza Count: ${unacked_stanzas.length} -` + `New: ${handled} - Previous: ${last_known_handled}`;
    headless_log.error(err_msg);
  }

  converse_core_converse.session.save({
    'num_stanzas_handled_by_server': handled,
    'num_stanzas_since_last_ack': 0,
    'unacked_stanzas': unacked_stanzas.slice(delta)
  });

  return true;
}

function sendAck() {
  if (converse_core_converse.session.get('smacks_enabled')) {
    const h = converse_core_converse.session.get('num_stanzas_handled');

    const stanza = converse_smacks_u.toStanza(`<a xmlns="${converse_smacks_Strophe.NS.SM}" h="${h}"/>`);
    converse_core_api.send(stanza);
  }

  return true;
}

function stanzaHandler(el) {
  if (converse_core_converse.session.get('smacks_enabled')) {
    if (converse_smacks_u.isTagEqual(el, 'iq') || converse_smacks_u.isTagEqual(el, 'presence') || converse_smacks_u.isTagEqual(el, 'message')) {
      const h = converse_core_converse.session.get('num_stanzas_handled');

      converse_core_converse.session.save('num_stanzas_handled', h + 1);
    }
  }

  return true;
}

function initSessionData() {
  converse_core_converse.session.save({
    'smacks_enabled': converse_core_converse.session.get('smacks_enabled') || false,
    'num_stanzas_handled': converse_core_converse.session.get('num_stanzas_handled') || 0,
    'num_stanzas_handled_by_server': converse_core_converse.session.get('num_stanzas_handled_by_server') || 0,
    'num_stanzas_since_last_ack': converse_core_converse.session.get('num_stanzas_since_last_ack') || 0,
    'unacked_stanzas': converse_core_converse.session.get('unacked_stanzas') || []
  });
}

function resetSessionData() {
  converse_core_converse.session && converse_core_converse.session.save({
    'smacks_enabled': false,
    'num_stanzas_handled': 0,
    'num_stanzas_handled_by_server': 0,
    'num_stanzas_since_last_ack': 0,
    'unacked_stanzas': []
  });
}

function saveSessionData(el) {
  const data = {
    'smacks_enabled': true
  };

  if (['1', 'true'].includes(el.getAttribute('resume'))) {
    data['smacks_stream_id'] = el.getAttribute('id');
  }

  converse_core_converse.session.save(data);

  return true;
}

function onFailedStanza(el) {
  if (el.querySelector('item-not-found')) {
    // Stream resumption must happen before resource binding but
    // enabling a new stream must happen after resource binding.
    // Since resumption failed, we simply continue.
    //
    // After resource binding, sendEnableStanza will be called
    // based on the afterResourceBinding event.
    headless_log.warn('Could not resume previous SMACKS session, session id not found. ' + 'A new session will be established.');
  } else {
    headless_log.error('Failed to enable stream management');
    headless_log.error(el.outerHTML);
  }

  resetSessionData();
  /**
   * Triggered when the XEP-0198 stream could not be resumed.
   * @event _converse#streamResumptionFailed
   */

  converse_core_api.trigger('streamResumptionFailed');
  return true;
}

function resendUnackedStanzas() {
  const stanzas = converse_core_converse.session.get('unacked_stanzas'); // We clear the unacked_stanzas array because it'll get populated
  // again in `onStanzaSent`


  converse_core_converse.session.save('unacked_stanzas', []); // XXX: Currently we're resending *all* unacked stanzas, including
  // IQ[type="get"] stanzas that longer have handlers (because the
  // page reloaded or we reconnected, causing removal of handlers).
  //
  // *Side-note:* Is it necessary to clear handlers upon reconnection?
  //
  // I've considered not resending those stanzas, but then keeping
  // track of what's been sent and ack'd and their order gets
  // prohibitively complex.
  //
  // It's unclear how much of a problem this poses.
  //
  // Two possible solutions are running @converse/headless as a
  // service worker or handling IQ[type="result"] stanzas
  // differently, more like push stanzas, so that they don't need
  // explicit handlers.


  stanzas.forEach(s => converse_core_api.send(s));
}

function onResumedStanza(el) {
  saveSessionData(el);
  handleAck(el);
  resendUnackedStanzas();
  converse_core_converse.connection.do_bind = false; // No need to bind our resource anymore

  converse_core_converse.connection.authenticated = true;
  converse_core_converse.connection.restored = true;

  converse_core_converse.connection._changeConnectStatus(converse_smacks_Strophe.Status.CONNECTED, null);
}

async function sendResumeStanza() {
  const promise = converse_smacks_u.getResolveablePromise();

  converse_core_converse.connection._addSysHandler(el => promise.resolve(onResumedStanza(el)), converse_smacks_Strophe.NS.SM, 'resumed');

  converse_core_converse.connection._addSysHandler(el => promise.resolve(onFailedStanza(el)), converse_smacks_Strophe.NS.SM, 'failed');

  const previous_id = converse_core_converse.session.get('smacks_stream_id');

  const h = converse_core_converse.session.get('num_stanzas_handled');

  const stanza = converse_smacks_u.toStanza(`<resume xmlns="${converse_smacks_Strophe.NS.SM}" h="${h}" previd="${previous_id}"/>`);
  converse_core_api.send(stanza);

  converse_core_converse.connection.flush();

  await promise;
}

async function sendEnableStanza() {
  if (!converse_core_api.settings.get('enable_smacks') || converse_core_converse.session.get('smacks_enabled')) {
    return;
  }

  if (await isStreamManagementSupported()) {
    const promise = converse_smacks_u.getResolveablePromise();

    converse_core_converse.connection._addSysHandler(el => promise.resolve(saveSessionData(el)), converse_smacks_Strophe.NS.SM, 'enabled');

    converse_core_converse.connection._addSysHandler(el => promise.resolve(onFailedStanza(el)), converse_smacks_Strophe.NS.SM, 'failed');

    const resume = converse_core_api.connection.isType('websocket') || converse_core_converse.isTestEnv();

    const stanza = converse_smacks_u.toStanza(`<enable xmlns="${converse_smacks_Strophe.NS.SM}" resume="${resume}"/>`);
    converse_core_api.send(stanza);

    converse_core_converse.connection.flush();

    await promise;
  }
}

const smacks_handlers = [];

async function enableStreamManagement() {
  if (!converse_core_api.settings.get('enable_smacks')) {
    return;
  }

  if (!(await isStreamManagementSupported())) {
    return;
  }

  const conn = converse_core_converse.connection;

  while (smacks_handlers.length) {
    conn.deleteHandler(smacks_handlers.pop());
  }

  smacks_handlers.push(conn.addHandler(stanzaHandler));
  smacks_handlers.push(conn.addHandler(sendAck, converse_smacks_Strophe.NS.SM, 'r'));
  smacks_handlers.push(conn.addHandler(handleAck, converse_smacks_Strophe.NS.SM, 'a'));

  if (converse_core_converse.session.get('smacks_stream_id')) {
    await sendResumeStanza();
  } else {
    resetSessionData();
  }
}

function onStanzaSent(stanza) {
  if (!converse_core_converse.session) {
    headless_log.warn('No _converse.session!');
    return;
  }

  if (!converse_core_converse.session.get('smacks_enabled')) {
    return;
  }

  if (converse_smacks_u.isTagEqual(stanza, 'iq') || converse_smacks_u.isTagEqual(stanza, 'presence') || converse_smacks_u.isTagEqual(stanza, 'message')) {
    const stanza_string = converse_smacks_Strophe.serialize(stanza);

    converse_core_converse.session.save('unacked_stanzas', (converse_core_converse.session.get('unacked_stanzas') || []).concat([stanza_string]));

    const max_unacked = converse_core_api.settings.get('smacks_max_unacked_stanzas');

    if (max_unacked > 0) {
      const num = converse_core_converse.session.get('num_stanzas_since_last_ack') + 1;

      if (num % max_unacked === 0) {
        // Request confirmation of sent stanzas
        converse_core_api.send(converse_smacks_u.toStanza(`<r xmlns="${converse_smacks_Strophe.NS.SM}"/>`));
      }

      converse_core_converse.session.save({
        'num_stanzas_since_last_ack': num
      });
    }
  }
}

converse.plugins.add('converse-smacks', {
  initialize() {
    // Configuration values for this plugin
    // ====================================
    // Refer to docs/source/configuration.rst for explanations of these
    // configuration settings.
    converse_core_api.settings.extend({
      'enable_smacks': true,
      'smacks_max_unacked_stanzas': 5
    });
    converse_core_api.listen.on('afterResourceBinding', sendEnableStanza);
    converse_core_api.listen.on('beforeResourceBinding', enableStreamManagement);
    converse_core_api.listen.on('send', onStanzaSent);
    converse_core_api.listen.on('userSessionInitialized', initSessionData);
  }

});
// CONCATENATED MODULE: ./src/headless/converse-vcard.js
/**
 * @module converse-vcard
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */





const {
  Strophe: converse_vcard_Strophe,
  $iq: converse_vcard_$iq,
  dayjs: converse_vcard_dayjs
} = converse.env;
const converse_vcard_u = converse.env.utils;
converse.plugins.add('converse-vcard', {
  dependencies: ["converse-status", "converse-roster"],
  overrides: {
    XMPPStatus: {
      getNickname() {
        const {
          _converse
        } = this.__super__;

        const nick = this.__super__.getNickname.apply(this);

        if (!nick && _converse.xmppstatus.vcard) {
          return _converse.xmppstatus.vcard.get('nickname');
        } else {
          return nick;
        }
      },

      getFullname() {
        const {
          _converse
        } = this.__super__;

        const fullname = this.__super__.getFullname.apply(this);

        if (!fullname && _converse.xmppstatus.vcard) {
          return _converse.xmppstatus.vcard.get('fullname');
        } else {
          return fullname;
        }
      }

    },
    RosterContact: {
      getDisplayName() {
        if (!this.get('nickname') && this.vcard) {
          return this.vcard.getDisplayName();
        } else {
          return this.__super__.getDisplayName.apply(this);
        }
      },

      getFullname() {
        if (this.vcard) {
          return this.vcard.get('fullname');
        } else {
          return this.__super__.getFullname.apply(this);
        }
      }

    }
  },

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    converse_core_api.promises.add('VCardsInitialized');
    /**
     * Represents a VCard
     * @class
     * @namespace _converse.VCard
     * @memberOf _converse
     */

    converse_core_converse.VCard = model_Model.extend({
      defaults: {
        'image': converse_core_converse.DEFAULT_IMAGE,
        'image_type': converse_core_converse.DEFAULT_IMAGE_TYPE
      },

      set(key, val, options) {
        // Override Model.prototype.set to make sure that the
        // default `image` and `image_type` values are maintained.
        let attrs;

        if (typeof key === 'object') {
          attrs = key;
          options = val;
        } else {
          (attrs = {})[key] = val;
        }

        if ('image' in attrs && !attrs['image']) {
          attrs['image'] = converse_core_converse.DEFAULT_IMAGE;
          attrs['image_type'] = converse_core_converse.DEFAULT_IMAGE_TYPE;
          return model_Model.prototype.set.call(this, attrs, options);
        } else {
          return model_Model.prototype.set.apply(this, arguments);
        }
      },

      getDisplayName() {
        return this.get('nickname') || this.get('fullname') || this.get('jid');
      }

    });
    converse_core_converse.VCards = Collection.extend({
      model: converse_core_converse.VCard,

      initialize() {
        this.on('add', vcard => vcard.get('jid') && converse_core_api.vcard.update(vcard));
      }

    });

    async function onVCardData(jid, iq) {
      const vcard = iq.querySelector('vCard');
      let result = {};

      if (vcard !== null) {
        var _vcard$querySelector, _vcard$querySelector2, _vcard$querySelector3, _vcard$querySelector4, _vcard$querySelector5, _vcard$querySelector6, _vcard$querySelector7;

        result = {
          'stanza': iq,
          'fullname': (_vcard$querySelector = vcard.querySelector('FN')) === null || _vcard$querySelector === void 0 ? void 0 : _vcard$querySelector.textContent,
          'nickname': (_vcard$querySelector2 = vcard.querySelector('NICKNAME')) === null || _vcard$querySelector2 === void 0 ? void 0 : _vcard$querySelector2.textContent,
          'image': (_vcard$querySelector3 = vcard.querySelector('PHOTO BINVAL')) === null || _vcard$querySelector3 === void 0 ? void 0 : _vcard$querySelector3.textContent,
          'image_type': (_vcard$querySelector4 = vcard.querySelector('PHOTO TYPE')) === null || _vcard$querySelector4 === void 0 ? void 0 : _vcard$querySelector4.textContent,
          'url': (_vcard$querySelector5 = vcard.querySelector('URL')) === null || _vcard$querySelector5 === void 0 ? void 0 : _vcard$querySelector5.textContent,
          'role': (_vcard$querySelector6 = vcard.querySelector('ROLE')) === null || _vcard$querySelector6 === void 0 ? void 0 : _vcard$querySelector6.textContent,
          'email': (_vcard$querySelector7 = vcard.querySelector('EMAIL USERID')) === null || _vcard$querySelector7 === void 0 ? void 0 : _vcard$querySelector7.textContent,
          'vcard_updated': new Date().toISOString(),
          'vcard_error': undefined
        };
      }

      if (result.image) {
        const buffer = converse_vcard_u.base64ToArrayBuffer(result['image']);
        const ab = await crypto.subtle.digest('SHA-1', buffer);
        result['image_hash'] = converse_vcard_u.arrayBufferToHex(ab);
      }

      return result;
    }

    function createStanza(type, jid, vcard_el) {
      const iq = converse_vcard_$iq(jid ? {
        'type': type,
        'to': jid
      } : {
        'type': type
      });

      if (!vcard_el) {
        iq.c("vCard", {
          'xmlns': converse_vcard_Strophe.NS.VCARD
        });
      } else {
        iq.cnode(vcard_el);
      }

      return iq;
    }

    async function getVCard(_converse, jid) {
      const to = converse_vcard_Strophe.getBareJidFromJid(jid) === _converse.bare_jid ? null : jid;
      let iq;

      try {
        iq = await converse_core_api.sendIQ(createStanza("get", to));
      } catch (iq) {
        return {
          'stanza': iq,
          'jid': jid,
          'vcard_error': new Date().toISOString()
        };
      }

      return onVCardData(jid, iq);
    }

    async function setVCardOnModel(model) {
      let jid;

      if (model instanceof converse_core_converse.Message) {
        if (model.get('type') === 'error') {
          return;
        }

        jid = model.get('from');
      } else {
        jid = model.get('jid');
      }

      await converse_core_api.waitUntil('VCardsInitialized');
      model.vcard = converse_core_converse.vcards.findWhere({
        'jid': jid
      });

      if (!model.vcard) {
        model.vcard = converse_core_converse.vcards.create({
          'jid': jid
        });
      }

      model.vcard.on('change', () => model.trigger('vcard:change'));
    }

    function getVCardForChatroomOccupant(message) {
      var _message$collection;

      const chatbox = message === null || message === void 0 ? void 0 : (_message$collection = message.collection) === null || _message$collection === void 0 ? void 0 : _message$collection.chatbox;
      const nick = converse_vcard_Strophe.getResourceFromJid(message.get('from'));

      if (chatbox && chatbox.get('nick') === nick) {
        return converse_core_converse.xmppstatus.vcard;
      } else {
        const jid = message.occupant && message.occupant.get('jid') || message.get('from');

        if (jid) {
          return converse_core_converse.vcards.findWhere({
            jid
          }) || converse_core_converse.vcards.create({
            jid
          });
        } else {
          headless_log.error(`Could not assign VCard for message because no JID found! msgid: ${message.get('msgid')}`);
          return;
        }
      }
    }

    async function setVCardOnMUCMessage(message) {
      await converse_core_api.waitUntil('VCardsInitialized');

      if (['error', 'info'].includes(message.get('type'))) {
        return;
      } else {
        message.vcard = getVCardForChatroomOccupant(message);
      }
    }

    converse_core_converse.initVCardCollection = async function () {
      converse_core_converse.vcards = new converse_core_converse.VCards();
      converse_core_converse.vcards.browserStorage = converse_core_converse.createStore(`${converse_core_converse.bare_jid}-converse.vcards`);
      await new Promise(resolve => {
        converse_core_converse.vcards.fetch({
          'success': resolve,
          'error': resolve
        }, {
          'silent': true
        });
      });
      const vcards = converse_core_converse.vcards;

      if (converse_core_converse.session) {
        const jid = converse_core_converse.session.get('bare_jid');

        converse_core_converse.xmppstatus.vcard = vcards.findWhere({
          'jid': jid
        }) || vcards.create({
          'jid': jid
        });
      }
      /**
       * Triggered as soon as the `_converse.vcards` collection has been initialized and populated from cache.
       * @event _converse#VCardsInitialized
       */


      converse_core_api.trigger('VCardsInitialized');
    };

    function clearVCardsSession() {
      if (converse_core_converse.shouldClearCache()) {
        converse_core_api.promises.add('VCardsInitialized');

        if (converse_core_converse.vcards) {
          converse_core_converse.vcards.clearStore();

          delete converse_core_converse.vcards;
        }
      }
    }
    /************************ BEGIN Event Handlers ************************/


    converse_core_api.listen.on('chatBoxInitialized', m => setVCardOnModel(m));
    converse_core_api.listen.on('chatRoomInitialized', m => setVCardOnModel(m));
    converse_core_api.listen.on('chatRoomMessageInitialized', m => setVCardOnMUCMessage(m));
    converse_core_api.listen.on('addClientFeatures', () => converse_core_api.disco.own.features.add(converse_vcard_Strophe.NS.VCARD));
    converse_core_api.listen.on('clearSession', () => clearVCardsSession());
    converse_core_api.listen.on('messageInitialized', m => setVCardOnModel(m));
    converse_core_api.listen.on('rosterContactInitialized', m => setVCardOnModel(m));
    converse_core_api.listen.on('statusInitialized', converse_core_converse.initVCardCollection);
    /************************ BEGIN API ************************/

    Object.assign(converse_core_converse.api, {
      /**
       * The XEP-0054 VCard API
       *
       * This API lets you access and update user VCards
       *
       * @namespace _converse.api.vcard
       * @memberOf _converse.api
       */
      'vcard': {
        /**
         * Enables setting new values for a VCard.
         *
         * Sends out an IQ stanza to set the user's VCard and if
         * successful, it updates the {@link _converse.VCard}
         * for the passed in JID.
         *
         * @method _converse.api.vcard.set
         * @param {string} jid The JID for which the VCard should be set
         * @param {object} data A map of VCard keys and values
         * @example
         * _converse.api.vcard.set({
         *     'jid': _converse.bare_jid,
         *     'fn': 'John Doe',
         *     'nickname': 'jdoe'
         * }).then(() => {
         *     // Succes
         * }).catch(() => {
         *     // Failure
         * }).
         */
        async set(jid, data) {
          if (!jid) {
            throw Error("No jid provided for the VCard data");
          }

          const div = document.createElement('div');
          const vcard_el = converse_vcard_u.toStanza(`
                        <vCard xmlns="vcard-temp">
                            <FN>${data.fn}</FN>
                            <NICKNAME>${data.nickname}</NICKNAME>
                            <URL>${data.url}</URL>
                            <ROLE>${data.role}</ROLE>
                            <EMAIL><INTERNET/><PREF/><USERID>${data.email}</USERID></EMAIL>
                            <PHOTO>
                                <TYPE>${data.image_type}</TYPE>
                                <BINVAL>${data.image}</BINVAL>
                            </PHOTO>
                        </vCard>`, div);
          let result;

          try {
            result = await converse_core_api.sendIQ(createStanza("set", jid, vcard_el));
          } catch (e) {
            throw e;
          }

          await converse_core_api.vcard.update(jid, true);
          return result;
        },

        /**
         * @method _converse.api.vcard.get
         * @param {Model|string} model Either a `Model` instance, or a string JID.
         *     If a `Model` instance is passed in, then it must have either a `jid`
         *     attribute or a `muc_jid` attribute.
         * @param {boolean} [force] A boolean indicating whether the vcard should be
         *     fetched even if it's been fetched before.
         * @returns {promise} A Promise which resolves with the VCard data for a particular JID or for
         *     a `Model` instance which represents an entity with a JID (such as a roster contact,
         *     chat or chatroom occupant).
         *
         * @example
         * _converse.api.waitUntil('rosterContactsFetched').then(() => {
         *     _converse.api.vcard.get('someone@example.org').then(
         *         (vcard) => {
         *             // Do something with the vcard...
         *         }
         *     );
         * });
         */
        get(model, force) {
          if (typeof model === 'string') {
            return getVCard(converse_core_converse, model);
          } else if (force || !model.get('vcard_updated') || !converse_vcard_dayjs(model.get('vcard_error')).isSame(new Date(), "day")) {
            const jid = model.get('jid');

            if (!jid) {
              headless_log.error("No JID to get vcard for");
            }

            return getVCard(converse_core_converse, jid);
          } else {
            return Promise.resolve({});
          }
        },

        /**
         * Fetches the VCard associated with a particular `Model` instance
         * (by using its `jid` or `muc_jid` attribute) and then updates the model with the
         * returned VCard data.
         *
         * @method _converse.api.vcard.update
         * @param {Model} model A `Model` instance
         * @param {boolean} [force] A boolean indicating whether the vcard should be
         *     fetched again even if it's been fetched before.
         * @returns {promise} A promise which resolves once the update has completed.
         * @example
         * _converse.api.waitUntil('rosterContactsFetched').then(async () => {
         *     const chatbox = await _converse.chatboxes.getChatBox('someone@example.org');
         *     _converse.api.vcard.update(chatbox);
         * });
         */
        async update(model, force) {
          const data = await this.get(model, force);
          model = typeof model === 'string' ? converse_core_converse.vcards.findWhere({
            'jid': model
          }) : model;

          if (!model) {
            headless_log.error(`Could not find a VCard model for ${model}`);
            return;
          }

          delete data['stanza'];
          model.save(data);
        }

      }
    });
  }

});
// CONCATENATED MODULE: ./src/headless/headless.js
/* START: Removable components
 * --------------------
 * Any of the following components may be removed if they're not needed.
 */
 // XEP-0050 Ad Hoc Commands

 // XEP-0199 XMPP Ping

 // XEP-0206 BOSH

 // XEP-0115 Entity Capabilities

 // XEP-0280 Message Carbons

 // RFC-6121 Instant messaging


 // XEP-0030 Service discovery

 // Support for headline messages

 // XEP-0313 Message Archive Management

 // XEP-0045 Multi-user chat

 // XEP-0199 XMPP Ping

 // XEP-0060 Pubsub

 // RFC-6121 Contacts Roster

 // XEP-0198 Stream Management

 // XEP-0199 XMPP Ping

 // XEP-0054 VCard-temp

/* END: Removable components */


/* harmony default export */ var headless = (converse);
// EXTERNAL MODULE: ./node_modules/jed/jed.js
var jed = __webpack_require__(64);
var jed_default = /*#__PURE__*/__webpack_require__.n(jed);

// CONCATENATED MODULE: ./src/i18n/index.js
/**
 * @module i18n
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description This is the internationalization module
 */





function detectLocale(library_check) {
  /* Determine which locale is supported by the user's system as well
   * as by the relevant library (e.g. converse.js or dayjs).
   * @param { Function } library_check - Returns a boolean indicating whether
   *   the locale is supported.
   */
  let locale;

  if (window.navigator.userLanguage) {
    locale = isLocaleAvailable(window.navigator.userLanguage, library_check);
  }

  if (window.navigator.languages && !locale) {
    for (let i = 0; i < window.navigator.languages.length && !locale; i++) {
      locale = isLocaleAvailable(window.navigator.languages[i], library_check);
    }
  }

  if (window.navigator.browserLanguage && !locale) {
    locale = isLocaleAvailable(window.navigator.browserLanguage, library_check);
  }

  if (window.navigator.language && !locale) {
    locale = isLocaleAvailable(window.navigator.language, library_check);
  }

  if (window.navigator.systemLanguage && !locale) {
    locale = isLocaleAvailable(window.navigator.systemLanguage, library_check);
  }

  return locale || 'en';
}

function isConverseLocale(locale, supported_locales) {
  return typeof locale === 'string' && supported_locales.includes(locale);
}

function getLocale(preferred_locale, isSupportedByLibrary) {
  if (typeof preferred_locale === 'string') {
    if (preferred_locale === 'en' || isSupportedByLibrary(preferred_locale)) {
      return preferred_locale;
    }
  }

  return detectLocale(isSupportedByLibrary) || 'en';
}
/* Check whether the locale or sub locale (e.g. en-US, en) is supported.
 * @param { String } locale - The locale to check for
 * @param { Function } available - Returns a boolean indicating whether the locale is supported
 */


function isLocaleAvailable(locale, available) {
  if (available(locale)) {
    return locale;
  } else {
    var sublocale = locale.split("-")[0];

    if (sublocale !== locale && available(sublocale)) {
      return sublocale;
    }
  }
}
/* Fetch the translations for the given local at the given URL.
 * @private
 * @method i18n#fetchTranslations
 * @param { _converse }
 */


async function fetchTranslations(_converse) {
  const {
    api,
    locale
  } = _converse;
  const dayjs_locale = locale.toLowerCase().replace('_', '-');

  if (!isConverseLocale(locale, api.settings.get("locales")) || locale === 'en') {
    return;
  }

  const {
    default: data
  } = await __webpack_require__(492)(`./${locale}/LC_MESSAGES/converse.po`);
  await __webpack_require__(493)(`./${dayjs_locale}`);
  dayjs_min_default.a.locale(getLocale(dayjs_locale, l => dayjs_min_default.a.locale(l)));
  jed_instance = new jed_default.a(data);
}

let jed_instance;
/**
 * @namespace i18n
 */

Object.assign(i18n, {
  getLocale(preferred_locale, available_locales) {
    return getLocale(preferred_locale, preferred => isConverseLocale(preferred, available_locales));
  },

  translate(str) {
    if (!jed_instance) {
      return jed_default.a.sprintf.apply(jed_default.a, arguments);
    }

    const t = jed_instance.translate(str);

    if (arguments.length > 1) {
      return t.fetch.apply(t, [].slice.call(arguments, 1));
    } else {
      return t.fetch();
    }
  },

  async initialize() {
    if (converse_core_converse.isTestEnv()) {
      converse_core_converse.locale = 'en';
    } else {
      try {
        const preferred_locale = converse_core_api.settings.get('i18n');
        converse_core_converse.locale = i18n.getLocale(preferred_locale, converse_core_api.settings.get("locales"));
        await fetchTranslations(converse_core_converse);
      } catch (e) {
        headless_log.fatal(e.message);
        converse_core_converse.locale = 'en';
      }
    }
  },

  __(...args) {
    return i18n.translate(...args);
  }

});
const i18n_ = i18n.__;
// CONCATENATED MODULE: ./src/converse-registry.js

const registry = {};

function define(name, constructor) {
  this.registry[name] = constructor;
}

function converse_registry_register() {
  Object.keys(registry).forEach(name => {
    if (!customElements.get(name)) {
      customElements.define(name, registry[name]);
    }
  });
}

converse_core_api.elements = {
  registry,
  define,
  register: converse_registry_register
};
// CONCATENATED MODULE: ./src/converse-autocomplete.js
/**
 * @module converse-autocomplete
 * @copyright Lea Verou and the Converse.js contributors
 * @description
 *  Converse.js plugin which started as a fork of Lea Verou's Awesomplete
 *  https://leaverou.github.io/awesomplete/
 * @license Mozilla Public License (MPLv2)
 */


const converse_autocomplete_u = converse.env.utils;
const FILTER_CONTAINS = function (text, input) {
  return RegExp(converse_autocomplete_helpers.regExpEscape(input.trim()), "i").test(text);
};
const FILTER_STARTSWITH = function (text, input) {
  return RegExp("^" + converse_autocomplete_helpers.regExpEscape(input.trim()), "i").test(text);
};

const SORT_BY_LENGTH = function (a, b) {
  if (a.length !== b.length) {
    return a.length - b.length;
  }

  return a < b ? -1 : 1;
};

const SORT_BY_QUERY_POSITION = function (a, b) {
  const query = a.query.toLowerCase();
  const x = a.label.toLowerCase().indexOf(query);
  const y = b.label.toLowerCase().indexOf(query);

  if (x === y) {
    return SORT_BY_LENGTH(a, b);
  }

  return (x === -1 ? Infinity : x) < (y === -1 ? Infinity : y) ? -1 : 1;
};

const ITEM = (text, input) => {
  input = input.trim();
  const element = document.createElement("li");
  element.setAttribute("aria-selected", "false");
  const regex = new RegExp("(" + input + ")", "ig");
  const parts = input ? text.split(regex) : [text];
  parts.forEach(txt => {
    if (input && txt.match(regex)) {
      const match = document.createElement("mark");
      match.textContent = txt;
      element.appendChild(match);
    } else {
      element.appendChild(document.createTextNode(txt));
    }
  });
  return element;
};

const converse_autocomplete_helpers = {
  getElement(expr, el) {
    return typeof expr === "string" ? (el || document).querySelector(expr) : expr || null;
  },

  bind(element, o) {
    if (element) {
      for (var event in o) {
        if (!Object.prototype.hasOwnProperty.call(o, event)) {
          continue;
        }

        const callback = o[event];
        event.split(/\s+/).forEach(event => element.addEventListener(event, callback));
      }
    }
  },

  unbind(element, o) {
    if (element) {
      for (var event in o) {
        if (!Object.prototype.hasOwnProperty.call(o, event)) {
          continue;
        }

        const callback = o[event];
        event.split(/\s+/).forEach(event => element.removeEventListener(event, callback));
      }
    }
  },

  regExpEscape(s) {
    return s.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
  }

};
/**
 * An autocomplete suggestion
 */

class Suggestion extends String {
  /**
   * @param { Any } data - The auto-complete data. Ideally an object e.g. { label, value },
   *      which specifies the value and human-presentable label of the suggestion.
   * @param { string } query - The query string being auto-completed
   */
  constructor(data, query) {
    super();
    const o = Array.isArray(data) ? {
      label: data[0],
      value: data[1]
    } : typeof data === "object" && "label" in data && "value" in data ? data : {
      label: data,
      value: data
    };
    this.label = o.label || o.value;
    this.value = o.value;
    this.query = query;
  }

  get lenth() {
    return this.label.length;
  }

  toString() {
    return "" + this.label;
  }

  valueOf() {
    return this.toString();
  }

}

class converse_autocomplete_AutoComplete {
  constructor(el, config = {}) {
    this.is_opened = false;

    if (converse_autocomplete_u.hasClass('suggestion-box', el)) {
      this.container = el;
    } else {
      this.container = el.querySelector('.suggestion-box');
    }

    this.input = this.container.querySelector('.suggestion-box__input');
    this.input.setAttribute("aria-autocomplete", "list");
    this.ul = this.container.querySelector('.suggestion-box__results');
    this.status = this.container.querySelector('.suggestion-box__additions');
    Object.assign(this, {
      'match_current_word': false,
      // Match only the current word, otherwise all input is matched
      'ac_triggers': [],
      // Array of keys (`ev.key`) values that will trigger auto-complete
      'include_triggers': [],
      // Array of trigger keys which should be included in the returned value
      'min_chars': 2,
      'max_items': 10,
      'auto_evaluate': true,
      // Should evaluation happen automatically without any particular key as trigger?
      'auto_first': false,
      // Should the first element be automatically selected?
      'data': a => a,
      'filter': FILTER_CONTAINS,
      'sort': config.sort === false ? false : SORT_BY_QUERY_POSITION,
      'item': ITEM
    }, config);
    this.index = -1;
    this.bindEvents();

    if (this.input.hasAttribute("list")) {
      this.list = "#" + this.input.getAttribute("list");
      this.input.removeAttribute("list");
    } else {
      this.list = this.input.getAttribute("data-list") || config.list || [];
    }
  }

  bindEvents() {
    // Bind events
    const input = {
      "blur": () => this.close({
        'reason': 'blur'
      })
    };

    if (this.auto_evaluate) {
      input["input"] = () => this.evaluate();
    }

    this._events = {
      'input': input,
      'form': {
        "submit": () => this.close({
          'reason': 'submit'
        })
      },
      'ul': {
        "mousedown": ev => this.onMouseDown(ev),
        "mouseover": ev => this.onMouseOver(ev)
      }
    };
    converse_autocomplete_helpers.bind(this.input, this._events.input);
    converse_autocomplete_helpers.bind(this.input.form, this._events.form);
    converse_autocomplete_helpers.bind(this.ul, this._events.ul);
  }

  set list(list) {
    if (Array.isArray(list) || typeof list === "function") {
      this._list = list;
    } else if (typeof list === "string" && list.includes(",")) {
      this._list = list.split(/\s*,\s*/);
    } else {
      var _helpers$getElement;

      // Element or CSS selector
      const children = ((_helpers$getElement = converse_autocomplete_helpers.getElement(list)) === null || _helpers$getElement === void 0 ? void 0 : _helpers$getElement.children) || [];
      this._list = Array.from(children).filter(el => !el.disabled).map(el => {
        const text = el.textContent.trim();
        const value = el.value || text;
        const label = el.label || text;
        return value !== "" ? {
          label,
          value
        } : null;
      }).filter(i => i);
    }

    if (document.activeElement === this.input) {
      this.evaluate();
    }
  }

  get list() {
    return this._list;
  }

  get selected() {
    return this.index > -1;
  }

  get opened() {
    return this.is_opened;
  }

  close(o) {
    if (!this.opened) {
      return;
    }

    this.ul.setAttribute("hidden", "");
    this.is_opened = false;
    this.index = -1;
    this.trigger("suggestion-box-close", o || {});
  }

  insertValue(suggestion) {
    if (this.match_current_word) {
      converse_autocomplete_u.replaceCurrentWord(this.input, suggestion.value);
    } else {
      this.input.value = suggestion.value;
    }
  }

  open() {
    this.ul.removeAttribute("hidden");
    this.is_opened = true;

    if (this.auto_first && this.index === -1) {
      this.goto(0);
    }

    this.trigger("suggestion-box-open");
  }

  destroy() {
    //remove events from the input and its form
    converse_autocomplete_helpers.unbind(this.input, this._events.input);
    converse_autocomplete_helpers.unbind(this.input.form, this._events.form);
    this.input.removeAttribute("aria-autocomplete");
  }

  next() {
    const count = this.ul.children.length;
    this.goto(this.index < count - 1 ? this.index + 1 : count ? 0 : -1);
  }

  previous() {
    const count = this.ul.children.length,
          pos = this.index - 1;
    this.goto(this.selected && pos !== -1 ? pos : count - 1);
  }

  goto(i) {
    // Should not be used directly, highlights specific item without any checks!
    const list = this.ul.children;

    if (this.selected) {
      list[this.index].setAttribute("aria-selected", "false");
    }

    this.index = i;

    if (i > -1 && list.length > 0) {
      list[i].setAttribute("aria-selected", "true");
      list[i].focus();
      this.status.textContent = list[i].textContent; // scroll to highlighted element in case parent's height is fixed

      this.ul.scrollTop = list[i].offsetTop - this.ul.clientHeight + list[i].clientHeight;
      this.trigger("suggestion-box-highlight", {
        'text': this.suggestions[this.index]
      });
    }
  }

  select(selected) {
    if (selected) {
      this.index = converse_autocomplete_u.siblingIndex(selected);
    } else {
      selected = this.ul.children[this.index];
    }

    if (selected) {
      const suggestion = this.suggestions[this.index];
      this.insertValue(suggestion);
      this.close({
        'reason': 'select'
      });
      this.auto_completing = false;
      this.trigger("suggestion-box-selectcomplete", {
        'text': suggestion
      });
    }
  }

  onMouseOver(ev) {
    const li = converse_autocomplete_u.ancestor(ev.target, 'li');

    if (li) {
      this.goto(Array.prototype.slice.call(this.ul.children).indexOf(li));
    }
  }

  onMouseDown(ev) {
    if (ev.button !== 0) {
      return; // Only select on left click
    }

    const li = converse_autocomplete_u.ancestor(ev.target, 'li');

    if (li) {
      ev.preventDefault();
      this.select(li, ev.target);
    }
  }

  onKeyDown(ev) {
    if (this.opened) {
      if ([converse.keycodes.ENTER, converse.keycodes.TAB].includes(ev.keyCode) && this.selected) {
        ev.preventDefault();
        ev.stopPropagation();
        this.select();
        return true;
      } else if (ev.keyCode === converse.keycodes.ESCAPE) {
        this.close({
          'reason': 'esc'
        });
        return true;
      } else if ([converse.keycodes.UP_ARROW, converse.keycodes.DOWN_ARROW].includes(ev.keyCode)) {
        ev.preventDefault();
        ev.stopPropagation();
        this[ev.keyCode === converse.keycodes.UP_ARROW ? "previous" : "next"]();
        return true;
      }
    }

    if ([converse.keycodes.SHIFT, converse.keycodes.META, converse.keycodes.META_RIGHT, converse.keycodes.ESCAPE, converse.keycodes.ALT].includes(ev.keyCode)) {
      return;
    }

    if (this.ac_triggers.includes(ev.key)) {
      if (ev.key === "Tab") {
        ev.preventDefault();
      }

      this.auto_completing = true;
    } else if (ev.key === "Backspace") {
      const word = converse_autocomplete_u.getCurrentWord(ev.target, ev.target.selectionEnd - 1);

      if (this.ac_triggers.includes(word[0])) {
        this.auto_completing = true;
      }
    }
  }

  async evaluate(ev) {
    const selecting = this.selected && ev && (ev.keyCode === converse.keycodes.UP_ARROW || ev.keyCode === converse.keycodes.DOWN_ARROW);

    if (!this.auto_evaluate && !this.auto_completing || selecting) {
      return;
    }

    const list = typeof this._list === "function" ? await this._list() : this._list;

    if (list.length === 0) {
      return;
    }

    let value = this.match_current_word ? converse_autocomplete_u.getCurrentWord(this.input) : this.input.value;
    const contains_trigger = this.ac_triggers.includes(value[0]);

    if (contains_trigger) {
      this.auto_completing = true;

      if (!this.include_triggers.includes(ev.key)) {
        value = value.slice('1');
      }
    }

    if ((contains_trigger || value.length) && value.length >= this.min_chars) {
      this.index = -1; // Populate list with options that match

      this.ul.innerHTML = "";
      this.suggestions = list.map(item => new Suggestion(this.data(item, value), value)).filter(item => this.filter(item, value));

      if (this.sort !== false) {
        this.suggestions = this.suggestions.sort(this.sort);
      }

      this.suggestions = this.suggestions.slice(0, this.max_items);
      this.suggestions.forEach(text => this.ul.appendChild(this.item(text, value)));

      if (this.ul.children.length === 0) {
        this.close({
          'reason': 'nomatches'
        });
      } else {
        this.open();
      }
    } else {
      this.close({
        'reason': 'nomatches'
      });

      if (!contains_trigger) {
        this.auto_completing = false;
      }
    }
  }

} // Make it an event emitter

Object.assign(converse_autocomplete_AutoComplete.prototype, Events);
converse.plugins.add("converse-autocomplete", {
  initialize() {
    const _converse = this._converse;
    _converse.FILTER_CONTAINS = FILTER_CONTAINS;
    _converse.FILTER_STARTSWITH = FILTER_STARTSWITH;
    _converse.AutoComplete = converse_autocomplete_AutoComplete;
  }

});
// CONCATENATED MODULE: ./src/templates/bookmarks_list.js



const bookmark_item = o => {
  const info_remove_bookmark = i18n_('Unbookmark this groupchat');

  const open_title = i18n_('Click to open this groupchat');

  return lit_html_html`
        <div class="list-item controlbox-padded room-item available-chatroom d-flex flex-row ${o.is_hidden(o.bm) ? 'hidden' : ''}" data-room-jid="${o.bm.get('jid')}">
            <a class="list-item-link open-room w-100" data-room-jid="${o.bm.get('jid')}"
            title="${open_title}"
            @click=${o.openRoom}>${o.bm.getDisplayName()}</a>

            <a class="list-item-action remove-bookmark fa fa-bookmark align-self-center ${o.bm.get('bookmarked') ? 'button-on' : ''}"
            data-room-jid="${o.bm.get('jid')}"
            data-bookmark-name="${o.bm.getDisplayName()}"
            title="${info_remove_bookmark}"
            @click=${o.removeBookmark}></a>
        </div>
    `;
};

/* harmony default export */ var bookmarks_list = (o => {
  const desc_bookmarks = i18n_('Click to toggle the bookmarks list');

  const label_bookmarks = i18n_('Bookmarks');

  return lit_html_html`
        <div class="list-container list-container--bookmarks ${!o.hidden && 'hidden' || ''}">
            <a class="list-toggle bookmarks-toggle controlbox-padded"
            title="${desc_bookmarks}"
            @click=${o.toggleBookmarksList}>

                <span class="fa ${o.toggle_state === o._converse.OPENED ? 'fa-caret-down' : 'fa-caret-right'}">
                </span> ${label_bookmarks}</a>
            <div class="items-list bookmarks rooms-list ${o.toggle_state !== o._converse.OPENED ? 'hidden' : ''}">
            ${o.bookmarks.map(bm => bookmark_item(Object.assign({
    bm
  }, o)))}
            </div>
        </div>
    `;
});
// CONCATENATED MODULE: ./src/templates/muc_bookmark_form.js


/* harmony default export */ var muc_bookmark_form = (o => {
  const i18n_heading = i18n_('Bookmark this groupchat');

  const i18n_autojoin = i18n_('Would you like this groupchat to be automatically joined upon startup?');

  const i18n_cancel = i18n_('Cancel');

  const i18n_name = i18n_('The name for this bookmark:');

  const i18n_nick = i18n_('What should your nickname for this groupchat be?');

  const i18n_submit = i18n_('Save');

  return lit_html_html`
        <form class="converse-form chatroom-form" @submit=${o.onSubmit}>
            <legend>${i18n_heading}</legend>
            <fieldset class="form-group">
                <label for="converse_muc_bookmark_name">${i18n_name}</label>
                <input class="form-control" type="text" value="${o.name}" name="name" required="required" id="converse_muc_bookmark_name"/>
            </fieldset>
            <fieldset class="form-group">
                <label for="converse_muc_bookmark_nick">${i18n_nick}</label>
                <input class="form-control" type="text" name="nick" value="${o.nick || ''}" id="converse_muc_bookmark_nick"/>
            </fieldset>
            <fieldset class="form-group form-check">
                <input class="form-check-input" id="converse_muc_bookmark_autojoin" type="checkbox" name="autojoin"/>
                <label class="form-check-label" for="converse_muc_bookmark_autojoin">${i18n_autojoin}</label>
            </fieldset>
            <fieldset class="form-group">
                <input class="btn btn-primary" type="submit" value="${i18n_submit}">
                <input class="btn btn-secondary button-cancel" type="button" value="${i18n_cancel}" @click=${o.onCancel}>
            </fieldset>
        </form>
    `;
});
// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/view.js
//     Backbone.js 1.4.0
//     (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
//     Backbone may be freely distributed under the MIT license.
// View
// ----
// Views are almost more convention than they are actual code. A View
// is simply a JavaScript object that represents a logical chunk of UI in the
// DOM. This might be a single item, an entire list, a sidebar or panel, or
// even the surrounding frame which wraps your whole app. Defining a chunk of
// UI as a **View** allows you to define your DOM events declaratively, without
// having to worry about render order ... and makes it easy for the view to
// react to specific changes in the state of your models.









const paddedLt = /^\s*</; // Caches a local reference to `Element.prototype` for faster access.

const view_ElementProto = typeof Element !== 'undefined' && Element.prototype || {};

const view_indexOf = function (array, item) {
  for (let i = 0, len = array.length; i < len; i++) if (array[i] === item) return i;

  return -1;
}; // Creating a View creates its initial element outside of the DOM,
// if an existing element is not provided...


const View = function (options) {
  this.cid = lodash_es_uniqueId('view');
  this._domEvents = [];
  this.preinitialize.apply(this, arguments);
  lodash_es_assignIn(this, lodash_es_pick(options, viewOptions));

  this._ensureElement();

  this.initialize.apply(this, arguments);
};
View.extend = inherits; // Cached regex to split keys for `delegate`.

const delegateEventSplitter = /^(\S+)\s*(.*)$/; // List of view options to be set as properties.

const viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; // Set up all inheritable **View** properties and methods.

Object.assign(View.prototype, Events, {
  // The default `tagName` of a View's element is `"div"`.
  tagName: 'div',
  $: function (selector) {
    return this.el.querySelectorAll(selector);
  },
  // preinitialize is an empty function by default. You can override it with a function
  // or object.  preinitialize will run before any instantiation logic is run in the View
  preinitialize: function () {},
  // Initialize is an empty function by default. Override it with your own
  // initialization logic.
  initialize: function () {},
  // **render** is the core function that your view should override, in order
  // to populate its element (`this.el`), with the appropriate HTML. The
  // convention is for **render** to always return `this`.
  render: function () {
    lodash_es_isFunction(this.beforeRender) && this.beforeRender();
    lodash_es_isFunction(this.toHTML) && render_render(this.toHTML(), this.el);
    lodash_es_isFunction(this.afterRender) && this.afterRender();
    return this;
  },
  // Remove this view by taking the element out of the DOM, and removing any
  // applicable Backbone.Events listeners.
  remove: function () {
    this._removeElement();

    this.stopListening();
    return this;
  },
  // Remove this view's element from the document and all event listeners
  // attached to it. Exposed for subclasses using an alternative DOM
  // manipulation API.
  _removeElement: function () {
    this.undelegateEvents();
    if (this.el.parentNode) this.el.parentNode.removeChild(this.el);
  },
  // Change the view's element (`this.el` property) and re-delegate the
  // view's events on the new element.
  setElement: function (element) {
    this.undelegateEvents();

    this._setElement(element);

    this.delegateEvents();
    return this;
  },
  // Apply the `element` to the view. `element` can be a CSS selector,
  // a string of HTML, or an Element node. If passed a NodeList or CSS
  // selector, uses just the first match.
  _setElement: function (element) {
    if (typeof element == 'string') {
      if (paddedLt.test(element)) {
        const el = document.createElement('div');
        el.innerHTML = element;
        this.el = el.firstChild;
      } else {
        this.el = document.querySelector(element);
      }
    } else if (element && !lodash_es_isElement(element) && element.length) {
      this.el = element[0];
    } else {
      this.el = element;
    }
  },
  // Set callbacks, where `this.events` is a hash of
  //
  // *{"event selector": "callback"}*
  //
  //     {
  //       'mousedown .title':  'edit',
  //       'click .button':     'save',
  //       'click .open':       function(e) { ... }
  //     }
  //
  // pairs. Callbacks will be bound to the view, with `this` set properly.
  // Uses event delegation for efficiency.
  // Omitting the selector binds the event to `this.el`.
  delegateEvents: function (events) {
    events || (events = lodash_es_result(this, 'events'));
    if (!events) return this;
    this.undelegateEvents();

    for (const key in events) {
      let method = events[key];
      if (!lodash_es_isFunction(method)) method = this[method];
      if (!method) continue;
      const match = key.match(delegateEventSplitter);
      this.delegate(match[1], match[2], method.bind(this));
    }

    return this;
  },
  // Make a event delegation handler for the given `eventName` and `selector`
  // and attach it to `this.el`.
  // If selector is empty, the listener will be bound to `this.el`. If not, a
  // new handler that will recursively traverse up the event target's DOM
  // hierarchy looking for a node that matches the selector. If one is found,
  // the event's `delegateTarget` property is set to it and the return the
  // result of calling bound `listener` with the parameters given to the
  // handler.
  delegate: function (eventName, selector, listener) {
    const root = this.el;

    if (!root) {
      return this;
    }

    if (typeof selector === 'function') {
      listener = selector;
      selector = null;
    } // Given that `focus` and `blur` events do not bubble, do not delegate these events


    if (['focus', 'blur'].indexOf(eventName) !== -1) {
      const els = this.el.querySelectorAll(selector);

      for (let i = 0, len = els.length; i < len; i++) {
        const item = els[i];
        item.addEventListener(eventName, listener, false);

        this._domEvents.push({
          el: item,
          eventName: eventName,
          handler: listener
        });
      }

      return listener;
    }

    const handler = selector ? function (e) {
      let node = e.target || e.srcElement;

      for (; node && node != root; node = node.parentNode) {
        if (node.matches(selector)) {
          e.delegateTarget = node;
          listener(e);
        }
      }
    } : listener;
    this.el.addEventListener(eventName, handler, false);

    this._domEvents.push({
      el: this.el,
      eventName: eventName,
      handler: handler,
      listener: listener,
      selector: selector
    });

    return this;
  },
  // Clears all callbacks previously bound to the view by `delegateEvents`.
  // You usually don't need to use this, but may wish to if you have multiple
  // Backbone views attached to the same DOM element.
  undelegateEvents: function () {
    if (this.el) {
      for (let i = 0, len = this._domEvents.length; i < len; i++) {
        const item = this._domEvents[i];
        item.el.removeEventListener(item.eventName, item.handler, false);
      }

      this._domEvents.length = 0;
    }

    return this;
  },
  // A finer-grained `undelegateEvents` for removing a single delegated event.
  // `selector` and `listener` are both optional.
  undelegate: function (eventName, selector, listener) {
    if (typeof selector === 'function') {
      listener = selector;
      selector = null;
    }

    if (this.el) {
      const handlers = this._domEvents.slice();

      let i = handlers.length;

      while (i--) {
        const item = handlers[i];
        const match = item.eventName === eventName && (listener ? item.listener === listener : true) && (selector ? item.selector === selector : true);

        if (!match) {
          continue;
        }

        item.el.removeEventListener(item.eventName, item.handler, false);

        this._domEvents.splice(i, 1);
      }
    }

    return this;
  },
  // Produces a DOM element to be assigned to your view. Exposed for
  // subclasses using an alternative DOM manipulation API.
  _createElement: function (tagName) {
    return document.createElement(tagName);
  },
  // Ensure that the View has a DOM element to render into.
  // If `this.el` is a string, pass it through `$()`, take the first
  // matching element, and re-assign it to `el`. Otherwise, create
  // an element from the `id`, `className` and `tagName` properties.
  _ensureElement: function () {
    if (!this.el) {
      const attrs = lodash_es_assignIn({}, lodash_es_result(this, 'attributes'));
      if (this.id) attrs.id = lodash_es_result(this, 'id');
      if (this.className) attrs['class'] = lodash_es_result(this, 'className');
      this.setElement(this._createElement(lodash_es_result(this, 'tagName')));

      this._setAttributes(attrs);
    } else {
      this.setElement(lodash_es_result(this, 'el'));
    }
  },
  // Set attributes from a hash on this view's element.  Exposed for
  // subclasses using an alternative DOM manipulation API.
  _setAttributes: function (attrs) {
    for (const attr in attrs) {
      attr in this.el ? this.el[attr] = attrs[attr] : this.el.setAttribute(attr, attrs[attr]);
    }
  }
});
// CONCATENATED MODULE: ./node_modules/lodash-es/invokeMap.js





/**
 * Invokes the method at `path` of each element in `collection`, returning
 * an array of the results of each invoked method. Any additional arguments
 * are provided to each invoked method. If `path` is a function, it's invoked
 * for, and `this` bound to, each element in `collection`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Array|Function|string} path The path of the method to invoke or
 *  the function invoked per iteration.
 * @param {...*} [args] The arguments to invoke each method with.
 * @returns {Array} Returns the array of results.
 * @example
 *
 * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
 * // => [[1, 5, 7], [1, 2, 3]]
 *
 * _.invokeMap([123, 456], String.prototype.split, '');
 * // => [['1', '2', '3'], ['4', '5', '6']]
 */

var invokeMap = _baseRest(function (collection, path, args) {
  var index = -1,
      isFunc = typeof path == 'function',
      result = lodash_es_isArrayLike(collection) ? Array(collection.length) : [];
  _baseEach(collection, function (value) {
    result[++index] = isFunc ? _apply(path, value, args) : _baseInvoke(value, path, args);
  });
  return result;
});
/* harmony default export */ var lodash_es_invokeMap = (invokeMap);
// CONCATENATED MODULE: ./src/converse-bookmark-views.js
/**
 * @module converse-bookmark-views
 * @description Converse.js plugin which adds views for XEP-0048 bookmarks
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */








const {
  Strophe: converse_bookmark_views_Strophe
} = converse.env;
const converse_bookmark_views_u = converse.env.utils;
converse.plugins.add('converse-bookmark-views', {
  /* Plugin dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin.
   *
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found. By default it's
   * false, which means these plugins are only loaded opportunistically.
   *
   * NB: These plugins need to have already been loaded via require.js.
   */
  dependencies: ["converse-chatboxes", "converse-muc", "converse-muc-views"],

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    // Configuration values for this plugin
    // ====================================
    // Refer to docs/source/configuration.rst for explanations of these
    // configuration settings.
    converse_core_api.settings.extend({
      hide_open_bookmarks: true
    });
    Object.assign(converse_core_converse, {
      removeBookmarkViaEvent(ev) {
        /* Remove a bookmark as determined by the passed in
         * event.
         */
        ev.preventDefault();
        const name = ev.target.getAttribute('data-bookmark-name');
        const jid = ev.target.getAttribute('data-room-jid');

        if (confirm(i18n_("Are you sure you want to remove the bookmark \"%1$s\"?", name))) {
          lodash_es_invokeMap(converse_core_converse.bookmarks.where({
            'jid': jid
          }), model_Model.prototype.destroy);
        }
      },

      addBookmarkViaEvent(ev) {
        /* Add a bookmark as determined by the passed in
         * event.
         */
        ev.preventDefault();
        const jid = ev.target.getAttribute('data-room-jid');
        converse_core_api.rooms.open(jid, {
          'bring_to_foreground': true
        });

        converse_core_converse.chatboxviews.get(jid).renderBookmarkForm();
      }

    });
    const bookmarkableChatRoomView = {
      /**
       * Set whether the groupchat is bookmarked or not.
       * @private
       */
      setBookmarkState() {
        if (converse_core_converse.bookmarks !== undefined) {
          const models = converse_core_converse.bookmarks.where({
            'jid': this.model.get('jid')
          });

          if (!models.length) {
            this.model.save('bookmarked', false);
          } else {
            this.model.save('bookmarked', true);
          }
        }
      },

      renderBookmarkForm() {
        this.hideChatRoomContents();

        if (!this.bookmark_form) {
          this.bookmark_form = new converse_core_converse.MUCBookmarkForm({
            'model': this.model,
            'chatroomview': this
          });
          const container_el = this.el.querySelector('.chatroom-body');
          container_el.insertAdjacentElement('beforeend', this.bookmark_form.el);
        }

        converse_bookmark_views_u.showElement(this.bookmark_form.el);
      },

      toggleBookmark(ev) {
        ev === null || ev === void 0 ? void 0 : ev.preventDefault();

        const models = converse_core_converse.bookmarks.where({
          'jid': this.model.get('jid')
        });

        if (!models.length) {
          this.renderBookmarkForm();
        } else {
          models.forEach(model => model.destroy());
        }
      }

    };
    Object.assign(converse_core_converse.ChatRoomView.prototype, bookmarkableChatRoomView);
    converse_core_converse.MUCBookmarkForm = View.extend({
      className: 'muc-bookmark-form chatroom-form-container',

      initialize(attrs) {
        this.chatroomview = attrs.chatroomview;
        this.render();
      },

      toHTML() {
        return muc_bookmark_form(Object.assign(this.model.toJSON(), {
          'onCancel': ev => this.closeBookmarkForm(ev),
          'onSubmit': ev => this.onBookmarkFormSubmitted(ev)
        }));
      },

      onBookmarkFormSubmitted(ev) {
        var _ev$target$querySelec, _ev$target$querySelec2, _ev$target$querySelec3;

        ev.preventDefault();

        converse_core_converse.bookmarks.createBookmark({
          'jid': this.model.get('jid'),
          'autojoin': ((_ev$target$querySelec = ev.target.querySelector('input[name="autojoin"]')) === null || _ev$target$querySelec === void 0 ? void 0 : _ev$target$querySelec.checked) || false,
          'name': (_ev$target$querySelec2 = ev.target.querySelector('input[name=name]')) === null || _ev$target$querySelec2 === void 0 ? void 0 : _ev$target$querySelec2.value,
          'nick': (_ev$target$querySelec3 = ev.target.querySelector('input[name=nick]')) === null || _ev$target$querySelec3 === void 0 ? void 0 : _ev$target$querySelec3.value
        });

        this.closeBookmarkForm(ev);
      },

      closeBookmarkForm(ev) {
        ev.preventDefault();
        this.chatroomview.closeForm();
      }

    });
    converse_core_converse.BookmarksView = View.extend({
      tagName: 'span',

      initialize() {
        this.listenTo(this.model, 'add', this.render);
        this.listenTo(this.model, 'remove', this.render);
        this.listenTo(converse_core_converse.chatboxes, 'add', this.render);
        this.listenTo(converse_core_converse.chatboxes, 'remove', this.render);
        const id = `converse.room-bookmarks${converse_core_converse.bare_jid}-list-model`;
        this.list_model = new converse_core_converse.BookmarksList({
          id
        });
        this.list_model.browserStorage = converse_core_converse.createStore(id);

        const render = () => {
          this.render();
          this.insertIntoControlBox();
        };

        this.list_model.fetch({
          'success': render,
          'error': render
        });
      },

      toHTML() {
        const is_hidden = b => !!(converse_core_api.settings.get('hide_open_bookmarks') && converse_core_converse.chatboxes.get(b.get('jid')));

        return bookmarks_list({
          '_converse': converse_core_converse,
          'bookmarks': this.model,
          'hidden': this.model.getUnopenedBookmarks().length && true,
          'is_hidden': is_hidden,
          'openRoom': ev => this.openRoom(ev),
          'removeBookmark': ev => this.removeBookmark(ev),
          'toggleBookmarksList': ev => this.toggleBookmarksList(ev),
          'toggle_state': this.list_model.get('toggle-state')
        });
      },

      insertIntoControlBox() {
        const controlboxview = converse_core_converse.chatboxviews.get('controlbox');

        if (controlboxview !== undefined && !converse_bookmark_views_u.rootContains(converse_core_converse.root, this.el)) {
          const el = controlboxview.el.querySelector('.list-container--bookmarks');
          el && el.parentNode.replaceChild(this.el, el);
        }
      },

      openRoom(ev) {
        ev.preventDefault();
        const name = ev.target.textContent;
        const jid = ev.target.getAttribute('data-room-jid');
        const data = {
          'name': name || converse_bookmark_views_Strophe.unescapeNode(converse_bookmark_views_Strophe.getNodeFromJid(jid)) || jid
        };
        converse_core_api.rooms.open(jid, data, true);
      },

      removeBookmark: converse_core_converse.removeBookmarkViaEvent,

      toggleBookmarksList(ev) {
        if (ev && ev.preventDefault) {
          ev.preventDefault();
        }

        const icon_el = ev.target.matches('.fa') ? ev.target : ev.target.querySelector('.fa');

        if (converse_bookmark_views_u.hasClass('fa-caret-down', icon_el)) {
          converse_bookmark_views_u.slideIn(this.el.querySelector('.bookmarks'));
          this.list_model.save({
            'toggle-state': converse_core_converse.CLOSED
          });
          icon_el.classList.remove("fa-caret-down");
          icon_el.classList.add("fa-caret-right");
        } else {
          icon_el.classList.remove("fa-caret-right");
          icon_el.classList.add("fa-caret-down");
          converse_bookmark_views_u.slideOut(this.el.querySelector('.bookmarks'));
          this.list_model.save({
            'toggle-state': converse_core_converse.OPENED
          });
        }
      }

    });
    /************************ BEGIN Event Handlers ************************/

    const initBookmarkViews = async function () {
      await converse_core_api.waitUntil('roomsPanelRendered');
      converse_core_converse.bookmarksview = new converse_core_converse.BookmarksView({
        'model': converse_core_converse.bookmarks
      });
      /**
       * Triggered once the _converse.Bookmarks collection and _converse.BookmarksView view
       * has been created and cached bookmarks have been fetched.
       * @event _converse#bookmarkViewsInitialized
       * @example _converse.api.listen.on('bookmarkViewsInitialized', () => { ... });
       */

      converse_core_api.trigger('bookmarkViewsInitialized');
    };

    converse_core_api.listen.on('getHeadingButtons', (view, buttons) => {
      if (converse_core_converse.allow_bookmarks && view.model.get('type') === converse_core_converse.CHATROOMS_TYPE) {
        const bookmarked = view.model.get('bookmarked');
        const data = {
          'i18n_title': bookmarked ? i18n_('Unbookmark this groupchat') : i18n_('Bookmark this groupchat'),
          'i18n_text': bookmarked ? i18n_('Unbookmark') : i18n_('Bookmark'),
          'handler': ev => view.toggleBookmark(ev),
          'a_class': 'toggle-bookmark',
          'icon_class': 'fa-bookmark',
          'name': 'bookmark'
        };
        const names = buttons.map(t => t.name);
        const idx = names.indexOf('details');

        const data_promise = converse_core_converse.checkBookmarksSupport().then(s => s ? data : '');

        return idx > -1 ? [...buttons.slice(0, idx), data_promise, ...buttons.slice(idx)] : [data_promise, ...buttons];
      }

      return buttons;
    });
    converse_core_api.listen.on('bookmarksInitialized', initBookmarkViews);
    converse_core_api.listen.on('chatRoomViewInitialized', view => view.setBookmarkState());
    /************************ END Event Handlers ************************/
  }

});
// EXTERNAL MODULE: ./node_modules/bootstrap.native/dist/bootstrap-native.js
var bootstrap_native = __webpack_require__(30);
var bootstrap_native_default = /*#__PURE__*/__webpack_require__.n(bootstrap_native);

// CONCATENATED MODULE: ./src/templates/alert.js

/* harmony default export */ var templates_alert = (o => lit_html_html`<div class="alert ${o.type}" role="alert"><p>${o.message}</p></div>`);
// CONCATENATED MODULE: ./src/templates/buttons.js


const modal_close_button = lit_html_html`<button type="button" class="btn btn-secondary" data-dismiss="modal">${i18n_('Close')}</button>`;
const modal_header_close_button = lit_html_html`<button type="button" class="close" data-dismiss="modal" aria-label="${i18n_('Close')}"><span aria-hidden="true">×</span></button>`;
// CONCATENATED MODULE: ./src/templates/alert_modal.js


/* harmony default export */ var alert_modal = (o => lit_html_html`
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header ${o.level}">
              <h5 class="modal-title">${o.title}</h5>
              ${modal_header_close_button}
            </div>
            <div class="modal-body">
              <span class="modal-alert"></span>
              ${o.messages.map(message => lit_html_html`<p>${message}</p>`)}
            </div>
        </div>
    </div>
`);
// CONCATENATED MODULE: ./src/templates/prompt.js



const tpl_field = f => lit_html_html`
    <div class="form-group">
        <label>
            ${f.label || ''}
            <input type="text"
                name="${f.name}"
                class="${f.challenge_failed ? 'error' : ''} form-control form-control--labeled"
                ?required="${f.required}"
                placeholder="${f.placeholder}" />
        </label>
    </div>
`;

/* harmony default export */ var templates_prompt = (o => lit_html_html`
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header ${o.level || ''}">
          <h5 class="modal-title">${o.title}</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">×</span>
          </button>
        </div>
        <div class="modal-body">
            <span class="modal-alert"></span>
            <form class="converse-form converse-form--modal confirm" action="#">
              <div class="form-group">
                  ${o.messages.map(message => lit_html_html`<p>${message}</p>`)}
              </div>
              ${o.fields.map(f => tpl_field(f))}
              <div class="form-group">
                  <button type="submit" class="btn btn-primary">${i18n_('OK')}</button>
                  <input type="button" class="btn btn-secondary" data-dismiss="modal" value="${i18n_('Cancel')}"/>
              </div>
          </form>
        </div>
      </div>
    </div>
`);
// CONCATENATED MODULE: ./src/converse-modal.js
/**
 * @module converse-modal
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */










const {
  sizzle: converse_modal_sizzle
} = converse.env;
const converse_modal_u = converse.env.utils;

let converse_modal_converse;

const BootstrapModal = View.extend({
  className: "modal",
  events: {
    'click  .nav-item .nav-link': 'switchTab'
  },

  initialize() {
    this.render();
    this.el.setAttribute('tabindex', '-1');
    this.el.setAttribute('role', 'dialog');
    this.el.setAttribute('aria-hidden', 'true');
    const label_id = this.el.querySelector('.modal-title').getAttribute('id');
    label_id && this.el.setAttribute('aria-labelledby', label_id);
    this.insertIntoDOM();
    const Modal = bootstrap_native_default.a.Modal;
    this.modal = new Modal(this.el, {
      backdrop: true,
      keyboard: true
    });
    this.el.addEventListener('hide.bs.modal', () => converse_modal_u.removeClass('selected', this.trigger_el), false);
  },

  insertIntoDOM() {
    const container_el = converse_modal_converse.chatboxviews.el.querySelector("#converse-modals");

    container_el.insertAdjacentElement('beforeEnd', this.el);
  },

  switchTab(ev) {
    ev.stopPropagation();
    ev.preventDefault();
    converse_modal_sizzle('.nav-link.active', this.el).forEach(el => {
      converse_modal_u.removeClass('active', this.el.querySelector(el.getAttribute('href')));
      converse_modal_u.removeClass('active', el);
    });
    converse_modal_u.addClass('active', ev.target);
    converse_modal_u.addClass('active', this.el.querySelector(ev.target.getAttribute('href')));
  },

  alert(message, type = 'primary') {
    const body = this.el.querySelector('.modal-alert');

    if (body === null) {
      headless_log.error("Could not find a .modal-alert element in the modal to show an alert message in!");
      return;
    } // FIXME: Instead of adding the alert imperatively, we should
    // find a way to let the modal rerender with an alert message


    render_render(templates_alert({
      'type': `alert-${type}`,
      'message': message
    }), body);
    const el = body.firstElementChild;
    setTimeout(() => {
      converse_modal_u.addClass('fade-out', el);
      setTimeout(() => converse_modal_u.removeElement(el), 600);
    }, 5000);
  },

  show(ev) {
    if (ev) {
      ev.preventDefault();
      this.trigger_el = ev.target;
      this.trigger_el.classList.add('selected');
    }

    this.modal.show();
  }

});
converse.env.BootstrapModal = BootstrapModal; // expose to plugins

const Confirm = BootstrapModal.extend({
  events: {
    'submit .confirm': 'onConfimation'
  },

  initialize() {
    this.confirmation = converse_modal_u.getResolveablePromise();
    BootstrapModal.prototype.initialize.apply(this, arguments);
    this.listenTo(this.model, 'change', this.render);
    this.el.addEventListener('closed.bs.modal', () => this.confirmation.reject(), false);
  },

  toHTML() {
    return templates_prompt(this.model.toJSON());
  },

  afterRender() {
    if (!this.close_handler_registered) {
      this.el.addEventListener('closed.bs.modal', () => {
        if (!this.confirmation.isResolved) {
          this.confirmation.reject();
        }
      }, false);
      this.close_handler_registered = true;
    }
  },

  onConfimation(ev) {
    ev.preventDefault();
    const form_data = new FormData(ev.target);
    const fields = (this.model.get('fields') || []).map(field => {
      const value = form_data.get(field.name).trim();
      field.value = value;

      if (field.challenge) {
        field.challenge_failed = value !== field.challenge;
      }

      return field;
    });

    if (fields.filter(c => c.challenge_failed).length) {
      this.model.set('fields', fields); // Setting an array doesn't trigger a change event

      this.model.trigger('change');
      return;
    }

    this.confirmation.resolve(fields);
    this.modal.hide();
  }

});
const Alert = BootstrapModal.extend({
  initialize() {
    BootstrapModal.prototype.initialize.apply(this, arguments);
    this.listenTo(this.model, 'change', this.render);
  },

  toHTML() {
    return alert_modal(Object.assign({
      __: i18n_
    }, this.model.toJSON()));
  }

});
converse.plugins.add('converse-modal', {
  initialize() {
    converse_modal_converse = this._converse;
    /************************ BEGIN Event Listeners ************************/

    converse_modal_converse.api.listen.on('disconnect', () => {
      const container = document.querySelector("#converse-modals");

      if (container) {
        container.innerHTML = '';
      }
    });
    /************************ BEGIN API ************************/
    // We extend the default converse.js API to add methods specific to MUC chat rooms.


    let alert;
    Object.assign(converse_modal_converse.api, {
      /**
       * Show a confirm modal to the user.
       * @method _converse.api.confirm
       * @param { String } title - The header text for the confirmation dialog
       * @param { (String[]|String) } messages - The text to show to the user
       * @param { Array<Field> } fields - An object representing a fields presented to the user.
       * @property { String } Field.label - The form label for the input field.
       * @property { String } Field.name - The name for the input field.
       * @property { String } [Field.challenge] - A challenge value that must be provided by the user.
       * @property { String } [Field.placeholder] - The placeholder for the input field.
       * @property { Boolean} [Field.required] - Whether the field is required or not
       * @returns { Promise<Array|false> } A promise which resolves with an array of
       *  filled in fields or `false` if the confirm dialog was closed or canceled.
       */
      async confirm(title, messages = [], fields = []) {
        if (typeof messages === 'string') {
          messages = [messages];
        }

        const model = new model_Model({
          title,
          messages,
          fields,
          'type': 'confirm'
        });
        const confirm = new Confirm({
          model
        });
        confirm.show();
        let result;

        try {
          result = await confirm.confirmation;
        } catch (e) {
          result = false;
        }

        confirm.remove();
        return result;
      },

      /**
       * Show a prompt modal to the user.
       * @method _converse.api.prompt
       * @param { String } title - The header text for the prompt
       * @param { (String[]|String) } messages - The prompt text to show to the user
       * @param { String } placeholder - The placeholder text for the prompt input
       * @returns { Promise<String|false> } A promise which resolves with the text provided by the
       *  user or `false` if the user canceled the prompt.
       */
      async prompt(title, messages = [], placeholder = '') {
        if (typeof messages === 'string') {
          messages = [messages];
        }

        const model = new model_Model({
          title,
          messages,
          'fields': [{
            'name': 'reason',
            'placeholder': placeholder
          }],
          'type': 'prompt'
        });
        const prompt = new Confirm({
          model
        });
        prompt.show();
        let result;

        try {
          var _await$prompt$confirm;

          result = (_await$prompt$confirm = (await prompt.confirmation).pop()) === null || _await$prompt$confirm === void 0 ? void 0 : _await$prompt$confirm.value;
        } catch (e) {
          result = false;
        }

        prompt.remove();
        return result;
      },

      /**
       * Show an alert modal to the user.
       * @method _converse.api.alert
       * @param { ('info'|'warn'|'error') } type - The type of alert.
       * @param { String } title - The header text for the alert.
       * @param { (String[]|String) } messages - The alert text to show to the user.
       */
      alert(type, title, messages) {
        if (typeof messages === 'string') {
          messages = [messages];
        }

        let level;

        if (type === 'error') {
          level = 'alert-danger';
        } else if (type === 'info') {
          level = 'alert-info';
        } else if (type === 'warn') {
          level = 'alert-warning';
        }

        if (alert === undefined) {
          const model = new model_Model({
            'title': title,
            'messages': messages,
            'level': level,
            'type': 'alert'
          });
          alert = new Alert({
            model
          });
        } else {
          alert.model.set({
            'title': title,
            'messages': messages,
            'level': level
          });
        }

        alert.show();
      }

    });
  }

});
// CONCATENATED MODULE: ./src/templates/image_modal.js



/* harmony default export */ var image_modal = (o => {
  return lit_html_html`
        <div class="modal-dialog fit-content" role="document">
            <div class="modal-content fit-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="message-versions-modal-label">${i18n_('Image: ')}<a target="_blank" rel="noopener" href="${o.src}">${o.src}</a></h4>
                    ${modal_header_close_button}
                </div>
                <div class="modal-body modal-body--image fit-content">
                    <img class="chat-image" src="${o.src}" @load=${o.onload}>
                </div>
                <div class="modal-footer">${modal_close_button}</div>
            </div>
        </div>`;
});
// CONCATENATED MODULE: ./src/modals/image.js


/* harmony default export */ var modals_image = (BootstrapModal.extend({
  toHTML() {
    return image_modal({
      'src': this.src,
      'onload': ev => ev.target.parentElement.style.height = `${ev.target.height}px`
    });
  }

}));
// CONCATENATED MODULE: ./src/components/element.js


class element_CustomElement extends lit_element_LitElement {
  constructor() {
    super();
    Object.assign(this, Events);
  }

  createRenderRoot() {
    // Render without the shadow DOM
    return this;
  }

  disconnectedCallback() {
    super.disconnectedCallback();
    this.stopListening();
  }

}
// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js
var URI = __webpack_require__(31);
var URI_default = /*#__PURE__*/__webpack_require__.n(URI);

// CONCATENATED MODULE: ./node_modules/lit-html/directives/until.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */



const _state = new WeakMap(); // Effectively infinity, but a SMI.


const _infinity = 0x7fffffff;
/**
 * Renders one of a series of values, including Promises, to a Part.
 *
 * Values are rendered in priority order, with the first argument having the
 * highest priority and the last argument having the lowest priority. If a
 * value is a Promise, low-priority values will be rendered until it resolves.
 *
 * The priority of values can be used to create placeholder content for async
 * data. For example, a Promise with pending content can be the first,
 * highest-priority, argument, and a non_promise loading indicator template can
 * be used as the second, lower-priority, argument. The loading indicator will
 * render immediately, and the primary content will render when the Promise
 * resolves.
 *
 * Example:
 *
 *     const content = fetch('./content.txt').then(r => r.text());
 *     html`${until(content, html`<span>Loading...</span>`)}`
 */

const until = directive_directive((...args) => part => {
  let state = _state.get(part);

  if (state === undefined) {
    state = {
      lastRenderedIndex: _infinity,
      values: []
    };

    _state.set(part, state);
  }

  const previousValues = state.values;
  let previousLength = previousValues.length;
  state.values = args;

  for (let i = 0; i < args.length; i++) {
    // If we've rendered a higher-priority value already, stop.
    if (i > state.lastRenderedIndex) {
      break;
    }

    const value = args[i]; // Render non-Promise values immediately

    if (isPrimitive(value) || typeof value.then !== 'function') {
      part.setValue(value);
      state.lastRenderedIndex = i; // Since a lower-priority value will never overwrite a higher-priority
      // synchronous value, we can stop processing now.

      break;
    } // If this is a Promise we've already handled, skip it.


    if (i < previousLength && value === previousValues[i]) {
      continue;
    } // We have a Promise that we haven't seen before, so priorities may have
    // changed. Forget what we rendered before.


    state.lastRenderedIndex = _infinity;
    previousLength = 0;
    Promise.resolve(value).then(resolvedValue => {
      const index = state.values.indexOf(value); // If state.values doesn't contain the value, we've re-rendered without
      // the value, so don't render it. Then, only render if the value is
      // higher-priority than what's already been rendered.

      if (index > -1 && index < state.lastRenderedIndex) {
        state.lastRenderedIndex = index;
        part.setValue(resolvedValue);
        part.commit();
      }
    });
  }
});
// CONCATENATED MODULE: ./src/templates/directives/body.js






const body_u = converse.env.utils;
/**
 * @class MessageText
 * A String subclass that is used to represent the rich text
 * of a chat message.
 *
 * The "rich" parts of the text is represented by lit-html TemplateResult
 * objects which are added via the {@link MessageText.addTemplateResult}
 * method and saved as metadata.
 *
 * By default Converse adds TemplateResults to support emojis, hyperlinks,
 * images, map URIs and mentions.
 *
 * 3rd party plugins can listen for the `beforeMessageBodyTransformed`
 * and/or `afterMessageBodyTransformed` events and then call
 * `addTemplateResult` on the MessageText instance in order to add their own
 * rich features.
 */

class body_MessageText extends String {
  /**
   * Create a new {@link MessageText} instance.
   * @param { String } text - The plain text that was received from the `<message>` stanza.
   */
  constructor(text) {
    super(text);
    this.references = [];
  }
  /**
   * The "rich" markup parts of a chat message are represented by lit-html
   * TemplateResult objects.
   *
   * This method can be used to add new template results to this message's
   * text.
   *
   * @method MessageText.addTemplateResult
   * @param { Number } begin - The starting index of the plain message text
   * which is being replaced with markup.
   * @param { Number } end - The ending index of the plain message text
   * which is being replaced with markup.
   * @param { Object } template - The lit-html TemplateResult instance
   */


  addTemplateResult(begin, end, template) {
    this.references.push({
      begin,
      end,
      template
    });
  }

  isMeCommand() {
    const text = this.toString();

    if (!text) {
      return false;
    }

    return text.startsWith('/me ');
  }

  static replaceText(text) {
    return convertASCII2Emoji(text.replace(/\n\n+/g, '\n\n'));
  }

  marshall() {
    let list = [this.toString()];
    this.references.sort((a, b) => b.begin - a.begin).forEach(ref => {
      const text = list.shift();
      list = [text.slice(0, ref.begin), ref.template, text.slice(ref.end), ...list];
    }); // Subtract `/me ` from 3rd person messages

    if (this.isMeCommand()) list[0] = list[0].substring(4);

    const isString = s => typeof s === 'string';

    return list.reduce((acc, i) => isString(i) ? [...acc, body_MessageText.replaceText(i)] : [...acc, i], []);
  }

}

function addMapURLs(text) {
  const regex = /geo:([\-0-9.]+),([\-0-9.]+)(?:,([\-0-9.]+))?(?:\?(.*))?/g;
  const matches = text.matchAll(regex);

  for (const m of matches) {
    text.addTemplateResult(m.index, m.index + m.input.length, body_u.convertUrlToHyperlink(m.input.replace(regex, converse_core_converse.geouri_replacement)));
  }
}

function addHyperlinks(text, onImgLoad, onImgClick) {
  const objs = [];

  try {
    const parse_options = {
      'start': /\b(?:([a-z][a-z0-9.+-]*:\/\/)|xmpp:|mailto:|www\.)/gi
    };
    URI_default.a.withinString(text, (url, start, end) => {
      objs.push({
        url,
        start,
        end
      });
      return url;
    }, parse_options);
  } catch (error) {
    headless_log.debug(error);
    return;
  }

  const show_images = converse_core_api.settings.get('show_images_inline');
  objs.forEach(url_obj => {
    const url_text = text.slice(url_obj.start, url_obj.end);
    const filtered_url = body_u.filterQueryParamsFromURL(url_text);
    text.addTemplateResult(url_obj.start, url_obj.end, show_images && body_u.isImageURL(url_text) && body_u.isImageDomainAllowed(url_text) ? body_u.convertToImageTag(filtered_url, onImgLoad, onImgClick) : body_u.convertUrlToHyperlink(filtered_url));
  });
}

async function addEmojis(text) {
  await converse_core_api.emojis.initialize();
  const references = [...getShortnameReferences(text.toString()), ...getCodePointReferences(text.toString())];
  references.forEach(e => {
    text.addTemplateResult(e.begin, e.end, getEmojiMarkup(e, {
      'add_title_wrapper': true
    }));
  });
}

const tpl_mention_with_nick = o => lit_html_html`<span class="mention mention--self badge badge-info">${o.mention}</span>`;

const tpl_mention = o => lit_html_html`<span class="mention">${o.mention}</span>`;

function addReferences(text, model) {
  var _model$get;

  if (!model.collection) {
    // This model doesn't belong to a collection anymore, so it must be
    // have been removed in the meantime and can be ignored.
    headless_log.debug('addReferences: ignoring dangling model');
    return;
  }

  const nick = model.collection.chatbox.get('nick');
  (_model$get = model.get('references')) === null || _model$get === void 0 ? void 0 : _model$get.forEach(ref => {
    const mention = text.slice(ref.begin, ref.end);

    if (mention === nick) {
      text.addTemplateResult(ref.begin, ref.end, tpl_mention_with_nick({
        mention
      }));
    } else {
      text.addTemplateResult(ref.begin, ref.end, tpl_mention({
        mention
      }));
    }
  });
}

class body_MessageBodyRenderer {
  constructor(component) {
    var _u$ancestor;

    this.model = component.model;
    this.component = component;
    this.chatview = (_u$ancestor = body_u.ancestor(this.component, 'converse-chat-message')) === null || _u$ancestor === void 0 ? void 0 : _u$ancestor.chatview; // We jot down whether we were scrolled down before rendering, because when an
    // image loads, it triggers 'scroll' and the chat will be marked as scrolled,
    // which is technically true, but not what we want because the user
    // didn't initiate the scrolling.

    this.was_scrolled_up = this.chatview.model.get('scrolled');
    this.text = this.component.model.getMessageText();
  }

  scrollDownOnImageLoad() {
    if (!this.was_scrolled_up) {
      this.chatview.scrollDown();
    }
  }

  async transform() {
    const text = new body_MessageText(this.text);
    /**
     * Synchronous event which provides a hook for transforming a chat message's body text
     * before the default transformations have been applied.
     * @event _converse#beforeMessageBodyTransformed
     * @param { _converse.Message } model - The model representing the message
     * @param { MessageText } text - A {@link MessageText } instance. You
     * can call {@link MessageText#addTemplateResult } on it in order to
     * add TemplateResult objects meant to render rich parts of the
     * message.
     * @example _converse.api.listen.on('beforeMessageBodyTransformed', (view, text) => { ... });
     */

    await converse_core_api.trigger('beforeMessageBodyTransformed', this.model, text, {
      'Synchronous': true
    });
    addHyperlinks(text, () => this.scrollDownOnImageLoad(), ev => this.component.showImageModal(ev));
    addMapURLs(text);
    await addEmojis(text);
    addReferences(text, this.model);
    /**
     * Synchronous event which provides a hook for transforming a chat message's body text
     * after the default transformations have been applied.
     * @event _converse#afterMessageBodyTransformed
     * @param { _converse.Message } model - The model representing the message
     * @param { MessageText } text - A {@link MessageText } instance. You
     * can call {@link MessageText#addTemplateResult} on it in order to
     * add TemplateResult objects meant to render rich parts of the
     * message.
     * @example _converse.api.listen.on('afterMessageBodyTransformed', (view, text) => { ... });
     */

    await converse_core_api.trigger('afterMessageBodyTransformed', this.model, text, {
      'Synchronous': true
    });
    return text.marshall();
  }

  render() {
    return lit_html_html`${until(this.transform(), lit_html_html`${this.text}`)}`;
  }

}

const renderBodyText = directive_directive(component => part => {
  var _model$collection;

  const renderer = new body_MessageBodyRenderer(component);
  part.setValue(renderer.render());
  const model = component.model;
  (_model$collection = model.collection) === null || _model$collection === void 0 ? void 0 : _model$collection.trigger('rendered', model);
});
// CONCATENATED MODULE: ./src/components/message-body.js





class message_body_MessageBody extends element_CustomElement {
  static get properties() {
    return {
      model: {
        type: Object
      },
      is_me_message: {
        type: Boolean
      },
      text: {
        type: String
      }
    };
  }

  showImageModal(ev) {
    ev.preventDefault();

    if (this.image_modal === undefined) {
      this.image_modal = new modals_image();
    }

    this.image_modal.src = ev.target.src;
    this.image_modal.render();
    this.image_modal.show(ev);
  }

  render() {
    return renderBodyText(this);
  }

}
converse_core_api.elements.define('converse-chat-message-body', message_body_MessageBody);
// CONCATENATED MODULE: ./src/templates/audio.js

/* harmony default export */ var audio = (o => lit_html_html`
    <audio controls src="${o.url}"></audio>
    <a target="_blank" rel="noopener" href="${o.url}">${o.label_download}</a>
`);
// CONCATENATED MODULE: ./src/templates/file.js

/* harmony default export */ var templates_file = (o => lit_html_html`<a target="_blank" rel="noopener" href="${o.url}">${o.label_download}</a>`);
// EXTERNAL MODULE: ./src/templates/form_captcha.html
var form_captcha = __webpack_require__(166);
var form_captcha_default = /*#__PURE__*/__webpack_require__.n(form_captcha);

// EXTERNAL MODULE: ./src/templates/form_checkbox.html
var form_checkbox = __webpack_require__(167);
var form_checkbox_default = /*#__PURE__*/__webpack_require__.n(form_checkbox);

// EXTERNAL MODULE: ./src/templates/form_input.html
var form_input = __webpack_require__(61);
var form_input_default = /*#__PURE__*/__webpack_require__.n(form_input);

// EXTERNAL MODULE: ./src/templates/form_select.html
var form_select = __webpack_require__(168);
var form_select_default = /*#__PURE__*/__webpack_require__.n(form_select);

// EXTERNAL MODULE: ./src/templates/form_textarea.html
var form_textarea = __webpack_require__(169);
var form_textarea_default = /*#__PURE__*/__webpack_require__.n(form_textarea);

// EXTERNAL MODULE: ./src/templates/form_url.html
var form_url = __webpack_require__(170);
var form_url_default = /*#__PURE__*/__webpack_require__.n(form_url);

// EXTERNAL MODULE: ./src/templates/form_username.html
var form_username = __webpack_require__(62);
var form_username_default = /*#__PURE__*/__webpack_require__.n(form_username);

// CONCATENATED MODULE: ./src/templates/directives/image.js


/**
 * lit-html directive which attempts to render an <img> element from a URL.
 * It will fall back to rendering an <a> element if it can't.
 *
 * @param { String } src - The value that will be assigned to the `src` attribute of the `<img>` element.
 * @param { String } href - The value that will be assigned to the `href` attribute of the `<img>` element.
 * @param { Function } onLoad - A callback function to be called once the image has loaded.
 * @param { Function } onClick - A callback function to be called once the image has been clicked.
*/

const renderImage = directive_directive((src, href, onLoad, onClick) => part => {
  function onError() {
    const u = converse.env.utils;

    if (u.isURLWithImageExtension(src)) {
      part.setValue(u.convertUrlToHyperlink(href));
      part.commit();
    } else {
      // Before giving up and falling back to just rendering a hyperlink,
      // we attach `.png` and try one more time.
      // This works with some Imgur URLs
      part.setValue(renderImage(`${src}.png`, href, onLoad, onClick));
      part.commit();
    }
  }

  part.setValue(lit_html_html`<a href="${href}"
                class="chat-image__link"
                target="_blank"
                rel="noopener"
            ><img class="chat-image img-thumbnail" src="${src}" @click=${onClick} @error=${onError} @load=${onLoad}/></a>`);
});
// CONCATENATED MODULE: ./src/templates/image.js


/* harmony default export */ var templates_image = (o => lit_html_html`${renderImage(o.url, o.url, o.onLoad, o.onClick)}`);
// EXTERNAL MODULE: ./src/templates/select_option.html
var select_option = __webpack_require__(171);
var select_option_default = /*#__PURE__*/__webpack_require__.n(select_option);

// CONCATENATED MODULE: ./src/templates/video.js

/* harmony default export */ var video = (o => lit_html_html`<video controls preload="metadata" src="${o.url}" style="max-height: 50vh"></video>`);
// CONCATENATED MODULE: ./src/utils/html.js
/**
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 * @description This is the DOM/HTML utilities module.
 */


















const {
  sizzle: html_sizzle
} = converse.env;
const APPROVED_URL_PROTOCOLS = ['http', 'https', 'xmpp', 'mailto'];

function getAutoCompleteProperty(name, options) {
  return {
    'muc#roomconfig_lang': 'language',
    'muc#roomconfig_roomsecret': options !== null && options !== void 0 && options.new_password ? 'new-password' : 'current-password'
  }[name];
}

const XFORM_TYPE_MAP = {
  'text-private': 'password',
  'text-single': 'text',
  'fixed': 'label',
  'boolean': 'checkbox',
  'hidden': 'hidden',
  'jid-multi': 'textarea',
  'list-single': 'dropdown',
  'list-multi': 'dropdown'
};

function slideOutWrapup(el) {
  /* Wrapup function for slideOut. */
  el.removeAttribute('data-slider-marker');
  el.classList.remove('collapsed');
  el.style.overflow = "";
  el.style.height = "";
}

function getURI(url) {
  try {
    return url instanceof URI_default.a ? url : new URI_default.a(url);
  } catch (error) {
    headless_log.debug(error);
    return null;
  }
}

function checkTLS(uri) {
  return window.location.protocol === 'http:' || window.location.protocol === 'https:' && uri.protocol().toLowerCase() === "https";
}

function checkFileTypes(types, url) {
  const uri = getURI(url);

  if (uri === null || !checkTLS(uri)) {
    return false;
  }

  const filename = uri.filename().toLowerCase();
  return !!types.filter(ext => filename.endsWith(ext)).length;
}

utils_core.isAudioURL = url => checkFileTypes(['.ogg', '.mp3', '.m4a'], url);

utils_core.isVideoURL = url => checkFileTypes(['.mp4', '.webm'], url);

utils_core.isURLWithImageExtension = url => checkFileTypes(['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.svg'], url);

utils_core.isImageURL = url => {
  const regex = converse_core_api.settings.get('image_urls_regex');
  return (regex === null || regex === void 0 ? void 0 : regex.test(url)) || utils_core.isURLWithImageExtension(url);
};

utils_core.isImageDomainAllowed = url => {
  const show_images_inline = converse_core_api.settings.get('show_images_inline');

  if (!Array.isArray(show_images_inline)) {
    return true;
  }

  try {
    const image_domain = getURI(url).domain();
    return show_images_inline.includes(image_domain);
  } catch (error) {
    headless_log.debug(error);
    return true;
  }
};

function getFileName(uri) {
  try {
    return decodeURI(uri.filename());
  } catch (error) {
    headless_log.debug(error);
    return uri.filename();
  }
}

function renderAudioURL(_converse, uri) {
  const {
    __
  } = _converse;
  return audio({
    'url': uri.toString(),
    'label_download': __('Download audio file "%1$s"', getFileName(uri))
  });
}

function renderImageURL(_converse, uri) {
  const {
    __
  } = _converse;
  return templates_file({
    'url': uri.toString(),
    'label_download': __('Download image file "%1$s"', getFileName(uri))
  });
}

function renderFileURL(_converse, uri) {
  const {
    __
  } = _converse;
  return templates_file({
    'url': uri.toString(),
    'label_download': __('Download file "%1$s"', getFileName(uri))
  });
}
/**
 * Returns the markup for a URL that points to a downloadable asset
 * (such as a video, image or audio file).
 * @method u#getOOBURLMarkup
 * @param { String } url
 * @returns { String }
 */


utils_core.getOOBURLMarkup = function (_converse, url) {
  const uri = getURI(url);

  if (uri === null) {
    return url;
  }

  if (utils_core.isVideoURL(uri)) {
    return video({
      url
    });
  } else if (utils_core.isAudioURL(uri)) {
    return renderAudioURL(_converse, uri);
  } else if (utils_core.isImageURL(uri)) {
    return renderImageURL(_converse, uri);
  } else {
    return renderFileURL(_converse, uri);
  }
};
/**
 * Applies some resistance to `value` around the `default_value`.
 * If value is close enough to `default_value`, then it is returned, otherwise
 * `value` is returned.
 * @method u#applyDragResistance
 * @param { Integer } value
 * @param { Integer } default_value
 * @returns { Integer }
 */


utils_core.applyDragResistance = function (value, default_value) {
  if (value === undefined) {
    return undefined;
  } else if (default_value === undefined) {
    return value;
  }

  const resistance = 10;

  if (value !== default_value && Math.abs(value - default_value) < resistance) {
    return default_value;
  }

  return value;
};
/**
 * Return the height of the passed in DOM element,
 * based on the heights of its children.
 * @method u#calculateElementHeight
 * @param {HTMLElement} el
 * @returns {integer}
 */


utils_core.calculateElementHeight = function (el) {
  return Array.from(el.children).reduce((result, child) => result + child.offsetHeight, 0);
};

utils_core.getNextElement = function (el, selector = '*') {
  let next_el = el.nextElementSibling;

  while (next_el !== null && !html_sizzle.matchesSelector(next_el, selector)) {
    next_el = next_el.nextElementSibling;
  }

  return next_el;
};

utils_core.getPreviousElement = function (el, selector = '*') {
  let prev_el = el.previousElementSibling;

  while (prev_el !== null && !html_sizzle.matchesSelector(prev_el, selector)) {
    prev_el = prev_el.previousElementSibling;
  }

  return prev_el;
};

utils_core.getFirstChildElement = function (el, selector = '*') {
  let first_el = el.firstElementChild;

  while (first_el !== null && !html_sizzle.matchesSelector(first_el, selector)) {
    first_el = first_el.nextElementSibling;
  }

  return first_el;
};

utils_core.getLastChildElement = function (el, selector = '*') {
  let last_el = el.lastElementChild;

  while (last_el !== null && !html_sizzle.matchesSelector(last_el, selector)) {
    last_el = last_el.previousElementSibling;
  }

  return last_el;
};

utils_core.hasClass = function (className, el) {
  return el instanceof Element && el.classList.contains(className);
};

utils_core.toggleClass = function (className, el) {
  utils_core.hasClass(className, el) ? utils_core.removeClass(className, el) : utils_core.addClass(className, el);
};
/**
 * Add a class to an element.
 * @method u#addClass
 * @param {string} className
 * @param {Element} el
 */


utils_core.addClass = function (className, el) {
  el instanceof Element && el.classList.add(className);
  return el;
};
/**
 * Remove a class from an element.
 * @method u#removeClass
 * @param {string} className
 * @param {Element} el
 */


utils_core.removeClass = function (className, el) {
  el instanceof Element && el.classList.remove(className);
  return el;
};

utils_core.removeElement = function (el) {
  el instanceof Element && el.parentNode && el.parentNode.removeChild(el);
  return el;
};

utils_core.getElementFromTemplateResult = function (tr) {
  const div = document.createElement('div');
  render_render(tr, div);
  return div.firstElementChild;
};

utils_core.showElement = el => {
  utils_core.removeClass('collapsed', el);
  utils_core.removeClass('hidden', el);
};

utils_core.hideElement = function (el) {
  el instanceof Element && el.classList.add('hidden');
  return el;
};

utils_core.ancestor = function (el, selector) {
  let parent = el;

  while (parent !== null && !html_sizzle.matchesSelector(parent, selector)) {
    parent = parent.parentElement;
  }

  return parent;
};
/**
 * Return the element's siblings until one matches the selector.
 * @private
 * @method u#nextUntil
 * @param { HTMLElement } el
 * @param { String } selector
 */


utils_core.nextUntil = function (el, selector) {
  const matches = [];
  let sibling_el = el.nextElementSibling;

  while (sibling_el !== null && !sibling_el.matches(selector)) {
    matches.push(sibling_el);
    sibling_el = sibling_el.nextElementSibling;
  }

  return matches;
};
/**
 * Helper method that replace HTML-escaped symbols with equivalent characters
 * (e.g. transform occurrences of '&amp;' to '&')
 * @private
 * @method u#unescapeHTML
 * @param { String } string - a String containing the HTML-escaped symbols.
 */


utils_core.unescapeHTML = function (string) {
  var div = document.createElement('div');
  div.innerHTML = string;
  return div.innerText;
};

utils_core.escapeHTML = function (string) {
  return string.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
};

utils_core.convertToImageTag = function (url, onLoad, onClick) {
  return templates_image({
    url,
    onClick,
    onLoad
  });
};

utils_core.convertURIoHyperlink = function (uri, urlAsTyped) {
  let normalized_url = uri.normalize()._string;

  const pretty_url = uri._parts.urn ? normalized_url : uri.readable();
  const visible_url = urlAsTyped || pretty_url;

  if (!uri._parts.protocol && !normalized_url.startsWith('http://') && !normalized_url.startsWith('https://')) {
    normalized_url = 'http://' + normalized_url;
  }

  if (uri._parts.protocol === 'xmpp' && uri._parts.query === 'join') {
    return lit_html_html`
            <a target="_blank"
               rel="noopener"
               @click=${ev => converse_core_api.rooms.open(ev.target.href)}
               href="${normalized_url}">${visible_url}</a>`;
  }

  return lit_html_html`<a target="_blank" rel="noopener" href="${normalized_url}">${visible_url}</a>`;
};

function isProtocolApproved(protocol, safeProtocolsList = APPROVED_URL_PROTOCOLS) {
  return !!safeProtocolsList.includes(protocol);
} // Will return false if URL is malformed or contains disallowed characters


function isUrlValid(urlString) {
  try {
    const url = new URL(urlString);
    return !!url;
  } catch (error) {
    return false;
  }
}

utils_core.convertUrlToHyperlink = function (url) {
  const http_url = RegExp('^w{3}.', 'ig').test(url) ? `http://${url}` : url;
  const uri = getURI(url);

  if (uri !== null && isUrlValid(http_url) && (isProtocolApproved(uri._parts.protocol) || !uri._parts.protocol)) {
    return this.convertURIoHyperlink(uri, url);
  }

  return url;
};

utils_core.filterQueryParamsFromURL = function (url) {
  const paramsArray = converse_core_api.settings.get("filter_url_query_params");
  if (!paramsArray) return url;
  const parsed_uri = getURI(url);
  return parsed_uri.removeQuery(paramsArray).toString();
};

utils_core.addHyperlinks = function (text) {
  const objs = [];
  const parse_options = {
    'start': /\b(?:([a-z][a-z0-9.+-]*:\/\/)|xmpp:|mailto:|www\.)/gi
  };

  try {
    URI_default.a.withinString(text, (url, start, end) => {
      objs.push({
        url,
        start,
        end
      });
      return url;
    }, parse_options);
  } catch (error) {
    headless_log.debug(error);
    return [text];
  }

  let list = [text];

  if (objs.length) {
    objs.sort((a, b) => b.start - a.start).forEach(url_obj => {
      const text = list.shift();
      const url_text = text.slice(url_obj.start, url_obj.end);
      list = [text.slice(0, url_obj.start), utils_core.convertUrlToHyperlink(url_text), text.slice(url_obj.end), ...list];
    });
  } else {
    list = [text];
  }

  return list;
};

utils_core.httpToGeoUri = function (text, _converse) {
  const replacement = 'geo:$1,$2';
  return text.replace(_converse.api.settings.get("geouri_regex"), replacement);
};

utils_core.slideInAllElements = function (elements, duration = 300) {
  return Promise.all(Array.from(elements).map(e => utils_core.slideIn(e, duration)));
};

utils_core.slideToggleElement = function (el, duration) {
  if (utils_core.hasClass('collapsed', el) || utils_core.hasClass('hidden', el)) {
    return utils_core.slideOut(el, duration);
  } else {
    return utils_core.slideIn(el, duration);
  }
};
/**
 * Shows/expands an element by sliding it out of itself
 * @private
 * @method u#slideOut
 * @param { HTMLElement } el - The HTML string
 * @param { Number } duration - The duration amount in milliseconds
 */


utils_core.slideOut = function (el, duration = 200) {
  return new Promise((resolve, reject) => {
    if (!el) {
      const err = "An element needs to be passed in to slideOut";
      headless_log.warn(err);
      reject(new Error(err));
      return;
    }

    const marker = el.getAttribute('data-slider-marker');

    if (marker) {
      el.removeAttribute('data-slider-marker');
      window.cancelAnimationFrame(marker);
    }

    const end_height = utils_core.calculateElementHeight(el);

    if (window.converse_disable_effects) {
      // Effects are disabled (for tests)
      el.style.height = end_height + 'px';
      slideOutWrapup(el);
      resolve();
      return;
    }

    if (!utils_core.hasClass('collapsed', el) && !utils_core.hasClass('hidden', el)) {
      resolve();
      return;
    }

    const steps = duration / 17; // We assume 17ms per animation which is ~60FPS

    let height = 0;

    function draw() {
      height += end_height / steps;

      if (height < end_height) {
        el.style.height = height + 'px';
        el.setAttribute('data-slider-marker', window.requestAnimationFrame(draw));
      } else {
        // We recalculate the height to work around an apparent
        // browser bug where browsers don't know the correct
        // offsetHeight beforehand.
        el.removeAttribute('data-slider-marker');
        el.style.height = utils_core.calculateElementHeight(el) + 'px';
        el.style.overflow = "";
        el.style.height = "";
        resolve();
      }
    }

    el.style.height = '0';
    el.style.overflow = 'hidden';
    el.classList.remove('hidden');
    el.classList.remove('collapsed');
    el.setAttribute('data-slider-marker', window.requestAnimationFrame(draw));
  });
};

utils_core.slideIn = function (el, duration = 200) {
  /* Hides/collapses an element by sliding it into itself. */
  return new Promise((resolve, reject) => {
    if (!el) {
      const err = "An element needs to be passed in to slideIn";
      headless_log.warn(err);
      return reject(new Error(err));
    } else if (utils_core.hasClass('collapsed', el)) {
      return resolve(el);
    } else if (window.converse_disable_effects) {
      // Effects are disabled (for tests)
      el.classList.add('collapsed');
      el.style.height = "";
      return resolve(el);
    }

    const marker = el.getAttribute('data-slider-marker');

    if (marker) {
      el.removeAttribute('data-slider-marker');
      window.cancelAnimationFrame(marker);
    }

    const original_height = el.offsetHeight,
          steps = duration / 17; // We assume 17ms per animation which is ~60FPS

    let height = original_height;
    el.style.overflow = 'hidden';

    function draw() {
      height -= original_height / steps;

      if (height > 0) {
        el.style.height = height + 'px';
        el.setAttribute('data-slider-marker', window.requestAnimationFrame(draw));
      } else {
        el.removeAttribute('data-slider-marker');
        el.classList.add('collapsed');
        el.style.height = "";
        resolve(el);
      }
    }

    el.setAttribute('data-slider-marker', window.requestAnimationFrame(draw));
  });
};

function afterAnimationEnds(el, callback) {
  el.classList.remove('visible');

  if (lodash_es_isFunction(callback)) {
    callback();
  }
}

utils_core.isInDOM = function (el) {
  return document.querySelector('body').contains(el);
};

utils_core.isVisible = function (el) {
  if (el === null) {
    return false;
  }

  if (utils_core.hasClass('hidden', el)) {
    return false;
  } // XXX: Taken from jQuery's "visible" implementation


  return el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length > 0;
};

utils_core.fadeIn = function (el, callback) {
  if (!el) {
    headless_log.warn("An element needs to be passed in to fadeIn");
  }

  if (window.converse_disable_effects) {
    el.classList.remove('hidden');
    return afterAnimationEnds(el, callback);
  }

  if (utils_core.hasClass('hidden', el)) {
    el.classList.add('visible');
    el.classList.remove('hidden');
    el.addEventListener("webkitAnimationEnd", () => afterAnimationEnds(el, callback));
    el.addEventListener("animationend", () => afterAnimationEnds(el, callback));
    el.addEventListener("oanimationend", () => afterAnimationEnds(el, callback));
  } else {
    afterAnimationEnds(el, callback);
  }
};
/**
 * Takes a field in XMPP XForm (XEP-004: Data Forms) format
 * and turns it into an HTML field.
 * Returns either text or a DOM element (which is not ideal, but fine for now).
 * @private
 * @method u#xForm2webForm
 * @param { XMLElement } field - the field to convert
 */


utils_core.xForm2webForm = function (field, stanza, options) {
  if (field.getAttribute('type') === 'list-single' || field.getAttribute('type') === 'list-multi') {
    const values = utils_core.queryChildren(field, 'value').map(el => el === null || el === void 0 ? void 0 : el.textContent);
    const options = utils_core.queryChildren(field, 'option').map(option => {
      var _option$querySelector;

      const value = (_option$querySelector = option.querySelector('value')) === null || _option$querySelector === void 0 ? void 0 : _option$querySelector.textContent;
      return select_option_default()({
        'value': value,
        'label': option.getAttribute('label'),
        'selected': values.includes(value),
        'required': !!field.querySelector('required')
      });
    });
    return form_select_default()({
      'id': utils_core.getUniqueId(),
      'name': field.getAttribute('var'),
      'label': field.getAttribute('label'),
      'options': options.join(''),
      'multiple': field.getAttribute('type') === 'list-multi',
      'required': !!field.querySelector('required')
    });
  } else if (field.getAttribute('type') === 'fixed') {
    var _field$querySelector;

    const text = (_field$querySelector = field.querySelector('value')) === null || _field$querySelector === void 0 ? void 0 : _field$querySelector.textContent;
    return '<p class="form-help">' + text + '</p>';
  } else if (field.getAttribute('type') === 'jid-multi') {
    var _field$querySelector2;

    return form_textarea_default()({
      'name': field.getAttribute('var'),
      'label': field.getAttribute('label') || '',
      'value': (_field$querySelector2 = field.querySelector('value')) === null || _field$querySelector2 === void 0 ? void 0 : _field$querySelector2.textContent,
      'required': !!field.querySelector('required')
    });
  } else if (field.getAttribute('type') === 'boolean') {
    var _field$querySelector3;

    const value = (_field$querySelector3 = field.querySelector('value')) === null || _field$querySelector3 === void 0 ? void 0 : _field$querySelector3.textContent;
    return form_checkbox_default()({
      'id': utils_core.getUniqueId(),
      'name': field.getAttribute('var'),
      'label': field.getAttribute('label') || '',
      'checked': (value === "1" || value === "true") && 'checked="1"' || '',
      'required': !!field.querySelector('required')
    });
  } else if (field.getAttribute('var') === 'url') {
    var _field$querySelector4;

    return form_url_default()({
      'label': field.getAttribute('label') || '',
      'value': (_field$querySelector4 = field.querySelector('value')) === null || _field$querySelector4 === void 0 ? void 0 : _field$querySelector4.textContent
    });
  } else if (field.getAttribute('var') === 'username') {
    var _field$querySelector5;

    return form_username_default()({
      'domain': ' @' + options.domain,
      'name': field.getAttribute('var'),
      'type': XFORM_TYPE_MAP[field.getAttribute('type')],
      'label': field.getAttribute('label') || '',
      'value': (_field$querySelector5 = field.querySelector('value')) === null || _field$querySelector5 === void 0 ? void 0 : _field$querySelector5.textContent,
      'required': !!field.querySelector('required')
    });
  } else if (field.getAttribute('var') === 'ocr') {
    // Captcha
    const uri = field.querySelector('uri');
    const el = html_sizzle('data[cid="' + uri.textContent.replace(/^cid:/, '') + '"]', stanza)[0];
    return form_captcha_default()({
      'label': field.getAttribute('label'),
      'name': field.getAttribute('var'),
      'data': el === null || el === void 0 ? void 0 : el.textContent,
      'type': uri.getAttribute('type'),
      'required': !!field.querySelector('required')
    });
  } else {
    var _field$querySelector6;

    const name = field.getAttribute('var');
    return form_input_default()({
      'id': utils_core.getUniqueId(),
      'label': field.getAttribute('label') || '',
      'name': name,
      'fixed_username': options === null || options === void 0 ? void 0 : options.fixed_username,
      'autocomplete': getAutoCompleteProperty(name, options),
      'placeholder': null,
      'required': !!field.querySelector('required'),
      'type': XFORM_TYPE_MAP[field.getAttribute('type')],
      'value': (_field$querySelector6 = field.querySelector('value')) === null || _field$querySelector6 === void 0 ? void 0 : _field$querySelector6.textContent
    });
  }
};

/* harmony default export */ var utils_html = (utils_core);
// CONCATENATED MODULE: ./src/dom-navigator.js
/**
 * @module dom-navigator
 * @description A class for navigating the DOM with the keyboard
 * This module started as a fork of Rubens Mariuzzo's dom-navigator.
 * @copyright Rubens Mariuzzo, JC Brand
 */


const {
  keycodes
} = converse;
/**
 * Indicates if a given element is fully visible in the viewport.
 * @param { Element } el The element to check.
 * @return { Boolean } True if the given element is fully visible in the viewport, otherwise false.
 */

function inViewport(el) {
  const rect = el.getBoundingClientRect();
  return rect.top >= 0 && rect.left >= 0 && rect.bottom <= window.innerHeight && rect.right <= window.innerWidth;
}
/**
 * Return the absolute offset top of an element.
 * @param el { Element } The element.
 * @return { Number } The offset top.
 */


function absoluteOffsetTop(el) {
  let offsetTop = 0;

  do {
    if (!isNaN(el.offsetTop)) {
      offsetTop += el.offsetTop;
    }
  } while (el = el.offsetParent);

  return offsetTop;
}
/**
 * Return the absolute offset left of an element.
 * @param el { Element } The element.
 * @return { Number } The offset left.
 */


function absoluteOffsetLeft(el) {
  let offsetLeft = 0;

  do {
    if (!isNaN(el.offsetLeft)) {
      offsetLeft += el.offsetLeft;
    }
  } while (el = el.offsetParent);

  return offsetLeft;
}
/**
 * Adds the ability to navigate the DOM with the arrow keys
 * @class DOMNavigator
 */


class dom_navigator_DOMNavigator {
  /**
   * Directions.
   * @returns {{left: string, up: string, right: string, down: string}}
   * @constructor
   */
  static get DIRECTION() {
    return {
      down: 'down',
      end: 'end',
      home: 'home',
      left: 'left',
      right: 'right',
      up: 'up'
    };
  }
  /**
   * The default options for the DOM navigator.
   * @returns {{
   *     down: number,
   *     getSelector: null,
   *     jump_to_picked: null,
   *     jump_to_picked_direction: null,
   *     jump_to_picked_selector: string,
   *     left: number,
   *     onSelected: null,
   *     right: number,
   *     selected: string,
   *     up: number
   * }}
   */


  static get DEFAULTS() {
    return {
      home: [`${keycodes.SHIFT}+${keycodes.UP_ARROW}`],
      end: [`${keycodes.SHIFT}+${keycodes.DOWN_ARROW}`],
      up: [keycodes.UP_ARROW],
      down: [keycodes.DOWN_ARROW],
      left: [keycodes.LEFT_ARROW, `${keycodes.SHIFT}+${keycodes.TAB}`],
      right: [keycodes.RIGHT_ARROW, keycodes.TAB],
      getSelector: null,
      jump_to_picked: null,
      jump_to_picked_direction: null,
      jump_to_picked_selector: 'picked',
      onSelected: null,
      selected: 'selected',
      selector: 'li'
    };
  }

  static getClosestElement(els, getDistance) {
    const next = els.reduce((prev, curr) => {
      const current_distance = getDistance(curr);

      if (current_distance < prev.distance) {
        return {
          distance: current_distance,
          element: curr
        };
      }

      return prev;
    }, {
      distance: Infinity
    });
    return next.element;
  }
  /**
   * Create a new DOM Navigator.
   * @param { Element } container The container of the element to navigate.
   * @param { Object } options The options to configure the DOM navigator.
   * @param { Function } options.getSelector
   * @param { Number } [options.down] - The keycode for navigating down
   * @param { Number } [options.left] - The keycode for navigating left
   * @param { Number } [options.right] - The keycode for navigating right
   * @param { Number } [options.up] - The keycode for navigating up
   * @param { String } [options.selected] - The class that should be added to the currently selected DOM element.
   * @param { String } [options.jump_to_picked] - A selector, which if
   * matched by the next element being navigated to, based on the direction
   * given by `jump_to_picked_direction`, will cause navigation
   * to jump to the element that matches the `jump_to_picked_selector`.
   * For example, this is useful when navigating to tabs. You want to
   * immediately navigate to the currently active tab instead of just
   * navigating to the first tab.
   * @param { String } [options.jump_to_picked_selector=picked] - The selector
   * indicating the currently picked element to jump to.
   * @param { String } [options.jump_to_picked_direction] - The direction for
   * which jumping to the picked element should be enabled.
   * @param { Function } [options.onSelected] - The callback function which
   * should be called when en element gets selected.
   * @constructor
   */


  constructor(container, options) {
    this.doc = window.document;
    this.container = container;
    this.scroll_container = options.scroll_container || container;
    this.options = Object.assign({}, dom_navigator_DOMNavigator.DEFAULTS, options);
    this.init();
  }
  /**
   * Initialize the navigator.
   */


  init() {
    this.selected = null;
    this.keydownHandler = null;
    this.elements = {}; // Create hotkeys map.

    this.keys = {};
    this.options.down.forEach(key => this.keys[key] = dom_navigator_DOMNavigator.DIRECTION.down);
    this.options.end.forEach(key => this.keys[key] = dom_navigator_DOMNavigator.DIRECTION.end);
    this.options.home.forEach(key => this.keys[key] = dom_navigator_DOMNavigator.DIRECTION.home);
    this.options.left.forEach(key => this.keys[key] = dom_navigator_DOMNavigator.DIRECTION.left);
    this.options.right.forEach(key => this.keys[key] = dom_navigator_DOMNavigator.DIRECTION.right);
    this.options.up.forEach(key => this.keys[key] = dom_navigator_DOMNavigator.DIRECTION.up);
  }
  /**
   * Enable this navigator.
   */


  enable() {
    this.getElements();

    this.keydownHandler = event => this.handleKeydown(event);

    this.doc.addEventListener('keydown', this.keydownHandler);
    this.enabled = true;
  }
  /**
   * Disable this navigator.
   */


  disable() {
    if (this.keydownHandler) {
      this.doc.removeEventListener('keydown', this.keydownHandler);
    }

    this.unselect();
    this.elements = {};
    this.enabled = false;
  }
  /**
   * Destroy this navigator removing any event registered and any other data.
   */


  destroy() {
    this.disable();

    if (this.container.domNavigator) {
      delete this.container.domNavigator;
    }
  }
  /**
   * @param {'down'|'right'|'left'|'up'} direction
   * @returns { HTMLElement }
   */


  getNextElement(direction) {
    let el;

    if (direction === dom_navigator_DOMNavigator.DIRECTION.home) {
      el = this.getElements(direction)[0];
    } else if (direction === dom_navigator_DOMNavigator.DIRECTION.end) {
      el = Array.from(this.getElements(direction)).pop();
    } else if (this.selected) {
      if (direction === dom_navigator_DOMNavigator.DIRECTION.right) {
        const els = this.getElements(direction);
        el = els.slice(els.indexOf(this.selected))[1];
      } else if (direction == dom_navigator_DOMNavigator.DIRECTION.left) {
        const els = this.getElements(direction);
        el = els.slice(0, els.indexOf(this.selected)).pop() || this.selected;
      } else if (direction == dom_navigator_DOMNavigator.DIRECTION.down) {
        const left = this.selected.offsetLeft;
        const top = this.selected.offsetTop + this.selected.offsetHeight;
        const els = this.elementsAfter(0, top);

        const getDistance = el => Math.abs(el.offsetLeft - left) + Math.abs(el.offsetTop - top);

        el = dom_navigator_DOMNavigator.getClosestElement(els, getDistance);
      } else if (direction == dom_navigator_DOMNavigator.DIRECTION.up) {
        const left = this.selected.offsetLeft;
        const top = this.selected.offsetTop - 1;
        const els = this.elementsBefore(Infinity, top);

        const getDistance = el => Math.abs(left - el.offsetLeft) + Math.abs(top - el.offsetTop);

        el = dom_navigator_DOMNavigator.getClosestElement(els, getDistance);
      } else {
        throw new Error("getNextElement: invalid direction value");
      }
    } else {
      if (direction === dom_navigator_DOMNavigator.DIRECTION.right || direction === dom_navigator_DOMNavigator.DIRECTION.down) {
        // If nothing is selected, we pretend that the first element is
        // selected, so we return the next.
        el = this.getElements(direction)[1];
      } else {
        el = this.getElements(direction)[0];
      }
    }

    if (this.options.jump_to_picked && el && el.matches(this.options.jump_to_picked) && direction === this.options.jump_to_picked_direction) {
      el = this.container.querySelector(this.options.jump_to_picked_selector) || el;
    }

    return el;
  }
  /**
   * Select the given element.
   * @param { Element } el The DOM element to select.
   * @param { string } [direction] The direction.
   */


  select(el, direction) {
    if (!el || el === this.selected) {
      return;
    }

    this.unselect();
    direction && this.scrollTo(el, direction);

    if (el.matches('input')) {
      el.focus();
    } else {
      utils_html.addClass(this.options.selected, el);
    }

    this.selected = el;
    this.options.onSelected && this.options.onSelected(el);
  }
  /**
   * Remove the current selection
   */


  unselect() {
    if (this.selected) {
      utils_html.removeClass(this.options.selected, this.selected);
      delete this.selected;
    }
  }
  /**
   * Scroll the container to an element.
   * @param { HTMLElement } el The destination element.
   * @param { String } direction The direction of the current navigation.
   * @return void.
   */


  scrollTo(el, direction) {
    if (!this.inScrollContainerViewport(el)) {
      const container = this.scroll_container;

      if (!container.contains(el)) {
        return;
      }

      switch (direction) {
        case dom_navigator_DOMNavigator.DIRECTION.left:
          container.scrollLeft = el.offsetLeft - container.offsetLeft;
          container.scrollTop = el.offsetTop - container.offsetTop;
          break;

        case dom_navigator_DOMNavigator.DIRECTION.up:
          container.scrollTop = el.offsetTop - container.offsetTop;
          break;

        case dom_navigator_DOMNavigator.DIRECTION.right:
          container.scrollLeft = el.offsetLeft - container.offsetLeft - (container.offsetWidth - el.offsetWidth);
          container.scrollTop = el.offsetTop - container.offsetTop - (container.offsetHeight - el.offsetHeight);
          break;

        case dom_navigator_DOMNavigator.DIRECTION.down:
          container.scrollTop = el.offsetTop - container.offsetTop - (container.offsetHeight - el.offsetHeight);
          break;
      }
    } else if (!inViewport(el)) {
      switch (direction) {
        case dom_navigator_DOMNavigator.DIRECTION.left:
          document.body.scrollLeft = absoluteOffsetLeft(el) - document.body.offsetLeft;
          break;

        case dom_navigator_DOMNavigator.DIRECTION.up:
          document.body.scrollTop = absoluteOffsetTop(el) - document.body.offsetTop;
          break;

        case dom_navigator_DOMNavigator.DIRECTION.right:
          document.body.scrollLeft = absoluteOffsetLeft(el) - document.body.offsetLeft - (document.documentElement.clientWidth - el.offsetWidth);
          break;

        case dom_navigator_DOMNavigator.DIRECTION.down:
          document.body.scrollTop = absoluteOffsetTop(el) - document.body.offsetTop - (document.documentElement.clientHeight - el.offsetHeight);
          break;
      }
    }
  }
  /**
   * Indicate if an element is in the container viewport.
   * @param { HTMLElement } el The element to check.
   * @return { Boolean } true if the given element is in the container viewport, otherwise false.
   */


  inScrollContainerViewport(el) {
    const container = this.scroll_container; // Check on left side.

    if (el.offsetLeft - container.scrollLeft < container.offsetLeft) {
      return false;
    } // Check on top side.


    if (el.offsetTop - container.scrollTop < container.offsetTop) {
      return false;
    } // Check on right side.


    if (el.offsetLeft + el.offsetWidth - container.scrollLeft > container.offsetLeft + container.offsetWidth) {
      return false;
    } // Check on down side.


    if (el.offsetTop + el.offsetHeight - container.scrollTop > container.offsetTop + container.offsetHeight) {
      return false;
    }

    return true;
  }
  /**
   * Find and store the navigable elements
   */


  getElements(direction) {
    const selector = this.options.getSelector ? this.options.getSelector(direction) : this.options.selector;

    if (!this.elements[selector]) {
      this.elements[selector] = Array.from(this.container.querySelectorAll(selector));
    }

    return this.elements[selector];
  }
  /**
   * Return an array of navigable elements after an offset.
   * @param { number } left The left offset.
   * @param { number } top The top offset.
   * @return { Array } An array of elements.
   */


  elementsAfter(left, top) {
    return this.getElements(dom_navigator_DOMNavigator.DIRECTION.down).filter(el => el.offsetLeft >= left && el.offsetTop >= top);
  }
  /**
   * Return an array of navigable elements before an offset.
   * @param { number } left The left offset.
   * @param { number } top The top offset.
   * @return { Array } An array of elements.
   */


  elementsBefore(left, top) {
    return this.getElements(dom_navigator_DOMNavigator.DIRECTION.up).filter(el => el.offsetLeft <= left && el.offsetTop <= top);
  }
  /**
   * Handle the key down event.
   * @param { Event } event The event object.
   */


  handleKeydown(ev) {
    const keys = keycodes;
    const direction = ev.shiftKey ? this.keys[`${keys.SHIFT}+${ev.which}`] : this.keys[ev.which];

    if (direction) {
      ev.preventDefault();
      ev.stopPropagation();
      const next = this.getNextElement(direction, ev);
      this.select(next, direction);
    }
  }

}

/* harmony default export */ var dom_navigator = (dom_navigator_DOMNavigator);
// CONCATENATED MODULE: ./src/components/dropdown.js





const dropdown_u = converse.env.utils;
class dropdown_BaseDropdown extends element_CustomElement {
  firstUpdated() {
    this.menu = this.querySelector('.dropdown-menu');
    this.dropdown = this.firstElementChild;
    this.button = this.dropdown.querySelector('button');
    this.dropdown.addEventListener('click', ev => this.toggleMenu(ev));
    this.dropdown.addEventListener('keyup', ev => this.handleKeyUp(ev));
    document.addEventListener('click', ev => !this.contains(ev.composedPath()[0]) && this.hideMenu(ev));
  }

  hideMenu() {
    var _this$button, _this$button2;

    dropdown_u.removeClass('show', this.menu);
    (_this$button = this.button) === null || _this$button === void 0 ? void 0 : _this$button.setAttribute('aria-expanded', false);
    (_this$button2 = this.button) === null || _this$button2 === void 0 ? void 0 : _this$button2.blur();
  }

  showMenu() {
    dropdown_u.addClass('show', this.menu);
    this.button.setAttribute('aria-expanded', true);
  }

  toggleMenu(ev) {
    ev.preventDefault();

    if (dropdown_u.hasClass('show', this.menu)) {
      this.hideMenu();
    } else {
      this.showMenu();
    }
  }

  handleKeyUp(ev) {
    if (ev.keyCode === converse.keycodes.ESCAPE) {
      this.hideMenu();
    } else if (ev.keyCode === converse.keycodes.DOWN_ARROW && this.navigator && !this.navigator.enabled) {
      this.enableArrowNavigation(ev);
    }
  }

}
class dropdown_DropdownList extends dropdown_BaseDropdown {
  static get properties() {
    return {
      'icon_classes': {
        type: String
      },
      'items': {
        type: Array
      }
    };
  }

  render() {
    const icon_classes = this.icon_classes || "fa fa-bars";
    return lit_html_html`
            <div class="dropleft">
                <button type="button" class="btn btn--transparent btn--standalone" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    <i class="${icon_classes} only-icon"></i>
                </button>
                <div class="dropdown-menu">
                    ${this.items.map(b => until(b, ''))}
                </div>
            </div>
        `;
  }

  hideMenu() {
    super.hideMenu();
    this.navigator.disable();
  }

  firstUpdated() {
    super.firstUpdated();
    this.initArrowNavigation();
  }

  initArrowNavigation() {
    if (!this.navigator) {
      const options = {
        'selector': '.dropdown-item',
        'onSelected': el => el.focus()
      };
      this.navigator = new dom_navigator(this.menu, options);
    }
  }

  enableArrowNavigation(ev) {
    if (ev) {
      ev.preventDefault();
      ev.stopPropagation();
    }

    this.navigator.enable();
    this.navigator.select(this.menu.firstElementChild);
  }

  handleKeyUp(ev) {
    super.handleKeyUp(ev);

    if (ev.keyCode === converse.keycodes.DOWN_ARROW && !this.navigator.enabled) {
      this.enableArrowNavigation(ev);
    }
  }

}
converse_core_api.elements.define('converse-dropdown', dropdown_DropdownList);
// CONCATENATED MODULE: ./src/components/message-actions.js






class message_actions_MessageActions extends element_CustomElement {
  static get properties() {
    return {
      chatview: {
        type: Object
      },
      model: {
        type: Object
      },
      editable: {
        type: Boolean
      },
      correcting: {
        type: Boolean
      },
      message_type: {
        type: String
      },
      is_retracted: {
        type: Boolean
      }
    };
  }

  render() {
    return lit_html_html`${until(this.renderActions(), '')}`;
  }

  static getActionsDropdownItem(o) {
    return lit_html_html`
            <button class="chat-msg__action ${o.button_class}" @click=${o.handler}>
                <converse-icon class="${o.icon_class}"
                    path-prefix="${converse_core_api.settings.get("assets_path")}"
                    color="var(--text-color-lighten-15-percent)"
                    size="1em"></converse-icon>
                ${o.i18n_text}
            </button>
        `;
  }

  onMessageEditButtonClicked(ev) {
    ev.preventDefault();
    this.chatview.onMessageEditButtonClicked(this.model);
  }

  onMessageRetractButtonClicked(ev) {
    ev.preventDefault();
    this.chatview.onMessageRetractButtonClicked(this.model);
  }

  async renderActions() {
    const buttons = [];

    if (this.editable) {
      buttons.push({
        'i18n_text': this.correcting ? i18n_('Cancel Editing') : i18n_('Edit'),
        'handler': ev => this.onMessageEditButtonClicked(ev),
        'button_class': 'chat-msg__action-edit',
        'icon_class': 'fa fa-pencil-alt',
        'name': 'edit'
      });
    }

    const may_be_moderated = this.model.get('type') === 'groupchat' && (await this.model.mayBeModerated());
    const retractable = !this.is_retracted && (this.model.mayBeRetracted() || may_be_moderated);

    if (retractable) {
      buttons.push({
        'i18n_text': i18n_('Retract'),
        'handler': ev => this.onMessageRetractButtonClicked(ev),
        'button_class': 'chat-msg__action-retract',
        'icon_class': 'fas fa-trash-alt',
        'name': 'retract'
      });
    }

    const items = buttons.map(b => message_actions_MessageActions.getActionsDropdownItem(b));

    if (items.length) {
      return lit_html_html`<converse-dropdown class="chat-msg__actions" .items=${items}></converse-dropdown>`;
    } else {
      return '';
    }
  }

}

converse_core_api.elements.define('converse-message-actions', message_actions_MessageActions);
// CONCATENATED MODULE: ./src/templates/message_versions_modal.js




/* harmony default export */ var message_versions_modal = (o => lit_html_html`
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="message-versions-modal-label">${i18n_('Message versions')}</h4>
                ${modal_header_close_button}
            </div>
            <div class="modal-body">
                <h4>Older versions</h4>
                ${Object.keys(o.older_versions).map(k => lit_html_html`<p class="older-msg"><time>${dayjs_min_default()(k).format('MMM D, YYYY, HH:mm:ss')}</time>: ${o.older_versions[k]}</p>`)}
                <hr/>
                <h4>Current version</h4>
                <p>${o.message}</p>
            </div>
            <div class="modal-footer">${modal_close_button}</div>
        </div>
    </div>
`);
// CONCATENATED MODULE: ./src/modals/message-versions.js


/* harmony default export */ var message_versions = (BootstrapModal.extend({
  // FIXME: this isn't globally unique
  id: "message-versions-modal",

  toHTML() {
    return message_versions_modal(this.model.toJSON());
  }

}));
// CONCATENATED MODULE: ./src/templates/avatar.js


const getImgHref = (image, image_type) => {
  return image.startsWith('data:') ? image : `data:${image_type};base64,${image}`;
};

/* harmony default export */ var avatar = (o => lit_html_html`
    <svg xmlns="http://www.w3.org/2000/svg" class="avatar ${o.classes}" width="${o.width}" height="${o.height}">
        <image width="${o.width}" height="${o.height}" preserveAspectRatio="xMidYMid meet" href="${getImgHref(o.image, o.image_type)}"/>
    </svg>`);
// CONCATENATED MODULE: ./src/templates/directives/avatar.js


const renderAvatar = directive_directive(o => part => {
  const data = {
    'classes': o.classes ? `${o.classes} avatar` : 'avatar',
    'height': o.width || 36,
    'image': o.image,
    'image_type': o.image_type,
    'width': o.height || 36
  };
  part.setValue(avatar(data));
});
// CONCATENATED MODULE: ./src/templates/chat_message.js



/* harmony default export */ var chat_message = (o => {
  const i18n_new_messages = i18n_('New messages');

  return lit_html_html`
        ${o.is_first_unread ? lit_html_html`<div class="message separator"><hr class="separator"><span class="separator-text">${i18n_new_messages}</span></div>` : ''}
        <div class="message chat-msg ${o.getExtraMessageClasses()}"
                data-isodate="${o.time}"
                data-msgid="${o.msgid}"
                data-from="${o.from}"
                data-encrypted="${o.is_encrypted}">

            <!-- Anchor to allow us to scroll the message into view -->
            <a id="${o.msgid}"></a>

            ${o.shouldShowAvatar() ? renderAvatar(o.getAvatarData()) : ''}
            <div class="chat-msg__content chat-msg__content--${o.sender} ${o.is_me_message ? 'chat-msg__content--action' : ''}">

                ${!o.is_me_message ? lit_html_html`
                    <span class="chat-msg__heading">
                        <span class="chat-msg__author">${o.username}</span>
                        ${o.renderAvatarByline()}
                        ${o.is_encrypted ? lit_html_html`<span class="fa fa-lock"></span>` : ''}
                    </span>` : ''}
                <div class="chat-msg__body chat-msg__body--${o.message_type} ${o.received ? 'chat-msg__body--received' : ''} ${o.is_delayed ? 'chat-msg__body--delayed' : ''}">
                    <div class="chat-msg__message">
                        ${o.is_me_message ? lit_html_html`
                            <time timestamp="${o.edited || o.time}" class="chat-msg__time">${o.pretty_time}</time>&nbsp;
                            <span class="chat-msg__author">${o.is_me_message ? '**' : ''}${o.username}</span>&nbsp;` : ''}
                        ${o.is_retracted ? o.renderRetraction() : o.renderMessageText()}
                    </div>
                    <converse-message-actions
                        .chatview=${o.chatview}
                        .model=${o.model}
                        ?correcting="${o.correcting}"
                        ?editable="${o.editable}"
                        ?is_retracted="${o.is_retracted}"
                        message_type="${o.message_type}"></converse-message-actions>
                </div>
            </div>
        </div>`;
});
// CONCATENATED MODULE: ./src/templates/spinner.js

/* harmony default export */ var spinner = ((o = {}) => lit_html_html`<span class="spinner fa fa-spinner centered ${o.classes || ''}"/>`);
// CONCATENATED MODULE: ./src/components/message.js















const {
  Strophe: message_Strophe
} = converse.env;
const message_u = converse.env.utils;
class message_Message extends element_CustomElement {
  static get properties() {
    return {
      chatview: {
        type: Object
      },
      correcting: {
        type: Boolean
      },
      editable: {
        type: Boolean
      },
      edited: {
        type: String
      },
      error: {
        type: String
      },
      error_text: {
        type: String
      },
      from: {
        type: String
      },
      has_mentions: {
        type: Boolean
      },
      hats: {
        type: Array
      },
      is_delayed: {
        type: Boolean
      },
      is_encrypted: {
        type: Boolean
      },
      is_first_unread: {
        type: Boolean
      },
      is_me_message: {
        type: Boolean
      },
      is_only_emojis: {
        type: Boolean
      },
      is_retracted: {
        type: Boolean
      },
      is_spoiler: {
        type: Boolean
      },
      is_spoiler_visible: {
        type: Boolean
      },
      message_type: {
        type: String
      },
      model: {
        type: Object
      },
      moderated_by: {
        type: String
      },
      moderation_reason: {
        type: String
      },
      msgid: {
        type: String
      },
      occupant_affiliation: {
        type: String
      },
      occupant_role: {
        type: String
      },
      oob_url: {
        type: String
      },
      progress: {
        type: Number
      },
      reason: {
        type: String
      },
      received: {
        type: String
      },
      retractable: {
        type: Boolean
      },
      retry_event_id: {
        type: String
      },
      sender: {
        type: String
      },
      show_spinner: {
        type: Boolean
      },
      spoiler_hint: {
        type: String
      },
      subject: {
        type: String
      },
      time: {
        type: String
      },
      username: {
        type: String
      }
    };
  }

  render() {
    const format = converse_core_api.settings.get('time_format');
    this.pretty_time = dayjs_min_default()(this.edited || this.time).format(format);

    if (this.show_spinner) {
      return spinner();
    } else if (this.model.get('file') && !this.model.get('oob_url')) {
      return this.renderFileProgress();
    } else if (['error', 'info'].includes(this.message_type)) {
      return this.renderInfoMessage();
    } else {
      return this.renderChatMessage();
    }
  }

  connectedCallback() {
    super.connectedCallback(); // Listen to changes and update properties (which will trigger a
    // re-render if necessary).

    this.listenTo(this.model, 'change', model => {
      const chatbox = this.model.collection.chatbox;
      Object.assign(this, getDerivedMessageProps(chatbox, this.model));
      Object.keys(model.changed).filter(p => Object.keys(message_Message.properties).includes(p)).forEach(p => this[p] = model.changed[p]);
    });
    const vcard = this.model.vcard;
    vcard && this.listenTo(vcard, 'change', () => this.requestUpdate());
  }

  updated() {
    // XXX: This is ugly but tests rely on this event.
    // For "normal" chat messages the event is fired in
    // src/templates/directives/body.js
    if (this.show_spinner || this.model.get('file') && !this.model.get('oob_url') || ['error', 'info'].includes(this.message_type)) {
      var _this$model$collectio;

      (_this$model$collectio = this.model.collection) === null || _this$model$collectio === void 0 ? void 0 : _this$model$collectio.trigger('rendered', this.model);
    }
  }

  renderInfoMessage() {
    const isodate = dayjs_min_default()(this.model.get('time')).toISOString();

    const i18n_retry = i18n_('Retry');

    return lit_html_html`
            <div class="message chat-info chat-${this.message_type}"
                data-isodate="${isodate}"
                data-type="${this.data_name}"
                data-value="${this.data_value}">

                <div class="chat-info__message">
                    ${this.model.getMessageText()}
                </div>
                ${this.reason ? lit_html_html`<q class="reason">${this.reason}</q>` : ``}
                ${this.error_text ? lit_html_html`<q class="reason">${this.error_text}</q>` : ``}
                ${this.retry_event_id ? lit_html_html`<a class="retry" @click=${this.onRetryClicked}>${i18n_retry}</a>` : ''}
            </div>
        `;
  }

  renderFileProgress() {
    const i18n_uploading = i18n_('Uploading file:');

    const filename = this.model.file.name;
    const size = filesize_min_default()(this.model.file.size);
    return lit_html_html`
            <div class="message chat-msg">
                ${renderAvatar(this.getAvatarData())}
                <div class="chat-msg__content">
                    <span class="chat-msg__text">${i18n_uploading} <strong>${filename}</strong>, ${size}</span>
                    <progress value="${this.progress}"/>
                </div>
            </div>`;
  }

  renderChatMessage() {
    return chat_message(this);
  }

  shouldShowAvatar() {
    return converse_core_api.settings.get('show_message_avatar') && !this.is_me_message && this.type !== 'headline';
  }

  getAvatarData() {
    var _this$model$vcard, _this$model$vcard2;

    const image_type = ((_this$model$vcard = this.model.vcard) === null || _this$model$vcard === void 0 ? void 0 : _this$model$vcard.get('image_type')) || converse_core_converse.DEFAULT_IMAGE_TYPE;
    const image_data = ((_this$model$vcard2 = this.model.vcard) === null || _this$model$vcard2 === void 0 ? void 0 : _this$model$vcard2.get('image')) || converse_core_converse.DEFAULT_IMAGE;
    const image = "data:" + image_type + ";base64," + image_data;
    return {
      'classes': 'chat-msg__avatar',
      'height': 36,
      'width': 36,
      image
    };
  }

  async onRetryClicked() {
    this.show_spinner = true;
    await converse_core_api.trigger(this.retry_event_id, {
      'synchronous': true
    });
    this.model.destroy();
    this.parentElement.removeChild(this);
  }

  isFollowup() {
    const messages = this.model.collection.models;
    const idx = messages.indexOf(this.model);
    const prev_model = idx ? messages[idx - 1] : null;

    if (prev_model === null) {
      return false;
    }

    const date = dayjs_min_default()(this.time);
    return this.from === prev_model.get('from') && !this.is_me_message && !prev_model.isMeCommand() && this.message_type !== 'info' && prev_model.get('type') !== 'info' && date.isBefore(dayjs_min_default()(prev_model.get('time')).add(10, 'minutes')) && !!this.is_encrypted === !!prev_model.get('is_encrypted');
  }

  getExtraMessageClasses() {
    const extra_classes = [this.isFollowup() ? 'chat-msg--followup' : null, this.is_delayed ? 'delayed' : null, this.is_me_message ? 'chat-msg--action' : null, this.is_retracted ? 'chat-msg--retracted' : null, this.message_type, this.shouldShowAvatar() ? 'chat-msg--with-avatar' : null].map(c => c);

    if (this.message_type === 'groupchat') {
      this.occupant_role && extra_classes.push(this.occupant_role);
      this.occupant_affiliation && extra_classes.push(this.occupant_affiliation);

      if (this.sender === 'them' && this.has_mentions) {
        extra_classes.push('mentioned');
      }
    }

    this.correcting && extra_classes.push('correcting');
    return extra_classes.filter(c => c).join(" ");
  }

  getRetractionText() {
    if (this.message_type === 'groupchat' && this.moderated_by) {
      const retracted_by_mod = this.moderated_by;
      const chatbox = this.model.collection.chatbox;

      if (!this.model.mod) {
        this.model.mod = chatbox.occupants.findOccupant({
          'jid': retracted_by_mod
        }) || chatbox.occupants.findOccupant({
          'nick': message_Strophe.getResourceFromJid(retracted_by_mod)
        });
      }

      const modname = this.model.mod ? this.model.mod.getDisplayName() : 'A moderator';
      return i18n_('%1$s has removed this message', modname);
    } else {
      return i18n_('%1$s has removed this message', this.model.getDisplayName());
    }
  }

  renderRetraction() {
    const retraction_text = this.is_retracted ? this.getRetractionText() : null;
    return lit_html_html`
            <div>${retraction_text}</div>
            ${this.moderation_reason ? lit_html_html`<q class="chat-msg--retracted__reason">${this.moderation_reason}</q>` : ''}
        `;
  }

  renderMessageText() {
    const i18n_edited = i18n_('This message has been edited');

    const i18n_show = i18n_('Show more');

    const is_groupchat_message = this.message_type === 'groupchat';

    const i18n_show_less = i18n_('Show less');

    const tpl_spoiler_hint = lit_html_html`
            <div class="chat-msg__spoiler-hint">
                <span class="spoiler-hint">${this.spoiler_hint}</span>
                <a class="badge badge-info spoiler-toggle" href="#" @click=${this.toggleSpoilerMessage}>
                    <i class="fa ${this.is_spoiler_visible ? 'fa-eye-slash' : 'fa-eye'}"></i>
                    ${this.is_spoiler_visible ? i18n_show_less : i18n_show}
                </a>
            </div>
        `;
    const spoiler_classes = this.is_spoiler ? `spoiler ${this.is_spoiler_visible ? '' : 'hidden'}` : '';
    return lit_html_html`
            ${this.is_spoiler ? tpl_spoiler_hint : ''}
            ${this.subject ? lit_html_html`<div class="chat-msg__subject">${this.subject}</div>` : ''}
            <span>
                <converse-chat-message-body
                    class="chat-msg__text ${this.is_only_emojis ? 'chat-msg__text--larger' : ''} ${spoiler_classes}"
                    .model="${this.model}"
                    ?is_me_message="${this.is_me_message}"
                    ?is_only_emojis="${this.is_only_emojis}"
                    ?is_spoiler="${this.is_spoiler}"
                    ?is_spoiler_visible="${this.is_spoiler_visible}"
                    text="${this.model.getMessageText()}"></converse-chat-message-body>
                ${this.received && !this.is_me_message && !is_groupchat_message ? lit_html_html`<span class="fa fa-check chat-msg__receipt"></span>` : ''}
                ${this.edited ? lit_html_html`<i title="${i18n_edited}" class="fa fa-edit chat-msg__edit-modal" @click=${this.showMessageVersionsModal}></i>` : ''}
            </span>
            ${this.oob_url ? lit_html_html`<div class="chat-msg__media">${message_u.getOOBURLMarkup(converse_core_converse, this.oob_url)}</div>` : ''}
            <div class="chat-msg__error">${this.error_text || this.error}</div>
        `;
  }

  renderAvatarByline() {
    return lit_html_html`
            ${this.hats.map(h => lit_html_html`<span class="badge badge-secondary">${h.title}</span>`)}
            <time timestamp="${this.edited || this.time}" class="chat-msg__time">${this.pretty_time}</time>
        `;
  }

  showMessageVersionsModal(ev) {
    ev.preventDefault();

    if (this.message_versions_modal === undefined) {
      this.message_versions_modal = new message_versions({
        'model': this.model
      });
    }

    this.message_versions_modal.show(ev);
  }

  toggleSpoilerMessage(ev) {
    ev === null || ev === void 0 ? void 0 : ev.preventDefault();
    this.model.save({
      'is_spoiler_visible': !this.model.get('is_spoiler_visible')
    });
  }

}
converse_core_api.elements.define('converse-chat-message', message_Message);
// CONCATENATED MODULE: ./src/templates/new_day.js

/* harmony default export */ var new_day = (o => lit_html_html`
    <div class="message date-separator" data-isodate="${o.time}">
        <hr class="separator"/>
        <time class="separator-text" datetime="${o.time}"><span>${o.datestring}</span></time>
    </div>
`);
// CONCATENATED MODULE: ./node_modules/lit-html/directives/repeat.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */
 // Helper functions for manipulating parts
// TODO(kschaaf): Refactor into Part API?

const createAndInsertPart = (containerPart, beforePart) => {
  const container = containerPart.startNode.parentNode;
  const beforeNode = beforePart === undefined ? containerPart.endNode : beforePart.startNode;
  const startNode = container.insertBefore(createMarker(), beforeNode);
  container.insertBefore(createMarker(), beforeNode);
  const newPart = new parts_NodePart(containerPart.options);
  newPart.insertAfterNode(startNode);
  return newPart;
};

const updatePart = (part, value) => {
  part.setValue(value);
  part.commit();
  return part;
};

const insertPartBefore = (containerPart, part, ref) => {
  const container = containerPart.startNode.parentNode;
  const beforeNode = ref ? ref.startNode : containerPart.endNode;
  const endNode = part.endNode.nextSibling;

  if (endNode !== beforeNode) {
    reparentNodes(container, part.startNode, endNode, beforeNode);
  }
};

const removePart = part => {
  removeNodes(part.startNode.parentNode, part.startNode, part.endNode.nextSibling);
}; // Helper for generating a map of array item to its index over a subset
// of an array (used to lazily generate `newKeyToIndexMap` and
// `oldKeyToIndexMap`)


const generateMap = (list, start, end) => {
  const map = new Map();

  for (let i = start; i <= end; i++) {
    map.set(list[i], i);
  }

  return map;
}; // Stores previous ordered list of parts and map of key to index


const partListCache = new WeakMap();
const keyListCache = new WeakMap();
/**
 * A directive that repeats a series of values (usually `TemplateResults`)
 * generated from an iterable, and updates those items efficiently when the
 * iterable changes based on user-provided `keys` associated with each item.
 *
 * Note that if a `keyFn` is provided, strict key-to-DOM mapping is maintained,
 * meaning previous DOM for a given key is moved into the new position if
 * needed, and DOM will never be reused with values for different keys (new DOM
 * will always be created for new keys). This is generally the most efficient
 * way to use `repeat` since it performs minimum unnecessary work for insertions
 * and removals.
 *
 * IMPORTANT: If providing a `keyFn`, keys *must* be unique for all items in a
 * given call to `repeat`. The behavior when two or more items have the same key
 * is undefined.
 *
 * If no `keyFn` is provided, this directive will perform similar to mapping
 * items to values, and DOM will be reused against potentially different items.
 */

const repeat = directive_directive((items, keyFnOrTemplate, template) => {
  let keyFn;

  if (template === undefined) {
    template = keyFnOrTemplate;
  } else if (keyFnOrTemplate !== undefined) {
    keyFn = keyFnOrTemplate;
  }

  return containerPart => {
    if (!(containerPart instanceof parts_NodePart)) {
      throw new Error('repeat can only be used in text bindings');
    } // Old part & key lists are retrieved from the last update
    // (associated with the part for this instance of the directive)


    const oldParts = partListCache.get(containerPart) || [];
    const oldKeys = keyListCache.get(containerPart) || []; // New part list will be built up as we go (either reused from
    // old parts or created for new keys in this update). This is
    // saved in the above cache at the end of the update.

    const newParts = []; // New value list is eagerly generated from items along with a
    // parallel array indicating its key.

    const newValues = [];
    const newKeys = [];
    let index = 0;

    for (const item of items) {
      newKeys[index] = keyFn ? keyFn(item, index) : index;
      newValues[index] = template(item, index);
      index++;
    } // Maps from key to index for current and previous update; these
    // are generated lazily only when needed as a performance
    // optimization, since they are only required for multiple
    // non-contiguous changes in the list, which are less common.


    let newKeyToIndexMap;
    let oldKeyToIndexMap; // Head and tail pointers to old parts and new values

    let oldHead = 0;
    let oldTail = oldParts.length - 1;
    let newHead = 0;
    let newTail = newValues.length - 1; // Overview of O(n) reconciliation algorithm (general approach
    // based on ideas found in ivi, vue, snabbdom, etc.):
    //
    // * We start with the list of old parts and new values (and
    //   arrays of their respective keys), head/tail pointers into
    //   each, and we build up the new list of parts by updating
    //   (and when needed, moving) old parts or creating new ones.
    //   The initial scenario might look like this (for brevity of
    //   the diagrams, the numbers in the array reflect keys
    //   associated with the old parts or new values, although keys
    //   and parts/values are actually stored in parallel arrays
    //   indexed using the same head/tail pointers):
    //
    //      oldHead v                 v oldTail
    //   oldKeys:  [0, 1, 2, 3, 4, 5, 6]
    //   newParts: [ ,  ,  ,  ,  ,  ,  ]
    //   newKeys:  [0, 2, 1, 4, 3, 7, 6] <- reflects the user's new
    //                                      item order
    //      newHead ^                 ^ newTail
    //
    // * Iterate old & new lists from both sides, updating,
    //   swapping, or removing parts at the head/tail locations
    //   until neither head nor tail can move.
    //
    // * Example below: keys at head pointers match, so update old
    //   part 0 in-place (no need to move it) and record part 0 in
    //   the `newParts` list. The last thing we do is advance the
    //   `oldHead` and `newHead` pointers (will be reflected in the
    //   next diagram).
    //
    //      oldHead v                 v oldTail
    //   oldKeys:  [0, 1, 2, 3, 4, 5, 6]
    //   newParts: [0,  ,  ,  ,  ,  ,  ] <- heads matched: update 0
    //   newKeys:  [0, 2, 1, 4, 3, 7, 6]    and advance both oldHead
    //                                      & newHead
    //      newHead ^                 ^ newTail
    //
    // * Example below: head pointers don't match, but tail
    //   pointers do, so update part 6 in place (no need to move
    //   it), and record part 6 in the `newParts` list. Last,
    //   advance the `oldTail` and `oldHead` pointers.
    //
    //         oldHead v              v oldTail
    //   oldKeys:  [0, 1, 2, 3, 4, 5, 6]
    //   newParts: [0,  ,  ,  ,  ,  , 6] <- tails matched: update 6
    //   newKeys:  [0, 2, 1, 4, 3, 7, 6]    and advance both oldTail
    //                                      & newTail
    //         newHead ^              ^ newTail
    //
    // * If neither head nor tail match; next check if one of the
    //   old head/tail items was removed. We first need to generate
    //   the reverse map of new keys to index (`newKeyToIndexMap`),
    //   which is done once lazily as a performance optimization,
    //   since we only hit this case if multiple non-contiguous
    //   changes were made. Note that for contiguous removal
    //   anywhere in the list, the head and tails would advance
    //   from either end and pass each other before we get to this
    //   case and removals would be handled in the final while loop
    //   without needing to generate the map.
    //
    // * Example below: The key at `oldTail` was removed (no longer
    //   in the `newKeyToIndexMap`), so remove that part from the
    //   DOM and advance just the `oldTail` pointer.
    //
    //         oldHead v           v oldTail
    //   oldKeys:  [0, 1, 2, 3, 4, 5, 6]
    //   newParts: [0,  ,  ,  ,  ,  , 6] <- 5 not in new map: remove
    //   newKeys:  [0, 2, 1, 4, 3, 7, 6]    5 and advance oldTail
    //         newHead ^           ^ newTail
    //
    // * Once head and tail cannot move, any mismatches are due to
    //   either new or moved items; if a new key is in the previous
    //   "old key to old index" map, move the old part to the new
    //   location, otherwise create and insert a new part. Note
    //   that when moving an old part we null its position in the
    //   oldParts array if it lies between the head and tail so we
    //   know to skip it when the pointers get there.
    //
    // * Example below: neither head nor tail match, and neither
    //   were removed; so find the `newHead` key in the
    //   `oldKeyToIndexMap`, and move that old part's DOM into the
    //   next head position (before `oldParts[oldHead]`). Last,
    //   null the part in the `oldPart` array since it was
    //   somewhere in the remaining oldParts still to be scanned
    //   (between the head and tail pointers) so that we know to
    //   skip that old part on future iterations.
    //
    //         oldHead v        v oldTail
    //   oldKeys:  [0, 1, -, 3, 4, 5, 6]
    //   newParts: [0, 2,  ,  ,  ,  , 6] <- stuck: update & move 2
    //   newKeys:  [0, 2, 1, 4, 3, 7, 6]    into place and advance
    //                                      newHead
    //         newHead ^           ^ newTail
    //
    // * Note that for moves/insertions like the one above, a part
    //   inserted at the head pointer is inserted before the
    //   current `oldParts[oldHead]`, and a part inserted at the
    //   tail pointer is inserted before `newParts[newTail+1]`. The
    //   seeming asymmetry lies in the fact that new parts are
    //   moved into place outside in, so to the right of the head
    //   pointer are old parts, and to the right of the tail
    //   pointer are new parts.
    //
    // * We always restart back from the top of the algorithm,
    //   allowing matching and simple updates in place to
    //   continue...
    //
    // * Example below: the head pointers once again match, so
    //   simply update part 1 and record it in the `newParts`
    //   array.  Last, advance both head pointers.
    //
    //         oldHead v        v oldTail
    //   oldKeys:  [0, 1, -, 3, 4, 5, 6]
    //   newParts: [0, 2, 1,  ,  ,  , 6] <- heads matched: update 1
    //   newKeys:  [0, 2, 1, 4, 3, 7, 6]    and advance both oldHead
    //                                      & newHead
    //            newHead ^        ^ newTail
    //
    // * As mentioned above, items that were moved as a result of
    //   being stuck (the final else clause in the code below) are
    //   marked with null, so we always advance old pointers over
    //   these so we're comparing the next actual old value on
    //   either end.
    //
    // * Example below: `oldHead` is null (already placed in
    //   newParts), so advance `oldHead`.
    //
    //            oldHead v     v oldTail
    //   oldKeys:  [0, 1, -, 3, 4, 5, 6] <- old head already used:
    //   newParts: [0, 2, 1,  ,  ,  , 6]    advance oldHead
    //   newKeys:  [0, 2, 1, 4, 3, 7, 6]
    //               newHead ^     ^ newTail
    //
    // * Note it's not critical to mark old parts as null when they
    //   are moved from head to tail or tail to head, since they
    //   will be outside the pointer range and never visited again.
    //
    // * Example below: Here the old tail key matches the new head
    //   key, so the part at the `oldTail` position and move its
    //   DOM to the new head position (before `oldParts[oldHead]`).
    //   Last, advance `oldTail` and `newHead` pointers.
    //
    //               oldHead v  v oldTail
    //   oldKeys:  [0, 1, -, 3, 4, 5, 6]
    //   newParts: [0, 2, 1, 4,  ,  , 6] <- old tail matches new
    //   newKeys:  [0, 2, 1, 4, 3, 7, 6]   head: update & move 4,
    //                                     advance oldTail & newHead
    //               newHead ^     ^ newTail
    //
    // * Example below: Old and new head keys match, so update the
    //   old head part in place, and advance the `oldHead` and
    //   `newHead` pointers.
    //
    //               oldHead v oldTail
    //   oldKeys:  [0, 1, -, 3, 4, 5, 6]
    //   newParts: [0, 2, 1, 4, 3,   ,6] <- heads match: update 3
    //   newKeys:  [0, 2, 1, 4, 3, 7, 6]    and advance oldHead &
    //                                      newHead
    //                  newHead ^  ^ newTail
    //
    // * Once the new or old pointers move past each other then all
    //   we have left is additions (if old list exhausted) or
    //   removals (if new list exhausted). Those are handled in the
    //   final while loops at the end.
    //
    // * Example below: `oldHead` exceeded `oldTail`, so we're done
    //   with the main loop.  Create the remaining part and insert
    //   it at the new head position, and the update is complete.
    //
    //                   (oldHead > oldTail)
    //   oldKeys:  [0, 1, -, 3, 4, 5, 6]
    //   newParts: [0, 2, 1, 4, 3, 7 ,6] <- create and insert 7
    //   newKeys:  [0, 2, 1, 4, 3, 7, 6]
    //                     newHead ^ newTail
    //
    // * Note that the order of the if/else clauses is not
    //   important to the algorithm, as long as the null checks
    //   come first (to ensure we're always working on valid old
    //   parts) and that the final else clause comes last (since
    //   that's where the expensive moves occur). The order of
    //   remaining clauses is is just a simple guess at which cases
    //   will be most common.
    //
    // * TODO(kschaaf) Note, we could calculate the longest
    //   increasing subsequence (LIS) of old items in new position,
    //   and only move those not in the LIS set. However that costs
    //   O(nlogn) time and adds a bit more code, and only helps
    //   make rare types of mutations require fewer moves. The
    //   above handles removes, adds, reversal, swaps, and single
    //   moves of contiguous items in linear time, in the minimum
    //   number of moves. As the number of multiple moves where LIS
    //   might help approaches a random shuffle, the LIS
    //   optimization becomes less helpful, so it seems not worth
    //   the code at this point. Could reconsider if a compelling
    //   case arises.

    while (oldHead <= oldTail && newHead <= newTail) {
      if (oldParts[oldHead] === null) {
        // `null` means old part at head has already been used
        // below; skip
        oldHead++;
      } else if (oldParts[oldTail] === null) {
        // `null` means old part at tail has already been used
        // below; skip
        oldTail--;
      } else if (oldKeys[oldHead] === newKeys[newHead]) {
        // Old head matches new head; update in place
        newParts[newHead] = updatePart(oldParts[oldHead], newValues[newHead]);
        oldHead++;
        newHead++;
      } else if (oldKeys[oldTail] === newKeys[newTail]) {
        // Old tail matches new tail; update in place
        newParts[newTail] = updatePart(oldParts[oldTail], newValues[newTail]);
        oldTail--;
        newTail--;
      } else if (oldKeys[oldHead] === newKeys[newTail]) {
        // Old head matches new tail; update and move to new tail
        newParts[newTail] = updatePart(oldParts[oldHead], newValues[newTail]);
        insertPartBefore(containerPart, oldParts[oldHead], newParts[newTail + 1]);
        oldHead++;
        newTail--;
      } else if (oldKeys[oldTail] === newKeys[newHead]) {
        // Old tail matches new head; update and move to new head
        newParts[newHead] = updatePart(oldParts[oldTail], newValues[newHead]);
        insertPartBefore(containerPart, oldParts[oldTail], oldParts[oldHead]);
        oldTail--;
        newHead++;
      } else {
        if (newKeyToIndexMap === undefined) {
          // Lazily generate key-to-index maps, used for removals &
          // moves below
          newKeyToIndexMap = generateMap(newKeys, newHead, newTail);
          oldKeyToIndexMap = generateMap(oldKeys, oldHead, oldTail);
        }

        if (!newKeyToIndexMap.has(oldKeys[oldHead])) {
          // Old head is no longer in new list; remove
          removePart(oldParts[oldHead]);
          oldHead++;
        } else if (!newKeyToIndexMap.has(oldKeys[oldTail])) {
          // Old tail is no longer in new list; remove
          removePart(oldParts[oldTail]);
          oldTail--;
        } else {
          // Any mismatches at this point are due to additions or
          // moves; see if we have an old part we can reuse and move
          // into place
          const oldIndex = oldKeyToIndexMap.get(newKeys[newHead]);
          const oldPart = oldIndex !== undefined ? oldParts[oldIndex] : null;

          if (oldPart === null) {
            // No old part for this value; create a new one and
            // insert it
            const newPart = createAndInsertPart(containerPart, oldParts[oldHead]);
            updatePart(newPart, newValues[newHead]);
            newParts[newHead] = newPart;
          } else {
            // Reuse old part
            newParts[newHead] = updatePart(oldPart, newValues[newHead]);
            insertPartBefore(containerPart, oldPart, oldParts[oldHead]); // This marks the old part as having been used, so that
            // it will be skipped in the first two checks above

            oldParts[oldIndex] = null;
          }

          newHead++;
        }
      }
    } // Add parts for any remaining new values


    while (newHead <= newTail) {
      // For all remaining additions, we insert before last new
      // tail, since old pointers are no longer valid
      const newPart = createAndInsertPart(containerPart, newParts[newTail + 1]);
      updatePart(newPart, newValues[newHead]);
      newParts[newHead++] = newPart;
    } // Remove any remaining unused old parts


    while (oldHead <= oldTail) {
      const oldPart = oldParts[oldHead++];

      if (oldPart !== null) {
        removePart(oldPart);
      }
    } // Save order of new parts for next round


    partListCache.set(containerPart, newParts);
    keyListCache.set(containerPart, newKeys);
  };
});
// CONCATENATED MODULE: ./src/components/message-history.js









const i18n_no_history = i18n_('No message history available.');

const tpl_message = o => lit_html_html`
    <converse-chat-message
        .chatview=${o.chatview}
        .hats=${o.hats}
        .model=${o.model}
        ?correcting=${o.correcting}
        ?editable=${o.editable}
        ?has_mentions=${o.has_mentions}
        ?is_delayed=${o.is_delayed}
        ?is_encrypted=${!!o.is_encrypted}
        ?is_first_unread=${o.is_first_unread}
        ?is_me_message=${o.is_me_message}
        ?is_only_emojis=${o.is_only_emojis}
        ?is_retracted=${o.is_retracted}
        ?is_spoiler=${o.is_spoiler}
        ?is_spoiler_visible=${o.is_spoiler_visible}
        ?retractable=${o.retractable}
        edited=${o.edited || ''}
        error=${o.error || ''}
        error_text=${o.error_text || ''}
        filename=${o.filename || ''}
        filesize=${o.filesize || ''}
        from=${o.from}
        message_type=${o.type || ''}
        moderated_by=${o.moderated_by || ''}
        moderation_reason=${o.moderation_reason || ''}
        msgid=${o.msgid}
        occupant_affiliation=${o.model.occupant ? o.model.occupant.get('affiliation') : ''}
        occupant_role=${o.model.occupant ? o.model.occupant.get('role') : ''}
        oob_url=${o.oob_url || ''}
        pretty_type=${o.pretty_type}
        progress=${o.progress || 0}
        reason=${o.reason || ''}
        received=${o.received || ''}
        retry_event_id=${o.retry_event_id || ''}
        sender=${o.sender}
        spoiler_hint=${o.spoiler_hint || ''}
        subject=${o.subject || ''}
        time=${o.time}
        username=${o.username}></converse-chat-message>
`; // Return a TemplateResult indicating a new day if the passed in message is
// more than a day later than its predecessor.


function getDayIndicator(model) {
  const models = model.collection.models;
  const idx = models.indexOf(model);
  const prev_model = models[idx - 1];

  if (!prev_model || dayjs_min_default()(model.get('time')).isAfter(dayjs_min_default()(prev_model.get('time')), 'day')) {
    const day_date = dayjs_min_default()(model.get('time')).startOf('day');
    return new_day({
      'type': 'date',
      'time': day_date.toISOString(),
      'datestring': day_date.format("dddd MMM Do YYYY")
    });
  }
} // This is set to _converse so that it can be overriden. An attempt was made to use
// a hook instead, but hook returns a promise and it forces the asynchronicity up
// to the render method.


converse_core_converse.getHats = function (model) {
  if (model.get('type') === 'groupchat') {
    var _model$occupant;

    const allowed_hats = converse_core_api.settings.get('muc_hats').filter(hat => hat).map(hat => hat.toLowerCase());
    let vcard_roles = [];

    if (allowed_hats.includes('vcard_roles')) {
      vcard_roles = model.vcard ? model.vcard.get('role') : null;
      vcard_roles = vcard_roles ? vcard_roles.split(',').filter(hat => hat).map(hat => ({
        title: hat
      })) : [];
    }

    const muc_role = model.occupant ? [model.occupant.get('role')] : [];
    const muc_affiliation = model.occupant ? [model.occupant.get('affiliation')] : [];
    const affiliation_role_hats = [...muc_role, ...muc_affiliation].filter(hat => hat).filter(hat => allowed_hats.includes(hat.toLowerCase())).map(hat => ({
      title: hat
    }));
    const hats = allowed_hats.includes('xep317') ? ((_model$occupant = model.occupant) === null || _model$occupant === void 0 ? void 0 : _model$occupant.get('hats')) || [] : [];
    return [...hats, ...vcard_roles, ...affiliation_role_hats];
  }

  return [];
};

function getDerivedMessageProps(chatbox, model) {
  const is_groupchat = model.get('type') === 'groupchat';
  return {
    'has_mentions': is_groupchat && model.get('sender') === 'them' && chatbox.isUserMentioned(model),
    'hats': converse_core_converse.getHats(model),
    'is_first_unread': chatbox.get('first_unread_id') === model.get('id'),
    'is_me_message': model.isMeCommand(),
    'is_retracted': model.get('retracted') || model.get('moderated') === 'retracted',
    'username': model.getDisplayName()
  };
}
class message_history_MessageHistory extends element_CustomElement {
  static get properties() {
    return {
      chatview: {
        type: Object
      },
      messages: {
        type: Array
      }
    };
  }

  render() {
    const msgs = this.messages;
    return msgs.length ? lit_html_html`${repeat(msgs, m => m.get('id'), m => this.renderMessage(m))}` : lit_html_html`<div class="empty-history-feedback form-help"><span>${i18n_no_history}</span></div>`;
  }

  renderMessage(model) {
    if (model.get('dangling_retraction') || model.get('is_only_key')) {
      return '';
    }

    const day = getDayIndicator(model);
    const templates = day ? [day] : [];
    const message = tpl_message(Object.assign(model.toJSON(), getDerivedMessageProps(this.chatview.model, model), {
      'chatview': this.chatview,
      model
    }));
    return [...templates, message];
  }

}
converse_core_api.elements.define('converse-message-history', message_history_MessageHistory);
// EXTERNAL MODULE: ./node_modules/xss/dist/xss.js
var xss = __webpack_require__(14);
var xss_default = /*#__PURE__*/__webpack_require__.n(xss);

// CONCATENATED MODULE: ./node_modules/lit-html/directives/unsafe-html.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */

 // For each part, remember the value that was last rendered to the part by the
// unsafeHTML directive, and the DocumentFragment that was last set as a value.
// The DocumentFragment is used as a unique key to check if the last value
// rendered to the part was with unsafeHTML. If not, we'll always re-render the
// value passed to unsafeHTML.

const unsafe_html_previousValues = new WeakMap();
/**
 * Renders the result as HTML, rather than text.
 *
 * Note, this is unsafe to use with any user-provided input that hasn't been
 * sanitized or escaped, as it may lead to cross-site-scripting
 * vulnerabilities.
 */

const unsafeHTML = directive_directive(value => part => {
  if (!(part instanceof parts_NodePart)) {
    throw new Error('unsafeHTML can only be used in text bindings');
  }

  const previousValue = unsafe_html_previousValues.get(part);

  if (previousValue !== undefined && isPrimitive(value) && value === previousValue.value && part.value === previousValue.fragment) {
    return;
  }

  const template = document.createElement('template');
  template.innerHTML = value; // innerHTML casts to string internally

  const fragment = document.importNode(template.content, true);
  part.setValue(fragment);
  unsafe_html_previousValues.set(part, {
    value,
    fragment
  });
});
// CONCATENATED MODULE: ./src/components/chat_content.js






class chat_content_ChatContent extends element_CustomElement {
  static get properties() {
    return {
      chatview: {
        type: Object
      },
      messages: {
        type: Array
      },
      notifications: {
        type: String
      }
    };
  }

  render() {
    const notifications = xss_default.a.filterXSS(this.notifications, {
      'whiteList': {}
    });
    return lit_html_html`
            <converse-message-history
                .chatview=${this.chatview}
                .messages=${this.messages}>
            </converse-message-history>
            <div class="chat-content__notifications">${unsafeHTML(notifications)}</div>
        `;
  }

}
converse_core_api.elements.define('converse-chat-content', chat_content_ChatContent);
// CONCATENATED MODULE: ./src/components/icons.js
/**
 * @module icons.js
 * @copyright Alfredo Medrano Sánchez and the Converse.js contributors
 * @description
 *  Component inspired by the one from fa-icons
 *  https://github.com/obsidiansoft-io/fa-icons/blob/master/LICENSE
 * @license Mozilla Public License (MPLv2)
 */



class icons_ConverseIcon extends element_CustomElement {
  static get properties() {
    return {
      color: String,
      class_name: {
        attribute: "class"
      },
      style: String,
      size: String
    };
  }

  static get styles() {
    return css`
            :host {
                display: inline-block;
                padding: 0;
                margin: 0;
            }
        `;
  }

  constructor() {
    super();
    this.class_name = "";
    this.style = "";
    this.size = "";
    this.color = "";
  }

  getSource() {
    return `#icon-${this.class_name.split(" ")[1].replace("fa-", "")}`;
  }

  getStyles() {
    return `
            ${this.size ? `width: ${this.size};` : ''}
            ${this.size ? `height: ${this.size};` : ''}
            ${this.color ? `fill: ${this.color};` : ''}
            ${this.style}
        `;
  }

  render() {
    return lit_html_html`<svg .style="${this.getStyles()}"> <use href="${this.getSource()}"> </use> </svg>`;
  }

}

customElements.define("converse-icon", icons_ConverseIcon);
// CONCATENATED MODULE: ./src/components/help_messages.js






class help_messages_ChatHelp extends element_CustomElement {
  static get properties() {
    return {
      chat_type: {
        type: String
      },
      messages: {
        type: Array
      },
      model: {
        type: Object
      },
      type: {
        type: String
      }
    };
  }

  render() {
    const isodate = new Date().toISOString();
    return [lit_html_html`<converse-icon class="fas fa-times close-chat-help"
                    @click=${this.close}
                    path-prefix="${converse_core_api.settings.get("assets_path")}"
                    size="1em"></converse-icon>`, ...this.messages.map(m => this.renderHelpMessage({
      isodate,
      'markup': xss_default.a.filterXSS(m, {
        'whiteList': {
          'strong': []
        }
      })
    }))];
  }

  close() {
    this.model.set({
      'show_help_messages': false
    });
  }

  renderHelpMessage(o) {
    return lit_html_html`<div class="message chat-${this.type}" data-isodate="${o.isodate}">${unsafeHTML(o.markup)}</div>`;
  }

}
converse_core_api.elements.define('converse-chat-help', help_messages_ChatHelp);
// CONCATENATED MODULE: ./src/templates/emoji_picker.js



const emoji_picker_u = converse.env.utils;

const emoji_category = o => {
  return lit_html_html`
        <li data-category="${o.category}"
            class="emoji-category ${o.category} ${o.current_category === o.category ? 'picked' : ''}"
            title="${i18n_(converse_core_converse.emoji_category_labels[o.category])}">

            <a class="pick-category"
               @click=${o.onCategoryPicked}
               href="#emoji-picker-${o.category}"
               data-category="${o.category}">${o.emoji} </a>
        </li>
    `;
};

const emoji_picker_header = o => {
  const cats = converse_core_api.settings.get('emoji_categories');

  const transform = c => cats[c] ? emoji_category(Object.assign({
    'category': c,
    'emoji': o.sn2Emoji(cats[c])
  }, o)) : '';

  return lit_html_html`<ul>${Object.keys(cats).map(transform)}</ul>`;
};

const emoji_item = o => {
  return lit_html_html`
        <li class="emoji insert-emoji ${o.shouldBeHidden(o.emoji.sn) ? 'hidden' : ''}" data-emoji="${o.emoji.sn}" title="${o.emoji.sn}">
            <a href="#" @click=${o.insertEmoji} data-emoji="${o.emoji.sn}">${emoji_picker_u.shortnamesToEmojis(o.emoji.sn)}</a>
        </li>
    `;
};

const tpl_search_results = o => {
  const i18n_search_results = i18n_('Search results');

  return lit_html_html`
        <span ?hidden=${!o.query} class="emoji-lists__container emojis-lists__container--search">
        <a id="emoji-picker-search-results" class="emoji-category__heading">${i18n_search_results}</a>
        <ul class="emoji-picker">
            ${o.search_results.map(emoji => emoji_item(Object.assign({
    emoji
  }, o)))}
        </ul>
        </span>
    `;
};

const emojis_for_category = o => {
  return lit_html_html`
        <a id="emoji-picker-${o.category}" class="emoji-category__heading" data-category="${o.category}">${i18n_(converse_core_api.settings.get('emoji_category_labels')[o.category])}</a>
        <ul class="emoji-picker" data-category="${o.category}">
            ${Object.values(converse.emojis.json[o.category]).map(emoji => emoji_item(Object.assign({
    emoji
  }, o)))}
        </ul>`;
};

const tpl_all_emojis = o => {
  const cats = converse_core_api.settings.get('emoji_categories');
  return lit_html_html`
        <span ?hidden=${o.query} class="emoji-lists__container emoji-lists__container--browse">
            ${Object.keys(cats).map(c => cats[c] ? emojis_for_category(Object.assign({
    'category': c
  }, o)) : '')}
        </span>`;
};

const skintone_emoji = o => {
  return lit_html_html`
        <li data-skintone="${o.skintone}" class="emoji-skintone ${o.current_skintone === o.skintone ? 'picked' : ''}">
            <a class="pick-skintone" href="#" data-skintone="${o.skintone}" @click=${o.onSkintonePicked}>${emoji_picker_u.shortnamesToEmojis(':' + o.skintone + ':')}</a>
        </li>`;
};

const tpl_emoji_picker = o => {
  const i18n_search = i18n_('Search');

  const skintones = ['tone1', 'tone2', 'tone3', 'tone4', 'tone5'];
  return lit_html_html`
        <div class="emoji-picker__header">
            <input class="form-control emoji-search" name="emoji-search" placeholder="${i18n_search}"
                .value=${o.query || ''}
                @keydown=${o.onSearchInputKeyDown}
                @blur=${o.onSearchInputBlurred}
                @focus=${o.onSearchInputFocus}>
            ${o.query ? '' : emoji_picker_header(o)}
        </div>
        ${o.render_emojis ? lit_html_html`<converse-emoji-picker-content
                .chatview=${o.chatview}
                .model=${o.model}
                .search_results="${o.search_results}"
                current_skintone="${o.current_skintone}"
                query="${o.query}"></converse-emoji-picker-content>` : ''}

        <div class="emoji-skintone-picker">
            <label>Skin tone</label>
            <ul>${skintones.map(skintone => skintone_emoji(Object.assign({
    skintone
  }, o)))}</ul>
        </div>`;
};
// CONCATENATED MODULE: ./src/components/emoji-picker-content.js




const {
  sizzle: emoji_picker_content_sizzle
} = converse.env;
class emoji_picker_content_EmojiPickerContent extends element_CustomElement {
  static get properties() {
    return {
      'chatview': {
        type: Object
      },
      'search_results': {
        type: Array
      },
      'current_skintone': {
        type: String
      },
      'model': {
        type: Object
      },
      'query': {
        type: String
      }
    };
  }

  render() {
    const props = {
      'current_skintone': this.current_skintone,
      'insertEmoji': ev => this.insertEmoji(ev),
      'query': this.query,
      'search_results': this.search_results,
      'shouldBeHidden': shortname => this.shouldBeHidden(shortname)
    };
    return lit_html_html`
          <div class="emoji-picker__lists">
              ${tpl_search_results(props)}
              ${tpl_all_emojis(props)}
          </div>
      `;
  }

  firstUpdated() {
    this.initIntersectionObserver();
  }

  initIntersectionObserver() {
    if (!window.IntersectionObserver) {
      return;
    }

    if (this.observer) {
      this.observer.disconnect();
    } else {
      const options = {
        root: this.querySelector('.emoji-picker__lists'),
        threshold: [0.1]
      };

      const handler = ev => this.setCategoryOnVisibilityChange(ev);

      this.observer = new IntersectionObserver(handler, options);
    }

    emoji_picker_content_sizzle('.emoji-picker', this).forEach(a => this.observer.observe(a));
  }

  setCategoryOnVisibilityChange(ev) {
    const selected = this.parentElement.navigator.selected;
    const intersection_with_selected = ev.filter(i => i.target.contains(selected)).pop();
    let current; // Choose the intersection that contains the currently selected
    // element, or otherwise the one with the largest ratio.

    if (intersection_with_selected) {
      current = intersection_with_selected;
    } else {
      current = ev.reduce((p, c) => c.intersectionRatio >= ((p === null || p === void 0 ? void 0 : p.intersectionRatio) || 0) ? c : p, null);
    }

    if (current && current.isIntersecting) {
      const category = current.target.getAttribute('data-category');

      if (category !== this.model.get('current_category')) {
        this.parentElement.preserve_scroll = true;
        this.model.save({
          'current_category': category
        });
      }
    }
  }

  insertEmoji(ev) {
    ev.preventDefault();
    ev.stopPropagation();
    const target = ev.target.nodeName === 'IMG' ? ev.target.parentElement : ev.target;
    this.parentElement.insertIntoTextArea(target.getAttribute('data-emoji'));
  }

  shouldBeHidden(shortname) {
    // Helper method for the template which decides whether an
    // emoji should be hidden, based on which skin tone is
    // currently being applied.
    if (shortname.includes('_tone')) {
      if (!this.current_skintone || !shortname.includes(this.current_skintone)) {
        return true;
      }
    } else {
      if (this.current_skintone && converse.emojis.toned.includes(shortname)) {
        return true;
      }
    }

    if (this.query && !converse_core_converse.FILTER_CONTAINS(shortname, this.query)) {
      return true;
    }

    return false;
  }

}
converse_core_api.elements.define('converse-emoji-picker-content', emoji_picker_content_EmojiPickerContent);
// CONCATENATED MODULE: ./src/components/emoji-picker.js










const components_emoji_picker_u = converse.env.utils;
class emoji_picker_EmojiPicker extends element_CustomElement {
  static get properties() {
    return {
      'chatview': {
        type: Object
      },
      'current_category': {
        type: String,
        'reflect': true
      },
      'current_skintone': {
        type: String,
        'reflect': true
      },
      'model': {
        type: Object
      },
      'query': {
        type: String,
        'reflet': true
      },
      // This is an optimization, we lazily render the emoji picker, otherwise tests slow to a crawl.
      'render_emojis': {
        type: Boolean
      }
    };
  }

  firstUpdated() {
    this.listenTo(this.model, 'change', o => this.onModelChanged(o.changed));
    this.initArrowNavigation();
  }

  constructor() {
    super();
    this._search_results = [];
    this.debouncedFilter = lodash_es_debounce(input => this.model.set({
      'query': input.value
    }), 250);
    this.registerEvents();
  }

  get search_results() {
    return this._search_results;
  }

  set search_results(value) {
    this._search_results = value;
    this.requestUpdate();
  }

  render() {
    return tpl_emoji_picker({
      'chatview': this.chatview,
      'current_category': this.current_category,
      'current_skintone': this.current_skintone,
      'model': this.model,
      'onCategoryPicked': ev => this.chooseCategory(ev),
      'onSearchInputBlurred': ev => this.chatview.emitFocused(ev),
      'onSearchInputFocus': ev => this.onSearchInputFocus(ev),
      'onSearchInputKeyDown': ev => this.onKeyDown(ev),
      'onSkintonePicked': ev => this.chooseSkinTone(ev),
      'query': this.query,
      'search_results': this.search_results,
      'render_emojis': this.render_emojis,
      'sn2Emoji': shortname => components_emoji_picker_u.shortnamesToEmojis(this.getTonedShortname(shortname))
    });
  }

  updated(changed) {
    changed.has('query') && this.updateSearchResults(changed);
    changed.has('current_category') && this.setScrollPosition();
  }

  onModelChanged(changed) {
    if ('current_category' in changed) this.current_category = changed.current_category;
    if ('current_skintone' in changed) this.current_skintone = changed.current_skintone;
    if ('query' in changed) this.query = changed.query;
  }

  setScrollPosition() {
    if (this.preserve_scroll) {
      this.preserve_scroll = false;
      return;
    }

    const el = this.querySelector('.emoji-lists__container--browse');
    const heading = this.querySelector(`#emoji-picker-${this.current_category}`);

    if (heading) {
      // +4 due to 2px padding on list elements
      el.scrollTop = heading.offsetTop - heading.offsetHeight * 3 + 4;
    }
  }

  updateSearchResults(changed) {
    const old_query = changed.get('query');
    const contains = converse_core_converse.FILTER_CONTAINS;

    if (this.query) {
      if (this.query === old_query) {
        return this.search_results;
      } else if (old_query && this.query.includes(old_query)) {
        this.search_results = this.search_results.filter(e => contains(e.sn, this.query));
      } else {
        this.search_results = converse.emojis.list.filter(e => contains(e.sn, this.query));
      }
    } else if (this.search_results.length) {
      // Avoid re-rendering by only setting to new empty array if it wasn't empty before
      this.search_results = [];
    }

    this.requestUpdate();
  }

  registerEvents() {
    this.onGlobalKeyDown = ev => this._onGlobalKeyDown(ev);

    const body = document.querySelector('body');
    body.addEventListener('keydown', this.onGlobalKeyDown);
  }

  connectedCallback() {
    super.connectedCallback();
    this.registerEvents();
  }

  disconnectedCallback() {
    const body = document.querySelector('body');
    body.removeEventListener('keydown', this.onGlobalKeyDown);
    super.disconnectedCallback();
  }

  _onGlobalKeyDown(ev) {
    if (!this.navigator) {
      return;
    }

    if (ev.keyCode === converse.keycodes.ENTER && this.navigator.selected && components_emoji_picker_u.isVisible(this)) {
      this.onEnterPressed(ev);
    } else if (ev.keyCode === converse.keycodes.DOWN_ARROW && !this.navigator.enabled && components_emoji_picker_u.isVisible(this)) {
      this.enableArrowNavigation(ev);
    }
  }

  setCategoryForElement(el) {
    const old_category = this.current_category;
    const category = (el === null || el === void 0 ? void 0 : el.getAttribute('data-category')) || old_category;

    if (old_category !== category) {
      this.model.save({
        'current_category': category
      });
    }
  }

  insertIntoTextArea(value) {
    this.chatview.onEmojiReceivedFromPicker(value);
    this.model.set({
      'autocompleting': null,
      'query': '',
      'ac_position': null
    });
  }

  chooseSkinTone(ev) {
    ev.preventDefault();
    ev.stopPropagation();
    const target = ev.target.nodeName === 'IMG' ? ev.target.parentElement : ev.target;
    const skintone = target.getAttribute("data-skintone").trim();

    if (this.current_skintone === skintone) {
      this.model.save({
        'current_skintone': ''
      });
    } else {
      this.model.save({
        'current_skintone': skintone
      });
    }
  }

  chooseCategory(ev) {
    ev.preventDefault && ev.preventDefault();
    ev.stopPropagation && ev.stopPropagation();
    const el = ev.target.matches('li') ? ev.target : components_emoji_picker_u.ancestor(ev.target, 'li');
    this.setCategoryForElement(el);
    this.navigator.select(el);
    !this.navigator.enabled && this.navigator.enable();
  }

  onKeyDown(ev) {
    if (ev.keyCode === converse.keycodes.TAB) {
      if (ev.target.value) {
        ev.preventDefault();
        const match = converse.emojis.shortnames.find(sn => converse_core_converse.FILTER_CONTAINS(sn, ev.target.value));
        match && this.model.set({
          'query': match
        });
      } else if (!this.navigator.enabled) {
        this.enableArrowNavigation(ev);
      }
    } else if (ev.keyCode === converse.keycodes.DOWN_ARROW && !this.navigator.enabled) {
      this.enableArrowNavigation(ev);
    } else if (ev.keyCode === converse.keycodes.ENTER) {
      this.onEnterPressed(ev);
    } else if (ev.keyCode === converse.keycodes.ESCAPE) {
      components_emoji_picker_u.ancestor(this, 'converse-emoji-dropdown').hideMenu();
      this.chatview.el.querySelector('.chat-textarea').focus();
      ev.stopPropagation();
      ev.preventDefault();
    } else if (ev.keyCode !== converse.keycodes.ENTER && ev.keyCode !== converse.keycodes.DOWN_ARROW) {
      this.debouncedFilter(ev.target);
    }
  }

  onEnterPressed(ev) {
    if (ev.emoji_keypress_handled) {
      // Prevent the emoji from being inserted a 2nd time due to this
      // method being called by two event handlers: onKeyDown and _onGlobalKeyDown
      return;
    }

    ev.preventDefault();
    ev.stopPropagation();
    ev.emoji_keypress_handled = true;

    if (converse.emojis.shortnames.includes(ev.target.value)) {
      this.insertIntoTextArea(ev.target.value);
    } else if (this.search_results.length === 1) {
      this.insertIntoTextArea(this.search_results[0].sn);
    } else if (this.navigator.selected && this.navigator.selected.matches('.insert-emoji')) {
      this.insertIntoTextArea(this.navigator.selected.getAttribute('data-emoji'));
    } else if (this.navigator.selected && this.navigator.selected.matches('.emoji-category')) {
      this.chooseCategory({
        'target': this.navigator.selected
      });
    }
  }

  onSearchInputFocus(ev) {
    this.chatview.emitBlurred(ev);
    this.disableArrowNavigation();
  }

  getTonedShortname(shortname) {
    if (converse.emojis.toned.includes(shortname) && this.current_skintone) {
      return `${shortname.slice(0, shortname.length - 1)}_${this.current_skintone}:`;
    }

    return shortname;
  }

  initArrowNavigation() {
    if (!this.navigator) {
      const default_selector = 'li:not(.hidden):not(.emoji-skintone), .emoji-search';
      const options = {
        'jump_to_picked': '.emoji-category',
        'jump_to_picked_selector': '.emoji-category.picked',
        'jump_to_picked_direction': dom_navigator.DIRECTION.down,
        'picked_selector': '.picked',
        'scroll_container': this.querySelector('.emoji-picker__lists'),
        'getSelector': direction => {
          if (direction === dom_navigator.DIRECTION.down) {
            const c = this.navigator.selected && this.navigator.selected.getAttribute('data-category');
            return c ? `ul[data-category="${c}"] li:not(.hidden):not(.emoji-skintone), .emoji-search` : default_selector;
          } else {
            return default_selector;
          }
        },
        'onSelected': el => {
          el.matches('.insert-emoji') && this.setCategoryForElement(el.parentElement);
          el.matches('.insert-emoji, .emoji-category') && el.firstElementChild.focus();
          el.matches('.emoji-search') && el.focus();
        }
      };
      this.navigator = new dom_navigator(this, options);
    }
  }

  disableArrowNavigation() {
    this.navigator.disable();
  }

  enableArrowNavigation(ev) {
    var _ev$preventDefault, _ev$stopPropagation;

    ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
    ev === null || ev === void 0 ? void 0 : (_ev$stopPropagation = ev.stopPropagation) === null || _ev$stopPropagation === void 0 ? void 0 : _ev$stopPropagation.call(ev);
    this.disableArrowNavigation();
    this.navigator.enable();
    this.navigator.handleKeydown(ev);
  }

}
class emoji_picker_EmojiDropdown extends dropdown_BaseDropdown {
  static get properties() {
    return {
      chatview: {
        type: Object
      }
    };
  }

  constructor() {
    super(); // This is an optimization, we lazily render the emoji picker, otherwise tests slow to a crawl.

    this.render_emojis = false;
  }

  initModel() {
    if (!this.init_promise) {
      this.init_promise = (async () => {
        await converse_core_api.emojis.initialize();
        const id = `converse.emoji-${converse_core_converse.bare_jid}-${this.chatview.model.get('jid')}`;
        this.model = new converse_core_converse.EmojiPicker({
          'id': id
        });
        this.model.browserStorage = converse_core_converse.createStore(id);
        await new Promise(resolve => this.model.fetch({
          'success': resolve,
          'error': resolve
        })); // We never want still be in the autocompleting state upon page load

        this.model.set({
          'autocompleting': null,
          'ac_position': null
        });
      })();
    }

    return this.init_promise;
  }

  render() {
    return lit_html_html`
            <div class="dropup">
                <button class="toggle-emojis"
                        title="${i18n_('Insert emojis')}"
                        data-toggle="dropdown"
                        aria-haspopup="true"
                        aria-expanded="false">
                    <converse-icon
                        class="fa fa-smile "
                        path-prefix="${converse_core_api.settings.get('assets_path')}"
                        size="1em"></converse-icon>
                </button>
                <div class="dropdown-menu">
                    ${until(this.initModel().then(() => lit_html_html`
                        <converse-emoji-picker
                                .chatview=${this.chatview}
                                .model=${this.model}
                                ?render_emojis=${this.render_emojis}
                                current_category="${this.model.get('current_category') || ''}"
                                current_skintone="${this.model.get('current_skintone') || ''}"
                                query="${this.model.get('query') || ''}"
                        ></converse-emoji-picker>`), '')}
                </div>
            </div>`;
  }

  connectedCallback() {
    super.connectedCallback();
    this.render_emojis = false;
  }

  toggleMenu(ev) {
    ev.stopPropagation();
    ev.preventDefault();

    if (components_emoji_picker_u.hasClass('show', this.menu)) {
      if (components_emoji_picker_u.ancestor(ev.target, '.toggle-emojis')) {
        this.hideMenu();
      }
    } else {
      this.showMenu();
    }
  }

  async showMenu() {
    await this.initModel();

    if (!this.render_emojis) {
      // Trigger an update so that emojis are rendered
      this.render_emojis = true;
      await this.requestUpdate();
    }

    super.showMenu();
    setTimeout(() => {
      var _this$querySelector;

      return (_this$querySelector = this.querySelector('.emoji-search')) === null || _this$querySelector === void 0 ? void 0 : _this$querySelector.focus();
    });
  }

}
converse_core_api.elements.define('converse-emoji-dropdown', emoji_picker_EmojiDropdown);
converse_core_api.elements.define('converse-emoji-picker', emoji_picker_EmojiPicker);
// CONCATENATED MODULE: ./src/components/toolbar.js






const toolbar_Strophe = converse.env.Strophe;
class toolbar_ChatToolbar extends element_CustomElement {
  static get properties() {
    return {
      chatview: {
        type: Object
      },
      // Used by getToolbarButtons hooks
      composing_spoiler: {
        type: Boolean
      },
      hidden_occupants: {
        type: Boolean
      },
      is_groupchat: {
        type: Boolean
      },
      message_limit: {
        type: Number
      },
      model: {
        type: Object
      },
      show_call_button: {
        type: Boolean
      },
      show_emoji_button: {
        type: Boolean
      },
      show_occupants_toggle: {
        type: Boolean
      },
      show_send_button: {
        type: Boolean
      },
      show_spoiler_button: {
        type: Boolean
      },
      show_toolbar: {
        type: Boolean
      }
    };
  }

  render() {
    const i18n_send_message = i18n_('Send the message');

    return lit_html_html`
            ${this.show_toolbar ? lit_html_html`<span class="toolbar-buttons">${until(this.getButtons(), '')}</span>` : ''}
            ${this.show_send_button ? lit_html_html`<button type="submit" class="btn send-button fa fa-paper-plane" title="${i18n_send_message}"></button>` : ''}
        `;
  }

  getButtons() {
    const buttons = [];

    if (this.show_emoji_button) {
      buttons.push(lit_html_html`<converse-emoji-dropdown .chatview=${this.chatview}></converse-dropdown>`);
    }

    if (this.show_call_button) {
      const i18n_start_call = i18n_('Start a call');

      buttons.push(lit_html_html`
                <button class="toggle-call" @click=${this.toggleCall} title="${i18n_start_call}">
                    <converse-icon class="fa fa-phone" path-prefix="/dist" size="1em"></converse-icon>
                </button>`);
    }

    const i18n_chars_remaining = i18n_('Message characters remaining');

    const message_limit = converse_core_api.settings.get('message_limit');

    if (message_limit) {
      buttons.push(lit_html_html`<span class="right message-limit" title="${i18n_chars_remaining}">${this.message_limit}</span>`);
    }

    if (this.show_spoiler_button) {
      buttons.push(this.getSpoilerButton());
    }

    const http_upload_promise = converse_core_api.disco.supports(toolbar_Strophe.NS.HTTPUPLOAD, converse_core_converse.domain);
    buttons.push(lit_html_html`${until(http_upload_promise.then(is_supported => this.getHTTPUploadButton(is_supported)), '')}`);

    if (this.show_occupants_toggle) {
      const i18n_hide_occupants = i18n_('Hide participants');

      const i18n_show_occupants = i18n_('Show participants');

      buttons.push(lit_html_html`
                <button class="toggle_occupants right"
                        title="${this.hidden_occupants ? i18n_show_occupants : i18n_hide_occupants}"
                        @click=${this.toggleOccupants}>
                    <converse-icon class="fa ${this.hidden_occupants ? `fa-angle-double-left` : `fa-angle-double-right`}"
                             path-prefix="${converse_core_api.settings.get('assets_path')}" size="1em"></converse-icon>
                </button>`);
    }
    /**
     * *Hook* which allows plugins to add more buttons to a chat's toolbar
     * @event _converse#getToolbarButtons
     */


    return converse_core_converse.api.hook('getToolbarButtons', this, buttons);
  }

  getHTTPUploadButton(is_supported) {
    if (is_supported) {
      const i18n_choose_file = i18n_('Choose a file to send');

      return lit_html_html`
                <button title="${i18n_choose_file}" @click=${this.toggleFileUpload}>
                    <converse-icon class="fa fa-paperclip"
                        path-prefix="${converse_core_api.settings.get('assets_path')}"
                        size="1em"></converse-icon>
                </button>
                <input type="file" @change=${this.onFileSelection} class="fileupload" multiple="" style="display:none"/>`;
    } else {
      return '';
    }
  }

  getSpoilerButton() {
    const model = this.model;

    if (!this.is_groupchat && model.presence.resources.length === 0) {
      return;
    }

    let i18n_toggle_spoiler;

    if (this.composing_spoiler) {
      i18n_toggle_spoiler = i18n_("Click to write as a normal (non-spoiler) message");
    } else {
      i18n_toggle_spoiler = i18n_("Click to write your message as a spoiler");
    }

    const markup = lit_html_html`
            <button class="toggle-compose-spoiler"
                    title="${i18n_toggle_spoiler}"
                    @click=${this.toggleComposeSpoilerMessage}>
                <converse-icon class="fa ${this.composing_spoiler ? 'fa-eye-slash' : 'fa-eye'}"
                         path-prefix="${converse_core_api.settings.get('assets_path')}"
                         size="1em"></converse-icon>
            </button>`;

    if (this.is_groupchat) {
      return markup;
    } else {
      const contact_jid = model.get('jid');
      const spoilers_promise = Promise.all(model.presence.resources.map(r => converse_core_api.disco.supports(toolbar_Strophe.NS.SPOILER, `${contact_jid}/${r.get('name')}`))).then(results => results.reduce((acc, val) => acc && val, true));
      return lit_html_html`${until(spoilers_promise.then(() => markup), '')}`;
    }
  }

  toggleFileUpload(ev) {
    var _ev$preventDefault, _ev$stopPropagation;

    ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
    ev === null || ev === void 0 ? void 0 : (_ev$stopPropagation = ev.stopPropagation) === null || _ev$stopPropagation === void 0 ? void 0 : _ev$stopPropagation.call(ev);
    this.querySelector('.fileupload').click();
  }

  onFileSelection(evt) {
    this.model.sendFiles(evt.target.files);
  }

  toggleComposeSpoilerMessage(ev) {
    var _ev$preventDefault2, _ev$stopPropagation2;

    ev === null || ev === void 0 ? void 0 : (_ev$preventDefault2 = ev.preventDefault) === null || _ev$preventDefault2 === void 0 ? void 0 : _ev$preventDefault2.call(ev);
    ev === null || ev === void 0 ? void 0 : (_ev$stopPropagation2 = ev.stopPropagation) === null || _ev$stopPropagation2 === void 0 ? void 0 : _ev$stopPropagation2.call(ev);
    this.model.set('composing_spoiler', !this.model.get('composing_spoiler'));
  }

  toggleOccupants(ev) {
    var _ev$preventDefault3, _ev$stopPropagation3;

    ev === null || ev === void 0 ? void 0 : (_ev$preventDefault3 = ev.preventDefault) === null || _ev$preventDefault3 === void 0 ? void 0 : _ev$preventDefault3.call(ev);
    ev === null || ev === void 0 ? void 0 : (_ev$stopPropagation3 = ev.stopPropagation) === null || _ev$stopPropagation3 === void 0 ? void 0 : _ev$stopPropagation3.call(ev);
    this.model.save({
      'hidden_occupants': !this.model.get('hidden_occupants')
    });
  }

  toggleCall(ev) {
    var _ev$preventDefault4, _ev$stopPropagation4;

    ev === null || ev === void 0 ? void 0 : (_ev$preventDefault4 = ev.preventDefault) === null || _ev$preventDefault4 === void 0 ? void 0 : _ev$preventDefault4.call(ev);
    ev === null || ev === void 0 ? void 0 : (_ev$stopPropagation4 = ev.stopPropagation) === null || _ev$stopPropagation4 === void 0 ? void 0 : _ev$stopPropagation4.call(ev);
    /**
     * When a call button (i.e. with class .toggle-call) on a chatbox has been clicked.
     * @event _converse#callButtonClicked
     * @type { object }
     * @property { Strophe.Connection } _converse.connection - The XMPP Connection object
     * @property { _converse.ChatBox | _converse.ChatRoom } _converse.connection - The XMPP Connection object
     * @example _converse.api.listen.on('callButtonClicked', (connection, model) => { ... });
     */

    converse_core_api.trigger('callButtonClicked', {
      connection: converse_core_converse.connection,
      model: this.model
    });
  }

}
window.customElements.define('converse-chat-toolbar', toolbar_ChatToolbar);
// CONCATENATED MODULE: ./src/components/converse.js

/**
 * `converse-root` is an optional custom element which can be used to
 * declaratively insert the Converse UI into the DOM.
 *
 * It can be inserted into the DOM before or after Converse has loaded or been
 * initialized.
 */

class converse_ConverseRoot extends HTMLElement {
  async connectedCallback() {
    await converse_core_api.waitUntil('initialized');
    converse.insertInto(this);
  }

}

customElements.define('converse-root', converse_ConverseRoot);
// CONCATENATED MODULE: ./src/templates/background_logo.js

/* harmony default export */ var background_logo = (() => lit_html_html`
    <div class="inner-content converse-brand row">
        <div class="converse-brand__padding"></div>
        <div class="converse-brand__heading">
            <svg height="200px"
                xmlns="http://www.w3.org/2000/svg"
                xmlns:xlink="http://www.w3.org/1999/xlink"
                viewBox="0 0 364 364"
                version="1.1">
                <title>Logo Converse</title>
                <defs>
                    <linearGradient id="gradient" x1="92.14" y1="27.64" x2="267.65" y2="331.62" gradientUnits="userSpaceOnUse">
                        <stop offset="0" stop-color="#fff1d1"/>
                        <stop offset="0.05" stop-color="#fae8c1"/>
                        <stop offset="0.15" stop-color="#f0d5a1"/>
                        <stop offset="0.27" stop-color="#e7c687"/>
                        <stop offset="0.4" stop-color="#e1bb72"/>
                        <stop offset="0.54" stop-color="#dcb264"/>
                        <stop offset="0.71" stop-color="#daad5c"/>
                        <stop offset="1" stop-color="#d9ac59"/>
                    </linearGradient>
                    <filter id="shadow">
                        <feGaussianBlur in="SourceAlpha" stdDeviation="2.3" result="blur1"/>
                        <feOffset in="blur1" dx="3" dy="3" result="blur2"/>
                        <feColorMatrix in="blur2" type="matrix" result="blur3"
                            values="1 0 0 0 0.1
                                    0 1 0 0 0.1
                                    0 0 1 0 0.1
                                    0 0 0 1 0"/>
                        <feMerge>
                            <feMergeNode in="blur3"/>
                            <feMergeNode in="SourceGraphic"/>
                        </feMerge>
                    </filter>
                </defs>
                <g filter="url(#shadow)">
                    <path d="M221.46,103.71c0,18.83-29.36,18.83-29.12,0C192.1,84.88,221.46,84.88,221.46,103.71Z" fill="#d9ac59"/>
                    <path d="M179.9,4.15A175.48,175.48,0,1,0,355.38,179.63,175.48,175.48,0,0,0,179.9,4.15Zm-40.79,264.5c-.23-17.82,27.58-17.82,27.58,0S138.88,286.48,139.11,268.65ZM218.6,168.24A79.65,79.65,0,0,1,205.15,174a12.76,12.76,0,0,0-6.29,4.65L167.54,222a1.36,1.36,0,0,1-2.46-.8v-35.8a2.58,2.58,0,0,0-3.06-2.53c-15.43,3-30.23,7.7-42.73,19.94-38.8,38-29.42,105.69,16.09,133.16a162.25,162.25,0,0,1-91.47-67.27C-3.86,182.26,34.5,47.25,138.37,25.66c46.89-9.75,118.25,5.16,123.73,62.83C265.15,120.64,246.56,152.89,218.6,168.24Z" fill="url(#gradient)"/>
                </g>
            </svg>
            <span class="converse-brand__text">
                <span>converse<span class="subdued">.js</span></span>
                <p class="byline">messaging freedom</p>
            </span>
        </div>
    </div>`);
// CONCATENATED MODULE: ./node_modules/lit-html/directives/unsafe-svg.js
/**
 * @license
 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */


 // For each part, remember the value that was last rendered to the part by the
// unsafeSVG directive, and the DocumentFragment that was last set as a value.
// The DocumentFragment is used as a unique key to check if the last value
// rendered to the part was with unsafeSVG. If not, we'll always re-render the
// value passed to unsafeSVG.

const unsafe_svg_previousValues = new WeakMap();
const isIe = window.navigator.userAgent.indexOf('Trident/') > 0;
/**
 * Renders the result as SVG, rather than text.
 *
 * Note, this is unsafe to use with any user-provided input that hasn't been
 * sanitized or escaped, as it may lead to cross-site-scripting
 * vulnerabilities.
 */

const unsafeSVG = directive_directive(value => part => {
  if (!(part instanceof parts_NodePart)) {
    throw new Error('unsafeSVG can only be used in text bindings');
  }

  const previousValue = unsafe_svg_previousValues.get(part);

  if (previousValue !== undefined && isPrimitive(value) && value === previousValue.value && part.value === previousValue.fragment) {
    return;
  }

  const template = document.createElement('template');
  const content = template.content;
  let svgElement;

  if (isIe) {
    // IE can't set innerHTML of an svg element. However, it also doesn't
    // support Trusted Types, so it's ok for us to use a string when setting
    // innerHTML.
    template.innerHTML = `<svg>${value}</svg>`;
    svgElement = content.firstChild;
  } else {
    svgElement = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    content.appendChild(svgElement);
    svgElement.innerHTML = value;
  }

  content.removeChild(svgElement);
  reparentNodes(content, svgElement.firstChild);
  const fragment = document.importNode(content, true);
  part.setValue(fragment);
  unsafe_svg_previousValues.set(part, {
    value,
    fragment
  });
});
// CONCATENATED MODULE: ./src/components/font-awesome.js




class font_awesome_FontAwesome extends element_CustomElement {
  constructor() {
    super();
    const promise = __webpack_require__.e(/* import() | icons */ 138).then(__webpack_require__.t.bind(null, 543, 7));
    this.data = promise.then(d => lit_html_html`${unsafeSVG(d.default())}`);
  }

  render() {
    // eslint-disable-line class-methods-use-this
    return lit_html_html`${until(this.data, '')}`;
  }

}
window.customElements.define('converse-fontawesome', font_awesome_FontAwesome);
// CONCATENATED MODULE: ./src/templates/converse.js


/* harmony default export */ var templates_converse = (() => lit_html_html`
    <div class="converse-chatboxes row no-gutters"></div>
    <div id="converse-modals" class="modals"></div>
    <converse-fontawesome></converse-fontawesome>
`);
// CONCATENATED MODULE: ./node_modules/lodash-es/drop.js


/**
 * Creates a slice of `array` with `n` elements dropped from the beginning.
 *
 * @static
 * @memberOf _
 * @since 0.5.0
 * @category Array
 * @param {Array} array The array to query.
 * @param {number} [n=1] The number of elements to drop.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
 * @returns {Array} Returns the slice of `array`.
 * @example
 *
 * _.drop([1, 2, 3]);
 * // => [2, 3]
 *
 * _.drop([1, 2, 3], 2);
 * // => [3]
 *
 * _.drop([1, 2, 3], 5);
 * // => []
 *
 * _.drop([1, 2, 3], 0);
 * // => [1, 2, 3]
 */

function drop_drop(array, n, guard) {
  var length = array == null ? 0 : array.length;

  if (!length) {
    return [];
  }

  n = guard || n === undefined ? 1 : lodash_es_toInteger(n);
  return _baseSlice(array, n < 0 ? 0 : n, length);
}

/* harmony default export */ var lodash_es_drop = (drop_drop);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseFilter.js

/**
 * The base implementation of `_.filter` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 */

function baseFilter(collection, predicate) {
  var result = [];
  _baseEach(collection, function (value, index, collection) {
    if (predicate(value, index, collection)) {
      result.push(value);
    }
  });
  return result;
}

/* harmony default export */ var _baseFilter = (baseFilter);
// CONCATENATED MODULE: ./node_modules/lodash-es/filter.js




/**
 * Iterates over elements of `collection`, returning an array of all elements
 * `predicate` returns truthy for. The predicate is invoked with three
 * arguments: (value, index|key, collection).
 *
 * **Note:** Unlike `_.remove`, this method returns a new array.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 * @see _.reject
 * @example
 *
 * var users = [
 *   { 'user': 'barney', 'age': 36, 'active': true },
 *   { 'user': 'fred',   'age': 40, 'active': false }
 * ];
 *
 * _.filter(users, function(o) { return !o.active; });
 * // => objects for ['fred']
 *
 * // The `_.matches` iteratee shorthand.
 * _.filter(users, { 'age': 36, 'active': true });
 * // => objects for ['barney']
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.filter(users, ['active', false]);
 * // => objects for ['fred']
 *
 * // The `_.property` iteratee shorthand.
 * _.filter(users, 'active');
 * // => objects for ['barney']
 *
 * // Combining several predicates using `_.overEvery` or `_.overSome`.
 * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
 * // => objects for ['fred', 'barney']
 */

function filter_filter(collection, predicate) {
  var func = lodash_es_isArray(collection) ? _arrayFilter : _baseFilter;
  return func(collection, _baseIteratee(predicate, 3));
}

/* harmony default export */ var lodash_es_filter = (filter_filter);
// CONCATENATED MODULE: ./node_modules/lodash-es/head.js
/**
 * Gets the first element of `array`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @alias first
 * @category Array
 * @param {Array} array The array to query.
 * @returns {*} Returns the first element of `array`.
 * @example
 *
 * _.head([1, 2, 3]);
 * // => 1
 *
 * _.head([]);
 * // => undefined
 */
function head(array) {
  return array && array.length ? array[0] : undefined;
}

/* harmony default export */ var lodash_es_head = (head);
// CONCATENATED MODULE: ./node_modules/lodash-es/_castFunction.js

/**
 * Casts `value` to `identity` if it's not a function.
 *
 * @private
 * @param {*} value The value to inspect.
 * @returns {Function} Returns cast function.
 */

function castFunction(value) {
  return typeof value == 'function' ? value : lodash_es_identity;
}

/* harmony default export */ var _castFunction = (castFunction);
// CONCATENATED MODULE: ./node_modules/lodash-es/forEach.js




/**
 * Iterates over elements of `collection` and invokes `iteratee` for each element.
 * The iteratee is invoked with three arguments: (value, index|key, collection).
 * Iteratee functions may exit iteration early by explicitly returning `false`.
 *
 * **Note:** As with other "Collections" methods, objects with a "length"
 * property are iterated like arrays. To avoid this behavior use `_.forIn`
 * or `_.forOwn` for object iteration.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @alias each
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
 * @returns {Array|Object} Returns `collection`.
 * @see _.forEachRight
 * @example
 *
 * _.forEach([1, 2], function(value) {
 *   console.log(value);
 * });
 * // => Logs `1` then `2`.
 *
 * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
 *   console.log(key);
 * });
 * // => Logs 'a' then 'b' (iteration order is not guaranteed).
 */

function forEach(collection, iteratee) {
  var func = lodash_es_isArray(collection) ? _arrayEach : _baseEach;
  return func(collection, _castFunction(iteratee));
}

/* harmony default export */ var lodash_es_forEach = (forEach);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseValues.js

/**
 * The base implementation of `_.values` and `_.valuesIn` which creates an
 * array of `object` property values corresponding to the property names
 * of `props`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array} props The property names to get values for.
 * @returns {Object} Returns the array of property values.
 */

function baseValues(object, props) {
  return _arrayMap(props, function (key) {
    return object[key];
  });
}

/* harmony default export */ var _baseValues = (baseValues);
// CONCATENATED MODULE: ./node_modules/lodash-es/values.js


/**
 * Creates an array of the own enumerable string keyed property values of `object`.
 *
 * **Note:** Non-object values are coerced to objects.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property values.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.values(new Foo);
 * // => [1, 2] (iteration order is not guaranteed)
 *
 * _.values('hi');
 * // => ['h', 'i']
 */

function values_values(object) {
  return object == null ? [] : _baseValues(object, lodash_es_keys(object));
}

/* harmony default export */ var lodash_es_values = (values_values);
// CONCATENATED MODULE: ./node_modules/lodash-es/includes.js





/* Built-in method references for those with the same name as other `lodash` methods. */

var includes_nativeMax = Math.max;
/**
 * Checks if `value` is in `collection`. If `collection` is a string, it's
 * checked for a substring of `value`, otherwise
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * is used for equality comparisons. If `fromIndex` is negative, it's used as
 * the offset from the end of `collection`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object|string} collection The collection to inspect.
 * @param {*} value The value to search for.
 * @param {number} [fromIndex=0] The index to search from.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
 * @returns {boolean} Returns `true` if `value` is found, else `false`.
 * @example
 *
 * _.includes([1, 2, 3], 1);
 * // => true
 *
 * _.includes([1, 2, 3], 1, 2);
 * // => false
 *
 * _.includes({ 'a': 1, 'b': 2 }, 1);
 * // => true
 *
 * _.includes('abcd', 'bc');
 * // => true
 */

function includes_includes(collection, value, fromIndex, guard) {
  collection = lodash_es_isArrayLike(collection) ? collection : lodash_es_values(collection);
  fromIndex = fromIndex && !guard ? lodash_es_toInteger(fromIndex) : 0;
  var length = collection.length;

  if (fromIndex < 0) {
    fromIndex = includes_nativeMax(length + fromIndex, 0);
  }

  return lodash_es_isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && _baseIndexOf(collection, value, fromIndex) > -1;
}

/* harmony default export */ var lodash_es_includes = (includes_includes);
// CONCATENATED MODULE: ./node_modules/lodash-es/initial.js

/**
 * Gets all but the last element of `array`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to query.
 * @returns {Array} Returns the slice of `array`.
 * @example
 *
 * _.initial([1, 2, 3]);
 * // => [1, 2]
 */

function initial(array) {
  var length = array == null ? 0 : array.length;
  return length ? _baseSlice(array, 0, -1) : [];
}

/* harmony default export */ var lodash_es_initial = (initial);
// CONCATENATED MODULE: ./node_modules/lodash-es/map.js




/**
 * Creates an array of values by running each element in `collection` thru
 * `iteratee`. The iteratee is invoked with three arguments:
 * (value, index|key, collection).
 *
 * Many lodash methods are guarded to work as iteratees for methods like
 * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
 *
 * The guarded methods are:
 * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
 * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
 * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
 * `template`, `trim`, `trimEnd`, `trimStart`, and `words`
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 * @example
 *
 * function square(n) {
 *   return n * n;
 * }
 *
 * _.map([4, 8], square);
 * // => [16, 64]
 *
 * _.map({ 'a': 4, 'b': 8 }, square);
 * // => [16, 64] (iteration order is not guaranteed)
 *
 * var users = [
 *   { 'user': 'barney' },
 *   { 'user': 'fred' }
 * ];
 *
 * // The `_.property` iteratee shorthand.
 * _.map(users, 'user');
 * // => ['barney', 'fred']
 */

function map_map(collection, iteratee) {
  var func = lodash_es_isArray(collection) ? _arrayMap : _baseMap;
  return func(collection, _baseIteratee(iteratee, 3));
}

/* harmony default export */ var lodash_es_map = (map_map);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseExtremum.js

/**
 * The base implementation of methods like `_.max` and `_.min` which accepts a
 * `comparator` to determine the extremum value.
 *
 * @private
 * @param {Array} array The array to iterate over.
 * @param {Function} iteratee The iteratee invoked per iteration.
 * @param {Function} comparator The comparator used to compare values.
 * @returns {*} Returns the extremum value.
 */

function baseExtremum(array, iteratee, comparator) {
  var index = -1,
      length = array.length;

  while (++index < length) {
    var value = array[index],
        current = iteratee(value);

    if (current != null && (computed === undefined ? current === current && !lodash_es_isSymbol(current) : comparator(current, computed))) {
      var computed = current,
          result = value;
    }
  }

  return result;
}

/* harmony default export */ var _baseExtremum = (baseExtremum);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseGt.js
/**
 * The base implementation of `_.gt` which doesn't coerce arguments.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if `value` is greater than `other`,
 *  else `false`.
 */
function baseGt(value, other) {
  return value > other;
}

/* harmony default export */ var _baseGt = (baseGt);
// CONCATENATED MODULE: ./node_modules/lodash-es/max.js



/**
 * Computes the maximum value of `array`. If `array` is empty or falsey,
 * `undefined` is returned.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Math
 * @param {Array} array The array to iterate over.
 * @returns {*} Returns the maximum value.
 * @example
 *
 * _.max([4, 2, 8, 6]);
 * // => 8
 *
 * _.max([]);
 * // => undefined
 */

function max_max(array) {
  return array && array.length ? _baseExtremum(array, lodash_es_identity, _baseGt) : undefined;
}

/* harmony default export */ var lodash_es_max = (max_max);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseLt.js
/**
 * The base implementation of `_.lt` which doesn't coerce arguments.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if `value` is less than `other`,
 *  else `false`.
 */
function baseLt(value, other) {
  return value < other;
}

/* harmony default export */ var _baseLt = (baseLt);
// CONCATENATED MODULE: ./node_modules/lodash-es/min.js



/**
 * Computes the minimum value of `array`. If `array` is empty or falsey,
 * `undefined` is returned.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Math
 * @param {Array} array The array to iterate over.
 * @returns {*} Returns the minimum value.
 * @example
 *
 * _.min([4, 2, 8, 6]);
 * // => 2
 *
 * _.min([]);
 * // => undefined
 */

function min(array) {
  return array && array.length ? _baseExtremum(array, lodash_es_identity, _baseLt) : undefined;
}

/* harmony default export */ var lodash_es_min = (min);
// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayReduce.js
/**
 * A specialized version of `_.reduce` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {*} [accumulator] The initial value.
 * @param {boolean} [initAccum] Specify using the first element of `array` as
 *  the initial value.
 * @returns {*} Returns the accumulated value.
 */
function arrayReduce(array, iteratee, accumulator, initAccum) {
  var index = -1,
      length = array == null ? 0 : array.length;

  if (initAccum && length) {
    accumulator = array[++index];
  }

  while (++index < length) {
    accumulator = iteratee(accumulator, array[index], index, array);
  }

  return accumulator;
}

/* harmony default export */ var _arrayReduce = (arrayReduce);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseReduce.js
/**
 * The base implementation of `_.reduce` and `_.reduceRight`, without support
 * for iteratee shorthands, which iterates over `collection` using `eachFunc`.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {*} accumulator The initial value.
 * @param {boolean} initAccum Specify using the first or last element of
 *  `collection` as the initial value.
 * @param {Function} eachFunc The function to iterate over `collection`.
 * @returns {*} Returns the accumulated value.
 */
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
  eachFunc(collection, function (value, index, collection) {
    accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection);
  });
  return accumulator;
}

/* harmony default export */ var _baseReduce = (baseReduce);
// CONCATENATED MODULE: ./node_modules/lodash-es/reduce.js





/**
 * Reduces `collection` to a value which is the accumulated result of running
 * each element in `collection` thru `iteratee`, where each successive
 * invocation is supplied the return value of the previous. If `accumulator`
 * is not given, the first element of `collection` is used as the initial
 * value. The iteratee is invoked with four arguments:
 * (accumulator, value, index|key, collection).
 *
 * Many lodash methods are guarded to work as iteratees for methods like
 * `_.reduce`, `_.reduceRight`, and `_.transform`.
 *
 * The guarded methods are:
 * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
 * and `sortBy`
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
 * @param {*} [accumulator] The initial value.
 * @returns {*} Returns the accumulated value.
 * @see _.reduceRight
 * @example
 *
 * _.reduce([1, 2], function(sum, n) {
 *   return sum + n;
 * }, 0);
 * // => 3
 *
 * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
 *   (result[value] || (result[value] = [])).push(key);
 *   return result;
 * }, {});
 * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
 */

function reduce(collection, iteratee, accumulator) {
  var func = lodash_es_isArray(collection) ? _arrayReduce : _baseReduce,
      initAccum = arguments.length < 3;
  return func(collection, _baseIteratee(iteratee, 4), accumulator, initAccum, _baseEach);
}

/* harmony default export */ var lodash_es_reduce = (reduce);
// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayReduceRight.js
/**
 * A specialized version of `_.reduceRight` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {*} [accumulator] The initial value.
 * @param {boolean} [initAccum] Specify using the last element of `array` as
 *  the initial value.
 * @returns {*} Returns the accumulated value.
 */
function arrayReduceRight(array, iteratee, accumulator, initAccum) {
  var length = array == null ? 0 : array.length;

  if (initAccum && length) {
    accumulator = array[--length];
  }

  while (length--) {
    accumulator = iteratee(accumulator, array[length], length, array);
  }

  return accumulator;
}

/* harmony default export */ var _arrayReduceRight = (arrayReduceRight);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseForRight.js

/**
 * This function is like `baseFor` except that it iterates over properties
 * in the opposite order.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @returns {Object} Returns `object`.
 */

var baseForRight = _createBaseFor(true);
/* harmony default export */ var _baseForRight = (baseForRight);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseForOwnRight.js


/**
 * The base implementation of `_.forOwnRight` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Object} Returns `object`.
 */

function baseForOwnRight(object, iteratee) {
  return object && _baseForRight(object, iteratee, lodash_es_keys);
}

/* harmony default export */ var _baseForOwnRight = (baseForOwnRight);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseEachRight.js


/**
 * The base implementation of `_.forEachRight` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array|Object} Returns `collection`.
 */

var baseEachRight = _createBaseEach(_baseForOwnRight, true);
/* harmony default export */ var _baseEachRight = (baseEachRight);
// CONCATENATED MODULE: ./node_modules/lodash-es/reduceRight.js





/**
 * This method is like `_.reduce` except that it iterates over elements of
 * `collection` from right to left.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
 * @param {*} [accumulator] The initial value.
 * @returns {*} Returns the accumulated value.
 * @see _.reduce
 * @example
 *
 * var array = [[0, 1], [2, 3], [4, 5]];
 *
 * _.reduceRight(array, function(flattened, other) {
 *   return flattened.concat(other);
 * }, []);
 * // => [4, 5, 2, 3, 0, 1]
 */

function reduceRight(collection, iteratee, accumulator) {
  var func = lodash_es_isArray(collection) ? _arrayReduceRight : _baseReduce,
      initAccum = arguments.length < 3;
  return func(collection, _baseIteratee(iteratee, 4), accumulator, initAccum, _baseEachRight);
}

/* harmony default export */ var lodash_es_reduceRight = (reduceRight);
// CONCATENATED MODULE: ./node_modules/lodash-es/negate.js
/** Error message constants. */
var negate_FUNC_ERROR_TEXT = 'Expected a function';
/**
 * Creates a function that negates the result of the predicate `func`. The
 * `func` predicate is invoked with the `this` binding and arguments of the
 * created function.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Function
 * @param {Function} predicate The predicate to negate.
 * @returns {Function} Returns the new negated function.
 * @example
 *
 * function isEven(n) {
 *   return n % 2 == 0;
 * }
 *
 * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
 * // => [1, 3, 5]
 */

function negate(predicate) {
  if (typeof predicate != 'function') {
    throw new TypeError(negate_FUNC_ERROR_TEXT);
  }

  return function () {
    var args = arguments;

    switch (args.length) {
      case 0:
        return !predicate.call(this);

      case 1:
        return !predicate.call(this, args[0]);

      case 2:
        return !predicate.call(this, args[0], args[1]);

      case 3:
        return !predicate.call(this, args[0], args[1], args[2]);
    }

    return !predicate.apply(this, args);
  };
}

/* harmony default export */ var lodash_es_negate = (negate);
// CONCATENATED MODULE: ./node_modules/lodash-es/reject.js





/**
 * The opposite of `_.filter`; this method returns the elements of `collection`
 * that `predicate` does **not** return truthy for.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 * @see _.filter
 * @example
 *
 * var users = [
 *   { 'user': 'barney', 'age': 36, 'active': false },
 *   { 'user': 'fred',   'age': 40, 'active': true }
 * ];
 *
 * _.reject(users, function(o) { return !o.active; });
 * // => objects for ['fred']
 *
 * // The `_.matches` iteratee shorthand.
 * _.reject(users, { 'age': 40, 'active': true });
 * // => objects for ['barney']
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.reject(users, ['active', false]);
 * // => objects for ['fred']
 *
 * // The `_.property` iteratee shorthand.
 * _.reject(users, 'active');
 * // => objects for ['barney']
 */

function reject_reject(collection, predicate) {
  var func = lodash_es_isArray(collection) ? _arrayFilter : _baseFilter;
  return func(collection, lodash_es_negate(_baseIteratee(predicate, 3)));
}

/* harmony default export */ var lodash_es_reject = (reject_reject);
// CONCATENATED MODULE: ./node_modules/lodash-es/rest.js


/** Error message constants. */

var rest_FUNC_ERROR_TEXT = 'Expected a function';
/**
 * Creates a function that invokes `func` with the `this` binding of the
 * created function and arguments from `start` and beyond provided as
 * an array.
 *
 * **Note:** This method is based on the
 * [rest parameter](https://mdn.io/rest_parameters).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Function
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @returns {Function} Returns the new function.
 * @example
 *
 * var say = _.rest(function(what, names) {
 *   return what + ' ' + _.initial(names).join(', ') +
 *     (_.size(names) > 1 ? ', & ' : '') + _.last(names);
 * });
 *
 * say('hello', 'fred', 'barney', 'pebbles');
 * // => 'hello fred, barney, & pebbles'
 */

function rest(func, start) {
  if (typeof func != 'function') {
    throw new TypeError(rest_FUNC_ERROR_TEXT);
  }

  start = start === undefined ? start : lodash_es_toInteger(start);
  return _baseRest(func, start);
}

/* harmony default export */ var lodash_es_rest = (rest);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseRandom.js
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeFloor = Math.floor,
    nativeRandom = Math.random;
/**
 * The base implementation of `_.random` without support for returning
 * floating-point numbers.
 *
 * @private
 * @param {number} lower The lower bound.
 * @param {number} upper The upper bound.
 * @returns {number} Returns the random number.
 */

function baseRandom(lower, upper) {
  return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
}

/* harmony default export */ var _baseRandom = (baseRandom);
// CONCATENATED MODULE: ./node_modules/lodash-es/_arraySample.js

/**
 * A specialized version of `_.sample` for arrays.
 *
 * @private
 * @param {Array} array The array to sample.
 * @returns {*} Returns the random element.
 */

function arraySample(array) {
  var length = array.length;
  return length ? array[_baseRandom(0, length - 1)] : undefined;
}

/* harmony default export */ var _arraySample = (arraySample);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSample.js


/**
 * The base implementation of `_.sample`.
 *
 * @private
 * @param {Array|Object} collection The collection to sample.
 * @returns {*} Returns the random element.
 */

function baseSample(collection) {
  return _arraySample(lodash_es_values(collection));
}

/* harmony default export */ var _baseSample = (baseSample);
// CONCATENATED MODULE: ./node_modules/lodash-es/sample.js



/**
 * Gets a random element from `collection`.
 *
 * @static
 * @memberOf _
 * @since 2.0.0
 * @category Collection
 * @param {Array|Object} collection The collection to sample.
 * @returns {*} Returns the random element.
 * @example
 *
 * _.sample([1, 2, 3, 4]);
 * // => 2
 */

function sample(collection) {
  var func = lodash_es_isArray(collection) ? _arraySample : _baseSample;
  return func(collection);
}

/* harmony default export */ var lodash_es_sample = (sample);
// CONCATENATED MODULE: ./node_modules/lodash-es/_shuffleSelf.js

/**
 * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
 *
 * @private
 * @param {Array} array The array to shuffle.
 * @param {number} [size=array.length] The size of `array`.
 * @returns {Array} Returns `array`.
 */

function shuffleSelf(array, size) {
  var index = -1,
      length = array.length,
      lastIndex = length - 1;
  size = size === undefined ? length : size;

  while (++index < size) {
    var rand = _baseRandom(index, lastIndex),
        value = array[rand];
    array[rand] = array[index];
    array[index] = value;
  }

  array.length = size;
  return array;
}

/* harmony default export */ var _shuffleSelf = (shuffleSelf);
// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayShuffle.js


/**
 * A specialized version of `_.shuffle` for arrays.
 *
 * @private
 * @param {Array} array The array to shuffle.
 * @returns {Array} Returns the new shuffled array.
 */

function arrayShuffle(array) {
  return _shuffleSelf(_copyArray(array));
}

/* harmony default export */ var _arrayShuffle = (arrayShuffle);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseShuffle.js


/**
 * The base implementation of `_.shuffle`.
 *
 * @private
 * @param {Array|Object} collection The collection to shuffle.
 * @returns {Array} Returns the new shuffled array.
 */

function baseShuffle(collection) {
  return _shuffleSelf(lodash_es_values(collection));
}

/* harmony default export */ var _baseShuffle = (baseShuffle);
// CONCATENATED MODULE: ./node_modules/lodash-es/shuffle.js



/**
 * Creates an array of shuffled values, using a version of the
 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to shuffle.
 * @returns {Array} Returns the new shuffled array.
 * @example
 *
 * _.shuffle([1, 2, 3, 4]);
 * // => [4, 1, 3, 2]
 */

function shuffle(collection) {
  var func = lodash_es_isArray(collection) ? _arrayShuffle : _baseShuffle;
  return func(collection);
}

/* harmony default export */ var lodash_es_shuffle = (shuffle);
// CONCATENATED MODULE: ./node_modules/lodash-es/_asciiSize.js

/**
 * Gets the size of an ASCII `string`.
 *
 * @private
 * @param {string} string The string inspect.
 * @returns {number} Returns the string size.
 */

var asciiSize = _baseProperty('length');
/* harmony default export */ var _asciiSize = (asciiSize);
// CONCATENATED MODULE: ./node_modules/lodash-es/_hasUnicode.js
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
    rsComboMarksRange = '\\u0300-\\u036f',
    reComboHalfMarksRange = '\\ufe20-\\ufe2f',
    rsComboSymbolsRange = '\\u20d0-\\u20ff',
    rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
    rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */

var rsZWJ = '\\u200d';
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */

var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
/**
 * Checks if `string` contains Unicode symbols.
 *
 * @private
 * @param {string} string The string to inspect.
 * @returns {boolean} Returns `true` if a symbol is found, else `false`.
 */

function hasUnicode(string) {
  return reHasUnicode.test(string);
}

/* harmony default export */ var _hasUnicode = (hasUnicode);
// CONCATENATED MODULE: ./node_modules/lodash-es/_unicodeSize.js
/** Used to compose unicode character classes. */
var _unicodeSize_rsAstralRange = '\\ud800-\\udfff',
    _unicodeSize_rsComboMarksRange = '\\u0300-\\u036f',
    _unicodeSize_reComboHalfMarksRange = '\\ufe20-\\ufe2f',
    _unicodeSize_rsComboSymbolsRange = '\\u20d0-\\u20ff',
    _unicodeSize_rsComboRange = _unicodeSize_rsComboMarksRange + _unicodeSize_reComboHalfMarksRange + _unicodeSize_rsComboSymbolsRange,
    _unicodeSize_rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */

var rsAstral = '[' + _unicodeSize_rsAstralRange + ']',
    rsCombo = '[' + _unicodeSize_rsComboRange + ']',
    rsFitz = '\\ud83c[\\udffb-\\udfff]',
    rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
    rsNonAstral = '[^' + _unicodeSize_rsAstralRange + ']',
    rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
    rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
    _unicodeSize_rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */

var reOptMod = rsModifier + '?',
    rsOptVar = '[' + _unicodeSize_rsVarRange + ']?',
    rsOptJoin = '(?:' + _unicodeSize_rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
    rsSeq = rsOptVar + reOptMod + rsOptJoin,
    rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */

var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/**
 * Gets the size of a Unicode `string`.
 *
 * @private
 * @param {string} string The string inspect.
 * @returns {number} Returns the string size.
 */

function unicodeSize(string) {
  var result = reUnicode.lastIndex = 0;

  while (reUnicode.test(string)) {
    ++result;
  }

  return result;
}

/* harmony default export */ var _unicodeSize = (unicodeSize);
// CONCATENATED MODULE: ./node_modules/lodash-es/_stringSize.js



/**
 * Gets the number of symbols in `string`.
 *
 * @private
 * @param {string} string The string to inspect.
 * @returns {number} Returns the string size.
 */

function stringSize(string) {
  return _hasUnicode(string) ? _unicodeSize(string) : _asciiSize(string);
}

/* harmony default export */ var _stringSize = (stringSize);
// CONCATENATED MODULE: ./node_modules/lodash-es/size.js





/** `Object#toString` result references. */

var size_mapTag = '[object Map]',
    size_setTag = '[object Set]';
/**
 * Gets the size of `collection` by returning its length for array-like
 * values or the number of own enumerable string keyed properties for objects.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object|string} collection The collection to inspect.
 * @returns {number} Returns the collection size.
 * @example
 *
 * _.size([1, 2, 3]);
 * // => 3
 *
 * _.size({ 'a': 1, 'b': 2 });
 * // => 2
 *
 * _.size('pebbles');
 * // => 7
 */

function size_size(collection) {
  if (collection == null) {
    return 0;
  }

  if (lodash_es_isArrayLike(collection)) {
    return lodash_es_isString(collection) ? _stringSize(collection) : collection.length;
  }

  var tag = _getTag(collection);

  if (tag == size_mapTag || tag == size_setTag) {
    return collection.size;
  }

  return _baseKeys(collection).length;
}

/* harmony default export */ var lodash_es_size = (size_size);
// CONCATENATED MODULE: ./node_modules/lodash-es/tail.js

/**
 * Gets all but the first element of `array`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Array
 * @param {Array} array The array to query.
 * @returns {Array} Returns the slice of `array`.
 * @example
 *
 * _.tail([1, 2, 3]);
 * // => [2, 3]
 */

function tail(array) {
  var length = array == null ? 0 : array.length;
  return length ? _baseSlice(array, 1, length) : [];
}

/* harmony default export */ var lodash_es_tail = (tail);
// CONCATENATED MODULE: ./node_modules/lodash-es/take.js


/**
 * Creates a slice of `array` with `n` elements taken from the beginning.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to query.
 * @param {number} [n=1] The number of elements to take.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
 * @returns {Array} Returns the slice of `array`.
 * @example
 *
 * _.take([1, 2, 3]);
 * // => [1]
 *
 * _.take([1, 2, 3], 2);
 * // => [1, 2]
 *
 * _.take([1, 2, 3], 5);
 * // => [1, 2, 3]
 *
 * _.take([1, 2, 3], 0);
 * // => []
 */

function take(array, n, guard) {
  if (!(array && array.length)) {
    return [];
  }

  n = guard || n === undefined ? 1 : lodash_es_toInteger(n);
  return _baseSlice(array, 0, n < 0 ? 0 : n);
}

/* harmony default export */ var lodash_es_take = (take);
// CONCATENATED MODULE: ./node_modules/lodash-es/_iteratorToArray.js
/**
 * Converts `iterator` to an array.
 *
 * @private
 * @param {Object} iterator The iterator to convert.
 * @returns {Array} Returns the converted array.
 */
function iteratorToArray(iterator) {
  var data,
      result = [];

  while (!(data = iterator.next()).done) {
    result.push(data.value);
  }

  return result;
}

/* harmony default export */ var _iteratorToArray = (iteratorToArray);
// CONCATENATED MODULE: ./node_modules/lodash-es/_asciiToArray.js
/**
 * Converts an ASCII `string` to an array.
 *
 * @private
 * @param {string} string The string to convert.
 * @returns {Array} Returns the converted array.
 */
function asciiToArray(string) {
  return string.split('');
}

/* harmony default export */ var _asciiToArray = (asciiToArray);
// CONCATENATED MODULE: ./node_modules/lodash-es/_unicodeToArray.js
/** Used to compose unicode character classes. */
var _unicodeToArray_rsAstralRange = '\\ud800-\\udfff',
    _unicodeToArray_rsComboMarksRange = '\\u0300-\\u036f',
    _unicodeToArray_reComboHalfMarksRange = '\\ufe20-\\ufe2f',
    _unicodeToArray_rsComboSymbolsRange = '\\u20d0-\\u20ff',
    _unicodeToArray_rsComboRange = _unicodeToArray_rsComboMarksRange + _unicodeToArray_reComboHalfMarksRange + _unicodeToArray_rsComboSymbolsRange,
    _unicodeToArray_rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */

var _unicodeToArray_rsAstral = '[' + _unicodeToArray_rsAstralRange + ']',
    _unicodeToArray_rsCombo = '[' + _unicodeToArray_rsComboRange + ']',
    _unicodeToArray_rsFitz = '\\ud83c[\\udffb-\\udfff]',
    _unicodeToArray_rsModifier = '(?:' + _unicodeToArray_rsCombo + '|' + _unicodeToArray_rsFitz + ')',
    _unicodeToArray_rsNonAstral = '[^' + _unicodeToArray_rsAstralRange + ']',
    _unicodeToArray_rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
    _unicodeToArray_rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
    _unicodeToArray_rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */

var _unicodeToArray_reOptMod = _unicodeToArray_rsModifier + '?',
    _unicodeToArray_rsOptVar = '[' + _unicodeToArray_rsVarRange + ']?',
    _unicodeToArray_rsOptJoin = '(?:' + _unicodeToArray_rsZWJ + '(?:' + [_unicodeToArray_rsNonAstral, _unicodeToArray_rsRegional, _unicodeToArray_rsSurrPair].join('|') + ')' + _unicodeToArray_rsOptVar + _unicodeToArray_reOptMod + ')*',
    _unicodeToArray_rsSeq = _unicodeToArray_rsOptVar + _unicodeToArray_reOptMod + _unicodeToArray_rsOptJoin,
    _unicodeToArray_rsSymbol = '(?:' + [_unicodeToArray_rsNonAstral + _unicodeToArray_rsCombo + '?', _unicodeToArray_rsCombo, _unicodeToArray_rsRegional, _unicodeToArray_rsSurrPair, _unicodeToArray_rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */

var _unicodeToArray_reUnicode = RegExp(_unicodeToArray_rsFitz + '(?=' + _unicodeToArray_rsFitz + ')|' + _unicodeToArray_rsSymbol + _unicodeToArray_rsSeq, 'g');
/**
 * Converts a Unicode `string` to an array.
 *
 * @private
 * @param {string} string The string to convert.
 * @returns {Array} Returns the converted array.
 */

function unicodeToArray(string) {
  return string.match(_unicodeToArray_reUnicode) || [];
}

/* harmony default export */ var _unicodeToArray = (unicodeToArray);
// CONCATENATED MODULE: ./node_modules/lodash-es/_stringToArray.js



/**
 * Converts `string` to an array.
 *
 * @private
 * @param {string} string The string to convert.
 * @returns {Array} Returns the converted array.
 */

function stringToArray(string) {
  return _hasUnicode(string) ? _unicodeToArray(string) : _asciiToArray(string);
}

/* harmony default export */ var _stringToArray = (stringToArray);
// CONCATENATED MODULE: ./node_modules/lodash-es/toArray.js










/** `Object#toString` result references. */

var toArray_mapTag = '[object Map]',
    toArray_setTag = '[object Set]';
/** Built-in value references. */

var symIterator = _Symbol ? _Symbol.iterator : undefined;
/**
 * Converts `value` to an array.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {Array} Returns the converted array.
 * @example
 *
 * _.toArray({ 'a': 1, 'b': 2 });
 * // => [1, 2]
 *
 * _.toArray('abc');
 * // => ['a', 'b', 'c']
 *
 * _.toArray(1);
 * // => []
 *
 * _.toArray(null);
 * // => []
 */

function toArray(value) {
  if (!value) {
    return [];
  }

  if (lodash_es_isArrayLike(value)) {
    return lodash_es_isString(value) ? _stringToArray(value) : _copyArray(value);
  }

  if (symIterator && value[symIterator]) {
    return _iteratorToArray(value[symIterator]());
  }

  var tag = _getTag(value),
      func = tag == toArray_mapTag ? _mapToArray : tag == toArray_setTag ? _setToArray : lodash_es_values;
  return func(value);
}

/* harmony default export */ var lodash_es_toArray = (toArray);
// CONCATENATED MODULE: ./node_modules/lodash-es/without.js



/**
 * Creates an array excluding all given values using
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons.
 *
 * **Note:** Unlike `_.pull`, this method returns a new array.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to inspect.
 * @param {...*} [values] The values to exclude.
 * @returns {Array} Returns the new array of filtered values.
 * @see _.difference, _.xor
 * @example
 *
 * _.without([2, 1, 2, 3], 1, 2);
 * // => [3]
 */

var without = _baseRest(function (array, values) {
  return lodash_es_isArrayLikeObject(array) ? _baseDifference(array, values) : [];
});
/* harmony default export */ var lodash_es_without = (without);
// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/overview.js
/*!
 * Copyright (c) JC Brand <jc@opkode.com>
 */




































const Overview = function (options) {
  /* An Overview is a View that contains and keeps track of sub-views.
   * Kind of like what a Collection is to a Model.
   */
  this.views = {};

  this.keys = () => Object.keys(this.views);

  this.getAll = () => this.views;

  this.get = id => this.views[id];
  /* Exclusive get. Returns all instances except the given id. */


  this.xget = id => {
    return this.keys().filter(k => k !== id).reduce((acc, k) => {
      acc[k] = this.views[k];
      return acc;
    }, {});
  };

  this.add = (id, view) => {
    this.views[id] = view;
    return view;
  };

  this.remove = id => {
    if (typeof id === "undefined") {
      new View().remove.apply(this);
    }

    const view = this.views[id];

    if (view) {
      delete this.views[id];
      view.remove();
      return view;
    }
  };

  this.removeAll = () => {
    this.keys().forEach(id => this.remove(id));
    return this;
  };

  View.apply(this, Array.prototype.slice.apply(arguments));
};

const methods = {
  includes: lodash_es_includes,
  difference: lodash_es_difference,
  drop: lodash_es_drop,
  every: lodash_es_every,
  filter: lodash_es_filter,
  find: lodash_es_find,
  first: lodash_es_head,
  forEach: lodash_es_forEach,
  head: lodash_es_head,
  indexOf: lodash_es_indexOf,
  initial: lodash_es_initial,
  invoke: lodash_es_invoke,
  isEmpty: lodash_es_isEmpty,
  last: lodash_es_last,
  lastIndexOf: lodash_es_lastIndexOf,
  map: lodash_es_map,
  max: lodash_es_max,
  min: lodash_es_min,
  reduce: lodash_es_reduce,
  reduceRight: lodash_es_reduceRight,
  reject: lodash_es_reject,
  rest: lodash_es_rest,
  sample: lodash_es_sample,
  shuffle: lodash_es_shuffle,
  size: lodash_es_size,
  some: lodash_es_some,
  sortBy: lodash_es_sortBy,
  tail: lodash_es_tail,
  take: lodash_es_take,
  toArray: lodash_es_toArray,
  without: lodash_es_without
};
Object.keys(methods).forEach(name => {
  Overview.prototype[name] = function () {
    const args = Array.prototype.slice.call(arguments);
    args.unshift(this.views);
    return methods[name].apply(this, args);
  };
});
Object.assign(Overview.prototype, View.prototype);
Overview.extend = View.extend;
const OrderedListView = Overview.extend({
  /* An OrderedListView is a special type of Overview which adds some
   * methods and conventions for rendering an ordered list of elements.
   */
  // The `listItems` attribute denotes the path (from this View) to the
  // list of items.
  listItems: 'model',
  // The `sortEvent` attribute specifies the event which should cause the
  // ordered list to be sorted.
  sortEvent: 'change',
  // If false, we debounce sorting and inserting the new item
  // (for improved performance when a large amount of items get added all at once)
  // Otherwise we immediately sort the items and insert the new item.
  sortImmediatelyOnAdd: false,
  // The `listSelector` is the selector used to query for the DOM list
  // element which contains the ordered items.
  listSelector: '.ordered-items',
  // The `itemView` is constructor which should be called to create a
  // View for a new item.
  ItemView: undefined,
  // The `subviewIndex` is the attribute of the list element model which
  // acts as the index of the subview in the overview.
  // An overview is a "Collection" of views, and they can be retrieved
  // via an index. By default this is the 'id' attribute, but it could be
  // set to something else.
  subviewIndex: 'id',

  initialize() {
    this.sortEventually = lodash_es_debounce(() => this.sortAndPositionAllItems(), 100);
    this.items = lodash_es_get(this, this.listItems);
    this.items.on('remove', this.removeView, this);
    this.items.on('reset', this.removeAll, this);
    this.items.on('add', (a, b) => {
      if (this.sortImmediatelyOnAdd) {
        this.sortAndPositionAllItems();
      } else {
        this.sortEventually();
      }
    });

    if (this.sortEvent) {
      this.items.on(this.sortEvent, this.sortEventually, this);
    }
  },

  createItemView(item) {
    let item_view = this.get(item.get(this.subviewIndex));

    if (!item_view) {
      item_view = new this.ItemView({
        model: item
      });
      this.add(item.get(this.subviewIndex), item_view);
    } else {
      item_view.model = item;
      item_view.initialize();
    }

    item_view.render();
    return item_view;
  },

  removeView(item) {
    this.remove(item.get(this.subviewIndex));
  },

  sortAndPositionAllItems() {
    if (!this.items.length) {
      return;
    }

    this.items.sort();
    const list_el = this.el.querySelector(this.listSelector);
    const div = document.createElement('div');
    list_el.parentNode.replaceChild(div, list_el);
    this.items.forEach(item => {
      let view = this.get(item.get(this.subviewIndex));

      if (!view) {
        view = this.createItemView(item);
      }

      list_el.insertAdjacentElement('beforeend', view.el);
    });
    div.parentNode.replaceChild(list_el, div);
  }

});

// CONCATENATED MODULE: ./src/converse-chatboxviews.js
/**
 * @module converse-chatboxviews
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */










const converse_chatboxviews_u = converse.env.utils;
const AvatarMixin = {
  renderAvatar(el) {
    el = el || this.el;
    const avatar_el = el.querySelector('canvas.avatar, svg.avatar');

    if (avatar_el === null) {
      return;
    }

    if (this.model.vcard) {
      const data = {
        'classes': avatar_el.getAttribute('class'),
        'width': avatar_el.getAttribute('width'),
        'height': avatar_el.getAttribute('height'),
        'image_type': this.model.vcard.get('image_type'),
        'image': this.model.vcard.get('image')
      };
      avatar_el.outerHTML = converse_chatboxviews_u.getElementFromTemplateResult(avatar(data)).outerHTML;
    }
  }

};
const ViewWithAvatar = View.extend(AvatarMixin);
const ChatBoxViews = Overview.extend({
  _ensureElement() {
    /* Override method from backbone.js
        * If the #conversejs element doesn't exist, create it.
        */
    if (this.el) {
      this.setElement(lodash_es_result(this, 'el'), false);
    } else {
      let el = converse_core_converse.root.querySelector('#conversejs');

      if (el === null) {
        el = document.createElement('div');
        el.setAttribute('id', 'conversejs');
        converse_chatboxviews_u.addClass(`theme-${converse_core_api.settings.get('theme')}`, el);

        const body = converse_core_converse.root.querySelector('body');

        if (body) {
          body.appendChild(el);
        } else {
          // Perhaps inside a web component?
          converse_core_converse.root.appendChild(el);
        }
      }

      this.setElement(el, false);
    }
  },

  initialize() {
    this.listenTo(this.model, "destroy", this.removeChat);
    const bg = document.getElementById('conversejs-bg');

    if (bg && !bg.innerHTML.trim()) {
      render_render(background_logo(), bg);
    }

    const body = document.querySelector('body');
    body.classList.add(`converse-${converse_core_api.settings.get("view_mode")}`);
    this.el.classList.add(`converse-${converse_core_api.settings.get("view_mode")}`);

    if (converse_core_api.settings.get("singleton")) {
      this.el.classList.add(`converse-singleton`);
    }

    this.render();
  },

  render() {
    this._ensureElement();

    render_render(templates_converse(), this.el);
    this.row_el = this.el.querySelector('.row');
  },

  /*(
   * Add a new DOM element (likely a chat box) into the
   * the row managed by this overview.
   * @param { HTMLElement } el
   */
  insertRowColumn(el) {
    this.row_el.insertAdjacentElement('afterBegin', el);
  },

  removeChat(item) {
    this.remove(item.get('id'));
  },

  closeAllChatBoxes() {
    return Promise.all(this.map(v => v.close({
      'name': 'closeAllChatBoxes'
    })));
  }

});

function onChatBoxViewsInitialized() {
  converse_core_converse.chatboxviews = new converse_core_converse.ChatBoxViews({
    'model': converse_core_converse.chatboxes
  });
  /**
   * Triggered once the _converse.ChatBoxViews view-colleciton has been initialized
   * @event _converse#chatBoxViewsInitialized
   * @example _converse.api.listen.on('chatBoxViewsInitialized', () => { ... });
   */

  converse_core_api.trigger('chatBoxViewsInitialized');
}

function calculateViewportHeightUnit() {
  const vh = window.innerHeight * 0.01;
  document.documentElement.style.setProperty('--vh', `${vh}px`);
}

converse.plugins.add('converse-chatboxviews', {
  dependencies: ["converse-chatboxes", "converse-vcard"],

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    converse_core_api.elements.register();
    converse_core_api.promises.add(['chatBoxViewsInitialized']); // Configuration values for this plugin
    // ====================================
    // Refer to docs/source/configuration.rst for explanations of these
    // configuration settings.

    converse_core_api.settings.extend({
      'animate': true,
      'theme': 'default'
    });
    converse_core_converse.ViewWithAvatar = ViewWithAvatar;
    converse_core_converse.ChatBoxViews = ChatBoxViews;
    /************************ BEGIN Event Handlers ************************/

    converse_core_api.listen.on('chatBoxesInitialized', onChatBoxViewsInitialized);
    converse_core_api.listen.on('cleanup', () => delete converse_core_converse.chatboxviews);
    converse_core_api.listen.on('clearSession', () => converse_core_converse.chatboxviews.closeAllChatBoxes());
    converse_core_api.listen.on('chatBoxViewsInitialized', calculateViewportHeightUnit);
    window.addEventListener('resize', calculateViewportHeightUnit);
    /************************ END Event Handlers ************************/

    Object.assign(converse, {
      /**
       * Public API method which will ensure that the #conversejs element
       * is inserted into a container element.
       *
       * This method is useful when the #conversejs element has been
       * detached from the DOM somehow.
       * @async
       * @memberOf converse
       * @method insertInto
       * @example
       * converse.insertInto(document.querySelector('#converse-container'));
       */
      insertInto(container) {
        var _converse$chatboxview;

        const el = (_converse$chatboxview = converse_core_converse.chatboxviews) === null || _converse$chatboxview === void 0 ? void 0 : _converse$chatboxview.el;

        if (el && !container.contains(el)) {
          container.insertAdjacentElement('afterBegin', el);
          converse_core_api.chatviews.get().filter(v => v.model.get('id') !== 'controlbox').forEach(v => v.maintainScrollTop());
        } else if (!el) {
          throw new Error("Cannot insert non-existing #conversejs element into the DOM");
        }
      }

    });
  }

});
// CONCATENATED MODULE: ./src/templates/chatbox.js

/* harmony default export */ var templates_chatbox = (o => lit_html_html`
    <div class="flyout box-flyout">
        <div class="chat-head chat-head-chatbox row no-gutters"></div>
        <div class="chat-body">
            <div class="chat-content ${o.show_send_button ? 'chat-content-sendbutton' : ''}" aria-live="polite">
                <div class="chat-content__messages" @scroll=${o.markScrolled}></div>
                <div class="chat-content__help"></div>
            </div>
            <div class="bottom-panel">
                <div class="message-form-container">
            </div>
        </div>
    </div>
`);
// CONCATENATED MODULE: ./src/templates/chatbox_head.js




/* harmony default export */ var chatbox_head = (o => {
  const i18n_profile = i18n_('The User\'s Profile Image');

  const avatar_data = {
    'alt_text': i18n_profile,
    'extra_classes': '',
    'height': 40,
    'width': 40
  };

  const tpl_standalone_btns = o => o.standalone_btns.reverse().map(b => until(b, ''));

  return lit_html_html`
        <div class="chatbox-title ${o.status ? '' : "chatbox-title--no-desc"}">
            <div class="chatbox-title--row">
                ${!o._converse.api.settings.get("singleton") ? lit_html_html`<div class="chatbox-navback"><i class="fa fa-arrow-left"></i></div>` : ''}
                ${o.type !== o._converse.HEADLINES_TYPE ? lit_html_html`<span class="mr-2">${avatar(Object.assign({}, o, avatar_data))}</span>` : ''}
                <div class="chatbox-title__text" title="${o.jid}">
                    ${o.url ? lit_html_html`<a href="${o.url}" target="_blank" rel="noopener" class="user">${o.display_name}</a>` : o.display_name}
                </div>
            </div>
            <div class="chatbox-title__buttons row no-gutters">
                ${o.dropdown_btns.length ? lit_html_html`<converse-dropdown .items=${o.dropdown_btns}></converse-dropdown>` : ''}
                ${o.standalone_btns.length ? tpl_standalone_btns(o) : ''}
            </div>
        </div>
        ${o.status ? lit_html_html`<p class="chat-head__desc">${o.status}</p>` : ''}
    `;
});
// CONCATENATED MODULE: ./src/templates/chatbox_message_form.js

/* harmony default export */ var chatbox_message_form = (o => lit_html_html`
    <div class="new-msgs-indicator hidden">▼ ${o.unread_msgs} ▼</div>
    <form class="setNicknameButtonForm hidden">
        <input type="submit" class="btn btn-primary" name="join" value="Join"/>
    </form>
    <form class="sendXMPPMessage">
        <span class="chat-toolbar no-text-select"></span>
        <input type="text" placeholder="${o.label_spoiler_hint || ''}" value="${o.hint_value || ''}" class="${o.composing_spoiler ? '' : 'hidden'} spoiler-hint"/>

        <div class="suggestion-box">
            <ul class="suggestion-box__results suggestion-box__results--above" hidden=""></ul>
            <textarea
                type="text"
                class="chat-textarea suggestion-box__input
                    ${o.show_send_button ? 'chat-textarea-send-button' : ''}
                    ${o.composing_spoile ? 'spoiler' : ''}"
                placeholder="${o.label_message}">${o.message_value || ''}</textarea>
            <span class="suggestion-box__additions visually-hidden" role="status" aria-live="assertive" aria-relevant="additions"></span>
        </div>
    </form>
`);
// CONCATENATED MODULE: ./src/templates/toolbar.js


/* harmony default export */ var toolbar = (o => {
  const message_limit = converse_core_api.settings.get('message_limit');
  const show_call_button = converse_core_api.settings.get('visible_toolbar_buttons').call;
  const show_emoji_button = converse_core_api.settings.get('visible_toolbar_buttons').emoji;
  const show_send_button = converse_core_api.settings.get('show_send_button');
  const show_spoiler_button = converse_core_api.settings.get('visible_toolbar_buttons').spoiler;
  const show_toolbar = converse_core_api.settings.get('show_toolbar');
  return lit_html_html`
        <converse-chat-toolbar
            .chatview=${o.chatview}
            .model=${o.model}
            ?composing_spoiler="${o.composing_spoiler}"
            ?hidden_occupants="${o.hidden_occupants}"
            ?is_groupchat="${o.is_groupchat}"
            ?show_call_button="${show_call_button}"
            ?show_emoji_button="${show_emoji_button}"
            ?show_occupants_toggle="${o.show_occupants_toggle}"
            ?show_send_button="${show_send_button}"
            ?show_spoiler_button="${show_spoiler_button}"
            ?show_toolbar="${show_toolbar}"
            message_limit="${message_limit}"
        ></converse-chat-toolbar>
    `;
});
// CONCATENATED MODULE: ./src/templates/user_details_modal.js





const device_fingerprint = o => {
  const i18n_trusted = i18n_('Trusted');

  const i18n_untrusted = i18n_('Untrusted');

  if (o.device.get('bundle') && o.device.get('bundle').fingerprint) {
    return lit_html_html`
            <li class="list-group-item">
                <form class="fingerprint-trust">
                <div class="btn-group btn-group-toggle">
                    <label class="btn btn--small ${o.device.get('trusted') !== -1 ? 'btn-primary active' : 'btn-secondary'}">
                        <input type="radio" name="${o.device.get('id')}" value="1" ?checked=${o.device.get('trusted') !== -1}>${i18n_trusted}
                    </label>
                    <label class="btn btn--small ${o.device.get('trusted') !== -1 ? 'btn-primary active' : 'btn-secondary'}">
                        <input type="radio" name="${o.device.get('id')}" value="-1" ?checked=${o.device.get('trusted') === -1}>${i18n_untrusted}
                    </label>
                </div>
                <code class="fingerprint">${o.utils.formatFingerprint(o.device.get('bundle').fingerprint)}</code>
                </form>
            </li>
        `;
  } else {
    return '';
  }
};

const fingerprints = o => {
  const i18n_fingerprints = i18n_('OMEMO Fingerprints');

  const i18n_no_devices = i18n_("No OMEMO-enabled devices found");

  const devices = o.view.devicelist.devices;
  return lit_html_html`
        <hr/>
        <ul class="list-group fingerprints">
            <li class="list-group-item active">${i18n_fingerprints}</li>
            ${devices.length ? devices.map(device => device_fingerprint(Object.assign({
    device
  }, o))) : lit_html_html`<li class="list-group-item"> ${i18n_no_devices} </li>`}
        </ul>
    `;
};

const remove_button = o => {
  const i18n_remove_contact = i18n_('Remove as contact');

  return lit_html_html`
        <button type="button" @click="${o.removeContact}" class="btn btn-danger remove-contact">
            <i class="far fa-trash-alt"></i>${i18n_remove_contact}
        </button>
    `;
};

/* harmony default export */ var user_details_modal = (o => {
  const i18n_address = i18n_('XMPP Address');

  const i18n_email = i18n_('Email');

  const i18n_full_name = i18n_('Full Name');

  const i18n_nickname = i18n_('Nickname');

  const i18n_profile = i18n_('The User\'s Profile Image');

  const i18n_refresh = i18n_('Refresh');

  const i18n_role = i18n_('Role');

  const i18n_url = i18n_('URL');

  const avatar_data = {
    'alt_text': i18n_profile,
    'extra_classes': 'mb-3',
    'height': '120',
    'width': '120'
  };
  return lit_html_html`
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="user-details-modal-label">${o.display_name}</h5>
                    ${modal_header_close_button}
                </div>
                <div class="modal-body">
                    ${o.image ? lit_html_html`<div class="mb-4">${avatar(Object.assign(o, avatar_data))}</div>` : ''}
                    ${o.fullname ? lit_html_html`<p><label>${i18n_full_name}:</label> ${o.fullname}</p>` : ''}
                    <p><label>${i18n_address}:</label> <a href="xmpp:${o.jid}">${o.jid}</a></p>
                    ${o.nickname ? lit_html_html`<p><label>${i18n_nickname}:</label> ${o.nickname}</p>` : ''}
                    ${o.url ? lit_html_html`<p><label>${i18n_url}:</label> <a target="_blank" rel="noopener" href="${o.url}">${o.url}</a></p>` : ''}
                    ${o.email ? lit_html_html`<p><label>${i18n_email}:</label> <a href="mailto:${o.email}">${o.email}</a></p>` : ''}
                    ${o.role ? lit_html_html`<p><label>${i18n_role}:</label> ${o.role}</p>` : ''}

                    ${o._converse.pluggable.plugins['converse-omemo'].enabled(o._converse) ? fingerprints(o) : ''}
                </div>
                <div class="modal-footer">
                    ${modal_close_button}
                    <button type="button" class="btn btn-info refresh-contact"><i class="fa fa-refresh"> </i>${i18n_refresh}</button>
                    ${o.allow_contact_removal && o.is_roster_contact ? remove_button(o) : ''}

                </div>
            </div>
        </div>
    `;
});
// CONCATENATED MODULE: ./src/converse-chatview.js
/**
 * @module converse-chatview
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */


















const {
  Strophe: converse_chatview_Strophe,
  dayjs: converse_chatview_dayjs
} = converse.env;
const converse_chatview_u = converse.env.utils;
/**
 * The View of an open/ongoing chat conversation.
 * @class
 * @namespace _converse.ChatBoxView
 * @memberOf _converse
 */

const ChatBoxView = View.extend({
  length: 200,
  className: 'chatbox hidden',
  is_chatroom: false,
  // Leaky abstraction from MUC
  events: {
    'click .chatbox-navback': 'showControlBox',
    'click .new-msgs-indicator': 'viewUnreadMessages',
    'click .send-button': 'onFormSubmitted',
    'click .toggle-clear': 'clearMessages',
    'input .chat-textarea': 'inputChanged',
    'keydown .chat-textarea': 'onKeyDown',
    'keyup .chat-textarea': 'onKeyUp',
    'paste .chat-textarea': 'onPaste'
  },

  async initialize() {
    this.initDebounced();
    this.listenTo(this.model, 'change:composing_spoiler', this.renderMessageForm);
    this.listenTo(this.model, 'change:hidden', m => m.get('hidden') ? this.hide() : this.show());
    this.listenTo(this.model, 'change:status', this.onStatusMessageChanged);
    this.listenTo(this.model, 'destroy', this.remove);
    this.listenTo(this.model, 'show', this.show);
    this.listenTo(this.model, 'vcard:change', this.renderHeading);

    if (this.model.contact) {
      this.listenTo(this.model.contact, 'destroy', this.renderHeading);
    }

    if (this.model.rosterContactAdded) {
      this.model.rosterContactAdded.then(() => {
        this.listenTo(this.model.contact, 'change:nickname', this.renderHeading);
        this.renderHeading();
      });
    }

    this.listenTo(this.model.presence, 'change:show', this.onPresenceChanged);
    this.render(); // Need to be registered after render has been called.

    this.listenTo(this.model.messages, 'add', this.onMessageAdded);
    this.listenTo(this.model.messages, 'remove', this.renderChatHistory);
    this.listenTo(this.model.messages, 'rendered', this.maybeScrollDown);
    this.listenTo(this.model.messages, 'reset', this.renderChatHistory);
    this.listenTo(this.model.notifications, 'change', this.renderNotifications);
    this.listenTo(this.model, 'change:show_help_messages', this.renderHelpMessages);
    await this.model.messages.fetched;
    this.insertIntoDOM();
    this.model.maybeShow();
    this.scrollDown();
    /**
     * Triggered once the {@link _converse.ChatBoxView} has been initialized
     * @event _converse#chatBoxViewInitialized
     * @type { _converse.HeadlinesBoxView }
     * @example _converse.api.listen.on('chatBoxViewInitialized', view => { ... });
     */

    converse_core_api.trigger('chatBoxViewInitialized', this);
  },

  initDebounced() {
    this.markScrolled = lodash_es_debounce(this._markScrolled, 100);
    this.debouncedScrollDown = lodash_es_debounce(this.scrollDown, 100); // For tests that use Jasmine.Clock we want to turn of
    // debouncing, since setTimeout breaks.

    if (converse_core_api.settings.get('debounced_content_rendering')) {
      this.renderChatHistory = lodash_es_debounce(() => this.renderChatContent(false), 100);
      this.renderNotifications = lodash_es_debounce(() => this.renderChatContent(true), 100);
    } else {
      this.renderChatHistory = () => this.renderChatContent(false);

      this.renderNotifications = () => this.renderChatContent(true);
    }
  },

  render() {
    const result = templates_chatbox(Object.assign(this.model.toJSON(), {
      'markScrolled': ev => this.markScrolled(ev)
    }));
    render_render(result, this.el);
    this.content = this.el.querySelector('.chat-content');
    this.notifications = this.el.querySelector('.chat-content__notifications');
    this.msgs_container = this.el.querySelector('.chat-content__messages');
    this.help_container = this.el.querySelector('.chat-content__help');
    this.renderChatContent();
    this.renderMessageForm();
    this.renderHeading();
    return this;
  },

  onMessageAdded(message) {
    this.renderChatHistory();

    if (converse_chatview_u.isNewMessage(message)) {
      if (message.get('sender') === 'me') {
        // We remove the "scrolled" flag so that the chat area
        // gets scrolled down. We always want to scroll down
        // when the user writes a message as opposed to when a
        // message is received.
        this.model.set('scrolled', false);
      } else if (this.model.get('scrolled', true)) {
        this.showNewMessagesIndicator();
      }
    }
  },

  getNotifications() {
    if (this.model.notifications.get('chat_state') === converse_core_converse.COMPOSING) {
      return i18n_('%1$s is typing', this.model.getDisplayName());
    } else if (this.model.notifications.get('chat_state') === converse_core_converse.PAUSED) {
      return i18n_('%1$s has stopped typing', this.model.getDisplayName());
    } else if (this.model.notifications.get('chat_state') === converse_core_converse.GONE) {
      return i18n_('%1$s has gone away', this.model.getDisplayName());
    } else {
      return '';
    }
  },

  getHelpMessages() {
    return [`<strong>/clear</strong>: ${i18n_('Remove messages')}`, `<strong>/close</strong>: ${i18n_('Close this chat')}`, `<strong>/me</strong>: ${i18n_('Write in the third person')}`, `<strong>/help</strong>: ${i18n_('Show this menu')}`];
  },

  renderHelpMessages() {
    render_render(lit_html_html`<converse-chat-help
                .model=${this.model}
                .messages=${this.getHelpMessages()}
                ?hidden=${!this.model.get('show_help_messages')}
                type="info"
                chat_type="${this.model.get('type')}"></converse-chat-help>`, this.help_container);
  },

  renderChatContent(msgs_by_ref = false) {
    if (!this.tpl_chat_content) {
      this.tpl_chat_content = o => {
        return lit_html_html`
                    <converse-chat-content
                        .chatview=${this}
                        .messages=${o.messages}
                        notifications=${o.notifications}>
                    </converse-chat-content>`;
      };
    }

    const msg_models = this.model.messages.models;
    const messages = msgs_by_ref ? msg_models : Array.from(msg_models);
    render_render(this.tpl_chat_content({
      messages,
      'notifications': this.getNotifications()
    }), this.msgs_container);
  },

  renderToolbar() {
    if (!converse_core_api.settings.get('show_toolbar')) {
      return this;
    }

    const options = Object.assign({
      'model': this.model,
      'chatview': this
    }, this.model.toJSON(), this.getToolbarOptions());
    render_render(toolbar(options), this.el.querySelector('.chat-toolbar'));
    /**
     * Triggered once the _converse.ChatBoxView's toolbar has been rendered
     * @event _converse#renderToolbar
     * @type { _converse.ChatBoxView }
     * @example _converse.api.listen.on('renderToolbar', view => { ... });
     */

    converse_core_api.trigger('renderToolbar', this);
    return this;
  },

  renderMessageForm() {
    var _this$el$querySelecto, _this$el$querySelecto2;

    const form_container = this.el.querySelector('.message-form-container');
    render_render(chatbox_message_form(Object.assign(this.model.toJSON(), {
      'hint_value': (_this$el$querySelecto = this.el.querySelector('.spoiler-hint')) === null || _this$el$querySelecto === void 0 ? void 0 : _this$el$querySelecto.value,
      'label_message': this.model.get('composing_spoiler') ? i18n_('Hidden message') : i18n_('Message'),
      'label_spoiler_hint': i18n_('Optional hint'),
      'message_value': (_this$el$querySelecto2 = this.el.querySelector('.chat-textarea')) === null || _this$el$querySelecto2 === void 0 ? void 0 : _this$el$querySelecto2.value,
      'show_send_button': converse_core_api.settings.get('show_send_button'),
      'show_toolbar': converse_core_api.settings.get('show_toolbar'),
      'unread_msgs': i18n_('You have unread messages')
    })), form_container);
    this.el.addEventListener('focusin', ev => this.emitFocused(ev));
    this.el.addEventListener('focusout', ev => this.emitBlurred(ev));
    this.renderToolbar();
  },

  showControlBox() {
    var _converse$chatboxview;

    // Used in mobile view, to navigate back to the controlbox
    (_converse$chatboxview = converse_core_converse.chatboxviews.get('controlbox')) === null || _converse$chatboxview === void 0 ? void 0 : _converse$chatboxview.show();
    this.hide();
  },

  showUserDetailsModal(ev) {
    ev.preventDefault();

    if (this.user_details_modal === undefined) {
      this.user_details_modal = new converse_core_converse.UserDetailsModal({
        model: this.model
      });
    }

    this.user_details_modal.show(ev);
  },

  onDragOver(evt) {
    evt.preventDefault();
  },

  onDrop(evt) {
    if (evt.dataTransfer.files.length == 0) {
      // There are no files to be dropped, so this isn’t a file
      // transfer operation.
      return;
    }

    evt.preventDefault();
    this.model.sendFiles(evt.dataTransfer.files);
  },

  async renderHeading() {
    const tpl = await this.generateHeadingTemplate();
    render_render(tpl, this.el.querySelector('.chat-head-chatbox'));
  },

  async getHeadingStandaloneButton(promise_or_data) {
    const data = await promise_or_data;
    return lit_html_html`<a href="#"
            class="chatbox-btn ${data.a_class} fa ${data.icon_class}"
            @click=${data.handler}
            title="${data.i18n_title}"></a>`;
  },

  async getHeadingDropdownItem(promise_or_data) {
    const data = await promise_or_data;
    return lit_html_html`<a href="#"
            class="dropdown-item ${data.a_class}"
            @click=${data.handler}
            title="${data.i18n_title}"><i class="fa ${data.icon_class}"></i>${data.i18n_text}</a>`;
  },

  async generateHeadingTemplate() {
    var _this$model;

    const vcard = (_this$model = this.model) === null || _this$model === void 0 ? void 0 : _this$model.vcard;
    const vcard_json = vcard ? vcard.toJSON() : {};
    const heading_btns = await this.getHeadingButtons();
    const standalone_btns = heading_btns.filter(b => b.standalone);
    const dropdown_btns = heading_btns.filter(b => !b.standalone);
    return chatbox_head(Object.assign(vcard_json, this.model.toJSON(), {
      '_converse': converse_core_converse,
      'dropdown_btns': dropdown_btns.map(b => this.getHeadingDropdownItem(b)),
      'standalone_btns': standalone_btns.map(b => this.getHeadingStandaloneButton(b)),
      'display_name': this.model.getDisplayName()
    }));
  },

  /**
   * Returns a list of objects which represent buttons for the chat's header.
   * @async
   * @emits _converse#getHeadingButtons
   * @private
   * @method _converse.ChatBoxView#getHeadingButtons
   */
  getHeadingButtons() {
    const buttons = [{
      'a_class': 'show-user-details-modal',
      'handler': ev => this.showUserDetailsModal(ev),
      'i18n_text': i18n_('Details'),
      'i18n_title': i18n_('See more information about this person'),
      'icon_class': 'fa-id-card',
      'name': 'details',
      'standalone': converse_core_api.settings.get("view_mode") === 'overlayed'
    }];

    if (!converse_core_api.settings.get("singleton")) {
      buttons.push({
        'a_class': 'close-chatbox-button',
        'handler': ev => this.close(ev),
        'i18n_text': i18n_('Close'),
        'i18n_title': i18n_('Close and end this conversation'),
        'icon_class': 'fa-times',
        'name': 'close',
        'standalone': converse_core_api.settings.get("view_mode") === 'overlayed'
      });
    }
    /**
     * *Hook* which allows plugins to add more buttons to a chat's heading.
     * @event _converse#getHeadingButtons
     */


    return converse_core_converse.api.hook('getHeadingButtons', this, buttons);
  },

  getToolbarOptions() {
    //  FIXME: can this be removed?
    return {};
  },

  /**
   * Scrolls the chat down, *if* appropriate.
   *
   * Will only scroll down if we have received a message from
   * ourselves, or if the chat was scrolled down before (i.e. the
   * `scrolled` flag is `false`);
   * @param { _converse.Message|_converse.ChatRoomMessage } [message]
   *  - An optional message that serves as the cause for needing to scroll down.
   */
  maybeScrollDown(message) {
    const new_own_msg = !(message !== null && message !== void 0 && message.get('is_archived')) && (message === null || message === void 0 ? void 0 : message.get('sender')) === 'me';

    if ((new_own_msg || !this.model.get('scrolled')) && !this.model.isHidden()) {
      this.debouncedScrollDown();
    }
  },

  /**
   * Scrolls the chat down.
   *
   * This method will always scroll the chat down, regardless of
   * whether the user scrolled up manually or not.
   * @param { Event } [ev] - An optional event that is the cause for needing to scroll down.
   */
  scrollDown(ev) {
    var _ev$preventDefault, _ev$stopPropagation;

    ev === null || ev === void 0 ? void 0 : (_ev$preventDefault = ev.preventDefault) === null || _ev$preventDefault === void 0 ? void 0 : _ev$preventDefault.call(ev);
    ev === null || ev === void 0 ? void 0 : (_ev$stopPropagation = ev.stopPropagation) === null || _ev$stopPropagation === void 0 ? void 0 : _ev$stopPropagation.call(ev);

    if (this.model.get('scrolled')) {
      converse_chatview_u.safeSave(this.model, {
        'scrolled': false,
        'scrollTop': null
      });
    }

    if (this.msgs_container.scrollTo) {
      const behavior = this.msgs_container.scrollTop ? 'smooth' : 'auto';
      this.msgs_container.scrollTo({
        'top': this.msgs_container.scrollHeight,
        behavior
      });
    } else {
      this.msgs_container.scrollTop = this.msgs_container.scrollHeight;
    }

    this.onScrolledDown();
  },

  /**
   * Scroll to the previously saved scrollTop position, or scroll
   * down if it wasn't set.
   */
  maintainScrollTop() {
    const pos = this.model.get('scrollTop');

    if (pos) {
      this.msgs_container.scrollTop = pos;
    } else {
      this.scrollDown();
    }
  },

  insertIntoDOM() {
    converse_core_converse.chatboxviews.insertRowColumn(this.el);
    /**
     * Triggered once the _converse.ChatBoxView has been inserted into the DOM
     * @event _converse#chatBoxInsertedIntoDOM
     * @type { _converse.ChatBoxView | _converse.HeadlinesBoxView }
     * @example _converse.api.listen.on('chatBoxInsertedIntoDOM', view => { ... });
     */


    converse_core_api.trigger('chatBoxInsertedIntoDOM', this);
    return this;
  },

  addSpinner(append = false) {
    if (this.el.querySelector('.spinner') === null) {
      const el = converse_chatview_u.getElementFromTemplateResult(spinner());

      if (append) {
        this.content.insertAdjacentElement('beforeend', el);
        this.scrollDown();
      } else {
        this.content.insertAdjacentElement('afterbegin', el);
      }
    }
  },

  clearSpinner() {
    this.content.querySelectorAll('.spinner').forEach(converse_chatview_u.removeElement);
  },

  onStatusMessageChanged(item) {
    this.renderHeading();
    /**
     * When a contact's custom status message has changed.
     * @event _converse#contactStatusMessageChanged
     * @type {object}
     * @property { object } contact - The chat buddy
     * @property { string } message - The message text
     * @example _converse.api.listen.on('contactStatusMessageChanged', obj => { ... });
     */

    converse_core_api.trigger('contactStatusMessageChanged', {
      'contact': item.attributes,
      'message': item.get('status')
    });
  },

  /**
   * Given a message element, determine wether it should be
   * marked as a followup message to the previous element.
   *
   * Also determine whether the element following it is a
   * followup message or not.
   *
   * Followup messages are subsequent ones written by the same
   * author with no other conversation elements in between and
   * which were posted within 10 minutes of one another.
   * @private
   * @method _converse.ChatBoxView#markFollowups
   * @param { HTMLElement } el - The message element
   */
  markFollowups(el) {
    const from = el.getAttribute('data-from');
    const previous_el = el.previousElementSibling;
    const date = converse_chatview_dayjs(el.getAttribute('data-isodate'));
    const next_el = el.nextElementSibling;

    if (!converse_chatview_u.hasClass('chat-msg--action', el) && !converse_chatview_u.hasClass('chat-msg--action', previous_el) && !converse_chatview_u.hasClass('chat-info', el) && !converse_chatview_u.hasClass('chat-info', previous_el) && previous_el.getAttribute('data-from') === from && date.isBefore(converse_chatview_dayjs(previous_el.getAttribute('data-isodate')).add(10, 'minutes')) && el.getAttribute('data-encrypted') === previous_el.getAttribute('data-encrypted')) {
      converse_chatview_u.addClass('chat-msg--followup', el);
    }

    if (!next_el) {
      return;
    }

    if (!converse_chatview_u.hasClass('chat-msg--action', el) && converse_chatview_u.hasClass('chat-info', el) && next_el.getAttribute('data-from') === from && converse_chatview_dayjs(next_el.getAttribute('data-isodate')).isBefore(date.add(10, 'minutes')) && el.getAttribute('data-encrypted') === next_el.getAttribute('data-encrypted')) {
      converse_chatview_u.addClass('chat-msg--followup', next_el);
    } else {
      converse_chatview_u.removeClass('chat-msg--followup', next_el);
    }
  },

  parseMessageForCommands(text) {
    const match = text.replace(/^\s*/, "").match(/^\/(.*)\s*$/);

    if (match) {
      if (match[1] === "clear") {
        this.clearMessages();
        return true;
      } else if (match[1] === "close") {
        this.close();
        return true;
      } else if (match[1] === "help") {
        this.model.set({
          'show_help_messages': true
        });
        return true;
      }
    }
  },

  async onFormSubmitted(ev) {
    var _this$el$querySelecto3;

    ev.preventDefault();
    const textarea = this.el.querySelector('.chat-textarea');
    const message_text = textarea.value.trim();

    if (converse_core_api.settings.get('message_limit') && message_text.length > converse_core_api.settings.get('message_limit') || !message_text.replace(/\s/g, '').length) {
      return;
    }

    if (!converse_core_converse.connection.authenticated) {
      const err_msg = i18n_('Sorry, the connection has been lost, and your message could not be sent');

      converse_core_api.alert('error', i18n_('Error'), err_msg);
      converse_core_api.connection.reconnect();
      return;
    }

    let spoiler_hint,
        hint_el = {};

    if (this.model.get('composing_spoiler')) {
      hint_el = this.el.querySelector('form.sendXMPPMessage input.spoiler-hint');
      spoiler_hint = hint_el.value;
    }

    converse_chatview_u.addClass('disabled', textarea);
    textarea.setAttribute('disabled', 'disabled');
    (_this$el$querySelecto3 = this.el.querySelector('converse-emoji-dropdown')) === null || _this$el$querySelecto3 === void 0 ? void 0 : _this$el$querySelecto3.hideMenu();
    const is_command = this.parseMessageForCommands(message_text);
    const message = is_command ? null : await this.model.sendMessage(message_text, spoiler_hint);

    if (is_command || message) {
      hint_el.value = '';
      textarea.value = '';
      converse_chatview_u.removeClass('correcting', textarea);
      textarea.style.height = 'auto';
      this.updateCharCounter(textarea.value);
    }

    if (message) {
      /**
       * Triggered whenever a message is sent by the user
       * @event _converse#messageSend
       * @type { _converse.Message }
       * @example _converse.api.listen.on('messageSend', message => { ... });
       */
      converse_core_api.trigger('messageSend', message);
    }

    if (converse_core_api.settings.get("view_mode") === 'overlayed') {
      // XXX: Chrome flexbug workaround. The .chat-content area
      // doesn't resize when the textarea is resized to its original size.
      this.msgs_container.parentElement.style.display = 'none';
    }

    textarea.removeAttribute('disabled');
    converse_chatview_u.removeClass('disabled', textarea);

    if (converse_core_api.settings.get("view_mode") === 'overlayed') {
      // XXX: Chrome flexbug workaround.
      this.msgs_container.parentElement.style.display = '';
    } // Suppress events, otherwise superfluous CSN gets set
    // immediately after the message, causing rate-limiting issues.


    this.model.setChatState(converse_core_converse.ACTIVE, {
      'silent': true
    });
    textarea.focus();
  },

  updateCharCounter(chars) {
    if (converse_core_api.settings.get('message_limit')) {
      const message_limit = this.el.querySelector('.message-limit');
      const counter = converse_core_api.settings.get('message_limit') - chars.length;
      message_limit.textContent = counter;

      if (counter < 1) {
        converse_chatview_u.addClass('error', message_limit);
      } else {
        converse_chatview_u.removeClass('error', message_limit);
      }
    }
  },

  onPaste(ev) {
    if (ev.clipboardData.files.length !== 0) {
      ev.preventDefault(); // Workaround for quirk in at least Firefox 60.7 ESR:
      // It seems that pasted files disappear from the event payload after
      // the event has finished, which apparently happens during async
      // processing in sendFiles(). So we copy the array here.

      this.model.sendFiles(Array.from(ev.clipboardData.files));
      return;
    }

    this.updateCharCounter(ev.clipboardData.getData('text/plain'));
  },

  autocompleteInPicker(input, value) {
    const emoji_dropdown = this.el.querySelector('converse-emoji-dropdown');
    const emoji_picker = this.el.querySelector('converse-emoji-picker');

    if (emoji_picker && emoji_dropdown) {
      emoji_picker.model.set({
        'ac_position': input.selectionStart,
        'autocompleting': value,
        'query': value
      });
      emoji_dropdown.showMenu();
      return true;
    }
  },

  onEmojiReceivedFromPicker(emoji) {
    const model = this.el.querySelector('converse-emoji-picker').model;
    const autocompleting = model.get('autocompleting');
    const ac_position = model.get('ac_position');
    this.insertIntoTextArea(emoji, autocompleting, false, ac_position);
  },

  /**
   * Event handler for when a depressed key goes up
   * @private
   * @method _converse.ChatBoxView#onKeyUp
   */
  onKeyUp(ev) {
    this.updateCharCounter(ev.target.value);
  },

  /**
   * Event handler for when a key is pressed down in a chat box textarea.
   * @private
   * @method _converse.ChatBoxView#onKeyDown
   * @param { Event } ev
   */
  onKeyDown(ev) {
    if (ev.ctrlKey) {
      // When ctrl is pressed, no chars are entered into the textarea.
      return;
    }

    if (!ev.shiftKey && !ev.altKey && !ev.metaKey) {
      if (ev.keyCode === converse.keycodes.TAB) {
        const value = converse_chatview_u.getCurrentWord(ev.target, null, /(:.*?:)/g);

        if (value.startsWith(':') && this.autocompleteInPicker(ev.target, value)) {
          ev.preventDefault();
          ev.stopPropagation();
        }
      } else if (ev.keyCode === converse.keycodes.FORWARD_SLASH) {
        // Forward slash is used to run commands. Nothing to do here.
        return;
      } else if (ev.keyCode === converse.keycodes.ESCAPE) {
        return this.onEscapePressed(ev);
      } else if (ev.keyCode === converse.keycodes.ENTER) {
        return this.onEnterPressed(ev);
      } else if (ev.keyCode === converse.keycodes.UP_ARROW && !ev.target.selectionEnd) {
        const textarea = this.el.querySelector('.chat-textarea');

        if (!textarea.value || converse_chatview_u.hasClass('correcting', textarea)) {
          return this.editEarlierMessage();
        }
      } else if (ev.keyCode === converse.keycodes.DOWN_ARROW && ev.target.selectionEnd === ev.target.value.length && converse_chatview_u.hasClass('correcting', this.el.querySelector('.chat-textarea'))) {
        return this.editLaterMessage();
      }
    }

    if ([converse.keycodes.SHIFT, converse.keycodes.META, converse.keycodes.META_RIGHT, converse.keycodes.ESCAPE, converse.keycodes.ALT].includes(ev.keyCode)) {
      return;
    }

    if (this.model.get('chat_state') !== converse_core_converse.COMPOSING) {
      // Set chat state to composing if keyCode is not a forward-slash
      // (which would imply an internal command and not a message).
      this.model.setChatState(converse_core_converse.COMPOSING);
    }
  },

  getOwnMessages() {
    return this.model.messages.filter({
      'sender': 'me'
    });
  },

  onEnterPressed(ev) {
    return this.onFormSubmitted(ev);
  },

  onEscapePressed(ev) {
    ev.preventDefault();
    const idx = this.model.messages.findLastIndex('correcting');
    const message = idx >= 0 ? this.model.messages.at(idx) : null;

    if (message) {
      message.save('correcting', false);
    }

    this.insertIntoTextArea('', true, false);
  },

  async onMessageRetractButtonClicked(message) {
    if (message.get('sender') !== 'me') {
      return headless_log.error("onMessageRetractButtonClicked called for someone else's message!");
    }

    const retraction_warning = i18n_("Be aware that other XMPP/Jabber clients (and servers) may " + "not yet support retractions and that this message may not " + "be removed everywhere.");

    const messages = [i18n_('Are you sure you want to retract this message?')];

    if (converse_core_api.settings.get('show_retraction_warning')) {
      messages[1] = retraction_warning;
    }

    const result = await converse_core_api.confirm(i18n_('Confirm'), messages);

    if (result) {
      this.model.retractOwnMessage(message);
    }
  },

  onMessageEditButtonClicked(message) {
    var _this$el$querySelecto4;

    const currently_correcting = this.model.messages.findWhere('correcting');
    const unsent_text = (_this$el$querySelecto4 = this.el.querySelector('.chat-textarea')) === null || _this$el$querySelecto4 === void 0 ? void 0 : _this$el$querySelecto4.value;

    if (unsent_text && (!currently_correcting || currently_correcting.get('message') !== unsent_text)) {
      if (!confirm(i18n_("You have an unsent message which will be lost if you continue. Are you sure?"))) {
        return;
      }
    }

    if (currently_correcting !== message) {
      currently_correcting === null || currently_correcting === void 0 ? void 0 : currently_correcting.save('correcting', false);
      message.save('correcting', true);
      this.insertIntoTextArea(converse_chatview_u.prefixMentions(message), true, true);
    } else {
      message.save('correcting', false);
      this.insertIntoTextArea('', true, false);
    }
  },

  editLaterMessage() {
    let message;
    let idx = this.model.messages.findLastIndex('correcting');

    if (idx >= 0) {
      this.model.messages.at(idx).save('correcting', false);

      while (idx < this.model.messages.length - 1) {
        idx += 1;
        const candidate = this.model.messages.at(idx);

        if (candidate.get('editable')) {
          message = candidate;
          break;
        }
      }
    }

    if (message) {
      this.insertIntoTextArea(converse_chatview_u.prefixMentions(message), true, true);
      message.save('correcting', true);
    } else {
      this.insertIntoTextArea('', true, false);
    }
  },

  editEarlierMessage() {
    let message;
    let idx = this.model.messages.findLastIndex('correcting');

    if (idx >= 0) {
      this.model.messages.at(idx).save('correcting', false);

      while (idx > 0) {
        idx -= 1;
        const candidate = this.model.messages.at(idx);

        if (candidate.get('editable')) {
          message = candidate;
          break;
        }
      }
    }

    message = message || this.getOwnMessages().reverse().find(m => m.get('editable'));

    if (message) {
      this.insertIntoTextArea(converse_chatview_u.prefixMentions(message), true, true);
      message.save('correcting', true);
    }
  },

  inputChanged(ev) {
    const height = ev.target.scrollHeight + 'px';

    if (ev.target.style.height != height) {
      ev.target.style.height = 'auto';
      ev.target.style.height = height;
    }
  },

  async clearMessages(ev) {
    if (ev && ev.preventDefault) {
      ev.preventDefault();
    }

    const result = confirm(i18n_("Are you sure you want to clear the messages from this conversation?"));

    if (result === true) {
      await this.model.clearMessages();
    }

    return this;
  },

  /**
   * Insert a particular string value into the textarea of this chat box.
   * @private
   * @method _converse.ChatBoxView#insertIntoTextArea
   * @param {string} value - The value to be inserted.
   * @param {(boolean|string)} [replace] - Whether an existing value
   *  should be replaced. If set to `true`, the entire textarea will
   *  be replaced with the new value. If set to a string, then only
   *  that string will be replaced *if* a position is also specified.
   * @param {integer} [position] - The end index of the string to be
   * replaced with the new value.
   */
  insertIntoTextArea(value, replace = false, correcting = false, position) {
    const textarea = this.el.querySelector('.chat-textarea');

    if (correcting) {
      converse_chatview_u.addClass('correcting', textarea);
    } else {
      converse_chatview_u.removeClass('correcting', textarea);
    }

    if (replace) {
      if (position && typeof replace == 'string') {
        textarea.value = textarea.value.replace(new RegExp(replace, 'g'), (match, offset) => offset == position - replace.length ? value + ' ' : match);
      } else {
        textarea.value = value;
      }
    } else {
      let existing = textarea.value;

      if (existing && existing[existing.length - 1] !== ' ') {
        existing = existing + ' ';
      }

      textarea.value = existing + value + ' ';
    }

    this.updateCharCounter(textarea.value);
    converse_chatview_u.placeCaretAtEnd(textarea);
  },

  onPresenceChanged(item) {
    const show = item.get('show');
    const fullname = this.model.getDisplayName();
    let text;

    if (converse_chatview_u.isVisible(this.el)) {
      if (show === 'offline') {
        text = i18n_('%1$s has gone offline', fullname);
      } else if (show === 'away') {
        text = i18n_('%1$s has gone away', fullname);
      } else if (show === 'dnd') {
        text = i18n_('%1$s is busy', fullname);
      } else if (show === 'online') {
        text = i18n_('%1$s is online', fullname);
      }

      text && this.model.createMessage({
        'message': text,
        'type': 'info'
      });
    }
  },

  async close(ev) {
    if (ev && ev.preventDefault) {
      ev.preventDefault();
    }

    if (converse_core_converse.router.history.getFragment() === "converse/chat?jid=" + this.model.get('jid')) {
      converse_core_converse.router.navigate('');
    }

    if (converse_core_api.connection.connected()) {
      // Immediately sending the chat state, because the
      // model is going to be destroyed afterwards.
      this.model.setChatState(converse_core_converse.INACTIVE);
      this.model.sendChatState();
    }

    await this.model.close();
    this.remove();
    /**
     * Triggered once a chatbox has been closed.
     * @event _converse#chatBoxClosed
     * @type { _converse.ChatBoxView | _converse.ChatRoomView }
     * @example _converse.api.listen.on('chatBoxClosed', view => { ... });
     */

    converse_core_api.trigger('chatBoxClosed', this);
    return this;
  },

  emitBlurred(ev) {
    if (this.el.contains(document.activeElement) || this.el.contains(ev.relatedTarget)) {
      // Something else in this chatbox is still focused
      return;
    }
    /**
     * Triggered when the focus has been removed from a particular chat.
     * @event _converse#chatBoxBlurred
     * @type { _converse.ChatBoxView | _converse.ChatRoomView }
     * @example _converse.api.listen.on('chatBoxBlurred', (view, event) => { ... });
     */


    converse_core_api.trigger('chatBoxBlurred', this, ev);
  },

  emitFocused(ev) {
    if (this.el.contains(ev.relatedTarget)) {
      // Something else in this chatbox was already focused
      return;
    }
    /**
     * Triggered when the focus has been moved to a particular chat.
     * @event _converse#chatBoxFocused
     * @type { _converse.ChatBoxView | _converse.ChatRoomView }
     * @example _converse.api.listen.on('chatBoxFocused', (view, event) => { ... });
     */


    converse_core_api.trigger('chatBoxFocused', this, ev);
  },

  focus() {
    const textarea_el = this.el.getElementsByClassName('chat-textarea')[0];

    if (textarea_el && document.activeElement !== textarea_el) {
      textarea_el.focus();
    }

    return this;
  },

  maybeFocus() {
    converse_core_api.settings.get('auto_focus') && this.focus();
  },

  hide() {
    this.el.classList.add('hidden');
    return this;
  },

  afterShown() {
    this.model.clearUnreadMsgCounter();
    this.model.setChatState(converse_core_converse.ACTIVE);
    this.scrollDown();
    this.maybeFocus();
  },

  show() {
    if (this.model.get('hidden')) {
      headless_log.debug(`Not showing chat ${this.model.get('jid')} because it's set as hidden`);
      return;
    }

    if (converse_chatview_u.isVisible(this.el)) {
      this.maybeFocus();
      return;
    }

    if (converse_core_api.settings.get('animate')) {
      converse_chatview_u.fadeIn(this.el, () => this.afterShown());
    } else {
      converse_chatview_u.showElement(this.el);
      this.afterShown();
    }
  },

  showNewMessagesIndicator() {
    converse_chatview_u.showElement(this.el.querySelector('.new-msgs-indicator'));
  },

  hideNewMessagesIndicator() {
    const new_msgs_indicator = this.el.querySelector('.new-msgs-indicator');

    if (new_msgs_indicator !== null) {
      new_msgs_indicator.classList.add('hidden');
    }
  },

  /**
   * Called when the chat content is scrolled up or down.
   * We want to record when the user has scrolled away from
   * the bottom, so that we don't automatically scroll away
   * from what the user is reading when new messages are received.
   *
   * Don't call this method directly, instead, call `markScrolled`,
   * which debounces this method by 100ms.
   * @private
   */
  _markScrolled: function (ev) {
    let scrolled = true;
    let scrollTop = null;
    const is_at_bottom = this.msgs_container.scrollTop + this.msgs_container.clientHeight >= this.msgs_container.scrollHeight - 62; // sigh...

    if (is_at_bottom) {
      scrolled = false;
      this.onScrolledDown();
    } else if (this.msgs_container.scrollTop === 0) {
      /**
       * Triggered once the chat's message area has been scrolled to the top
       * @event _converse#chatBoxScrolledUp
       * @property { _converse.ChatBoxView | _converse.ChatRoomView } view
       * @example _converse.api.listen.on('chatBoxScrolledUp', obj => { ... });
       */
      converse_core_api.trigger('chatBoxScrolledUp', this);
    } else {
      scrollTop = ev.target.scrollTop;
    }

    converse_chatview_u.safeSave(this.model, {
      scrolled,
      scrollTop
    });
  },

  viewUnreadMessages() {
    this.model.save({
      'scrolled': false,
      'scrollTop': null
    });
    this.scrollDown();
  },

  onScrolledDown() {
    this.hideNewMessagesIndicator();

    if (!this.model.isHidden()) {
      this.model.clearUnreadMsgCounter(); // Clear location hash if set to one of the messages in our history

      const hash = window.location.hash;
      hash && this.model.messages.get(hash.slice(1)) && converse_core_converse.router.history.navigate();
    }
    /**
     * Triggered once the chat's message area has been scrolled down to the bottom.
     * @event _converse#chatBoxScrolledDown
     * @type {object}
     * @property { _converse.ChatBox | _converse.ChatRoom } chatbox - The chat model
     * @example _converse.api.listen.on('chatBoxScrolledDown', obj => { ... });
     */


    converse_core_api.trigger('chatBoxScrolledDown', {
      'chatbox': this.model
    }); // TODO: clean up
  },

  onWindowStateChanged(state) {
    if (state === 'visible') {
      if (!this.model.isHidden()) {
        // this.model.setChatState(_converse.ACTIVE);
        if (this.model.get('num_unread', 0)) {
          this.model.clearUnreadMsgCounter();
        }
      }
    } else if (state === 'hidden') {
      this.model.setChatState(converse_core_converse.INACTIVE, {
        'silent': true
      });
      this.model.sendChatState();
    }
  }

});
converse.plugins.add('converse-chatview', {
  /* Plugin dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin.
   *
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found. By default it's
   * false, which means these plugins are only loaded opportunistically.
   *
   * NB: These plugins need to have already been loaded via require.js.
   */
  dependencies: ["converse-chatboxviews", "converse-chat", "converse-disco", "converse-modal"],

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    converse_core_api.settings.extend({
      'auto_focus': true,
      'debounced_content_rendering': true,
      'filter_url_query_params': null,
      'image_urls_regex': null,
      'message_limit': 0,
      'muc_hats': ['xep317'],
      'show_images_inline': true,
      'show_message_avatar': true,
      'show_retraction_warning': true,
      'show_send_button': true,
      'show_toolbar': true,
      'time_format': 'HH:mm',
      'use_system_emojis': true,
      'visible_toolbar_buttons': {
        'call': false,
        'clear': true,
        'emoji': true,
        'spoiler': true
      }
    });
    converse_core_converse.ChatBoxView = ChatBoxView;
    converse_core_converse.UserDetailsModal = BootstrapModal.extend({
      id: "user-details-modal",
      events: {
        'click button.refresh-contact': 'refreshContact',
        'click .fingerprint-trust .btn input': 'toggleDeviceTrust'
      },

      initialize() {
        BootstrapModal.prototype.initialize.apply(this, arguments);
        this.model.rosterContactAdded.then(() => this.registerContactEventHandlers());
        this.listenTo(this.model, 'change', this.render);
        this.registerContactEventHandlers();
        /**
         * Triggered once the _converse.UserDetailsModal has been initialized
         * @event _converse#userDetailsModalInitialized
         * @type { _converse.ChatBox }
         * @example _converse.api.listen.on('userDetailsModalInitialized', chatbox => { ... });
         */

        converse_core_api.trigger('userDetailsModalInitialized', this.model);
      },

      toHTML() {
        var _this$model2;

        const vcard = (_this$model2 = this.model) === null || _this$model2 === void 0 ? void 0 : _this$model2.vcard;
        const vcard_json = vcard ? vcard.toJSON() : {};
        return user_details_modal(Object.assign(this.model.toJSON(), vcard_json, {
          '_converse': converse_core_converse,
          'allow_contact_removal': converse_core_api.settings.get('allow_contact_removal'),
          'display_name': this.model.getDisplayName(),
          'is_roster_contact': this.model.contact !== undefined,
          'removeContact': ev => this.removeContact(ev),
          'view': this,
          'utils': converse_chatview_u
        }));
      },

      registerContactEventHandlers() {
        if (this.model.contact !== undefined) {
          this.listenTo(this.model.contact, 'change', this.render);
          this.listenTo(this.model.contact.vcard, 'change', this.render);
          this.model.contact.on('destroy', () => {
            delete this.model.contact;
            this.render();
          });
        }
      },

      async refreshContact(ev) {
        if (ev && ev.preventDefault) {
          ev.preventDefault();
        }

        const refresh_icon = this.el.querySelector('.fa-refresh');
        converse_chatview_u.addClass('fa-spin', refresh_icon);

        try {
          await converse_core_api.vcard.update(this.model.contact.vcard, true);
        } catch (e) {
          headless_log.fatal(e);
          this.alert(i18n_('Sorry, something went wrong while trying to refresh'), 'danger');
        }

        converse_chatview_u.removeClass('fa-spin', refresh_icon);
      },

      removeContact(ev) {
        if (ev && ev.preventDefault) {
          ev.preventDefault();
        }

        if (!converse_core_api.settings.get('allow_contact_removal')) {
          return;
        }

        const result = confirm(i18n_("Are you sure you want to remove this contact?"));

        if (result === true) {
          this.modal.hide(); // XXX: This is annoying but necessary to get tests to pass.
          // The `dismissHandler` in bootstrap.native tries to
          // reference the remove button after it's been cleared from
          // the DOM, so we delay removing the contact to give it time.

          setTimeout(() => {
            this.model.contact.removeFromRoster(() => this.model.contact.destroy(), err => {
              headless_log.error(err);
              converse_core_api.alert('error', i18n_('Error'), [i18n_('Sorry, there was an error while trying to remove %1$s as a contact.', this.model.contact.getDisplayName())]);
            });
          }, 1);
        }
      }

    });
    converse_core_api.listen.on('chatBoxViewsInitialized', () => {
      const views = converse_core_converse.chatboxviews;

      converse_core_converse.chatboxes.on('add', async item => {
        if (!views.get(item.get('id')) && item.get('type') === converse_core_converse.PRIVATE_CHAT_TYPE) {
          await item.initialized;
          views.add(item.get('id'), new converse_core_converse.ChatBoxView({
            model: item
          }));
        }
      });
    });
    /************************ BEGIN Event Handlers ************************/

    function onWindowStateChanged(data) {
      if (converse_core_converse.chatboxviews) {
        converse_core_converse.chatboxviews.forEach(view => {
          if (view.model.get('id') !== 'controlbox') {
            view.onWindowStateChanged(data.state);
          }
        });
      }
    }

    converse_core_api.listen.on('windowStateChanged', onWindowStateChanged);
    converse_core_api.listen.on('connected', () => converse_core_api.disco.own.features.add(converse_chatview_Strophe.NS.SPOILER));
    /************************ END Event Handlers ************************/

    /************************ BEGIN API ************************/

    Object.assign(converse_core_api, {
      /**
       * The "chatview" namespace groups methods pertaining to views
       * for one-on-one chats.
       *
       * @namespace _converse.api.chatviews
       * @memberOf _converse.api
       */
      chatviews: {
        /**
         * Get the view of an already open chat.
         * @method _converse.api.chatviews.get
         * @param { Array.string | string } jids
         * @returns { _converse.ChatBoxView|undefined }  The chat should already be open, otherwise `undefined` will be returned.
         * @example
         * // To return a single view, provide the JID of the contact:
         * _converse.api.chatviews.get('buddy@example.com')
         * @example
         * // To return an array of views, provide an array of JIDs:
         * _converse.api.chatviews.get(['buddy1@example.com', 'buddy2@example.com'])
         */
        get(jids) {
          if (jids === undefined) {
            return Object.values(converse_core_converse.chatboxviews.getAll());
          }

          if (typeof jids === 'string') {
            return converse_core_converse.chatboxviews.get(jids);
          }

          return jids.map(jid => converse_core_converse.chatboxviews.get(jid));
        }

      }
    });
    /************************ END API ************************/
  }

});
// CONCATENATED MODULE: ./node_modules/haunted/lib/interface.js
let interface_current;
let currentId = 0;

function setCurrent(state) {
  interface_current = state;
}

function interface_clear() {
  interface_current = null;
  currentId = 0;
}

function notify() {
  return currentId++;
}


// CONCATENATED MODULE: ./node_modules/haunted/lib/symbols.js
const phaseSymbol = Symbol('haunted.phase');
const hookSymbol = Symbol('haunted.hook');
const updateSymbol = Symbol('haunted.update');
const commitSymbol = Symbol('haunted.commit');
const effectsSymbol = Symbol('haunted.effects');
const layoutEffectsSymbol = Symbol('haunted.layoutEffects');
const contextEvent = 'haunted.context';

// CONCATENATED MODULE: ./node_modules/haunted/lib/state.js



class state_State {
  constructor(update, host) {
    this.update = update;
    this.host = host;
    this[hookSymbol] = new Map();
    this[effectsSymbol] = [];
    this[layoutEffectsSymbol] = [];
  }

  run(cb) {
    setCurrent(this);
    let res = cb();
    interface_clear();
    return res;
  }

  _runEffects(phase) {
    let effects = this[phase];
    setCurrent(this);

    for (let effect of effects) {
      effect.call(this);
    }

    interface_clear();
  }

  runEffects() {
    this._runEffects(effectsSymbol);
  }

  runLayoutEffects() {
    this._runEffects(layoutEffectsSymbol);
  }

  teardown() {
    let hooks = this[hookSymbol];
    hooks.forEach(hook => {
      if (typeof hook.teardown === 'function') {
        hook.teardown();
      }
    });
  }

}


// CONCATENATED MODULE: ./node_modules/haunted/lib/scheduler.js


const scheduler_defer = Promise.resolve().then.bind(Promise.resolve());

function runner() {
  let tasks = [];
  let id;

  function runTasks() {
    id = null;
    let t = tasks;
    tasks = [];

    for (var i = 0, len = t.length; i < len; i++) {
      t[i]();
    }
  }

  return function (task) {
    tasks.push(task);

    if (id == null) {
      id = scheduler_defer(runTasks);
    }
  };
}

const read = runner();
const write = runner();

class scheduler_BaseScheduler {
  constructor(renderer, host) {
    this.renderer = renderer;
    this.host = host;
    this.state = new state_State(this.update.bind(this), host);
    this[phaseSymbol] = null;
    this._updateQueued = false;
  }

  update() {
    if (this._updateQueued) return;
    read(() => {
      let result = this.handlePhase(updateSymbol);
      write(() => {
        this.handlePhase(commitSymbol, result);
        write(() => {
          this.handlePhase(effectsSymbol);
        });
      });
      this._updateQueued = false;
    });
    this._updateQueued = true;
  }

  handlePhase(phase, arg) {
    this[phaseSymbol] = phase;

    switch (phase) {
      case commitSymbol:
        this.commit(arg);
        this.runEffects(layoutEffectsSymbol);
        return;

      case updateSymbol:
        return this.render();

      case effectsSymbol:
        return this.runEffects(effectsSymbol);
    }

    this[phaseSymbol] = null;
  }

  render() {
    return this.state.run(() => this.renderer.call(this.host, this.host));
  }

  runEffects(phase) {
    this.state._runEffects(phase);
  }

  teardown() {
    this.state.teardown();
  }

}


// CONCATENATED MODULE: ./node_modules/haunted/lib/component.js


const toCamelCase = (val = '') => val.replace(/-+([a-z])?/g, (_, char) => char ? char.toUpperCase() : '');

function makeComponent(render) {
  class Scheduler extends scheduler_BaseScheduler {
    constructor(renderer, frag, host) {
      super(renderer, host || frag);
      this.frag = frag;
    }

    commit(result) {
      render(result, this.frag);
    }

  }

  function component(renderer, baseElementOrOptions, options) {
    const BaseElement = (options || baseElementOrOptions || {}).baseElement || HTMLElement;
    const {
      observedAttributes = [],
      useShadowDOM = true,
      shadowRootInit = {}
    } = options || baseElementOrOptions || {};

    class Element extends BaseElement {
      constructor() {
        super();

        if (useShadowDOM === false) {
          this._scheduler = new Scheduler(renderer, this);
        } else {
          this.attachShadow({
            mode: 'open',
            ...shadowRootInit
          });
          this._scheduler = new Scheduler(renderer, this.shadowRoot, this);
        }
      }

      static get observedAttributes() {
        return renderer.observedAttributes || observedAttributes || [];
      }

      connectedCallback() {
        this._scheduler.update();
      }

      disconnectedCallback() {
        this._scheduler.teardown();
      }

      attributeChangedCallback(name, oldValue, newValue) {
        if (oldValue === newValue) {
          return;
        }

        let val = newValue === '' ? true : newValue;
        Reflect.set(this, toCamelCase(name), val);
      }

    }

    ;

    function reflectiveProp(initialValue) {
      let value = initialValue;
      return Object.freeze({
        enumerable: true,
        configurable: true,

        get() {
          return value;
        },

        set(newValue) {
          value = newValue;

          this._scheduler.update();
        }

      });
    }

    const proto = new Proxy(BaseElement.prototype, {
      getPrototypeOf(target) {
        return target;
      },

      set(target, key, value, receiver) {
        let desc;

        if (key in target) {
          desc = Object.getOwnPropertyDescriptor(target, key);

          if (desc && desc.set) {
            desc.set.call(receiver, value);
            return true;
          }

          Reflect.set(target, key, value, receiver);
          return true;
        }

        if (typeof key === 'symbol' || key[0] === '_') {
          desc = {
            enumerable: true,
            configurable: true,
            writable: true,
            value
          };
        } else {
          desc = reflectiveProp(value);
        }

        Object.defineProperty(receiver, key, desc);

        if (desc.set) {
          desc.set.call(receiver, value);
        }

        return true;
      }

    });
    Object.setPrototypeOf(Element.prototype, proto);
    return Element;
  }

  return component;
}


// CONCATENATED MODULE: ./node_modules/haunted/lib/hook.js



class hook_Hook {
  constructor(id, state) {
    this.id = id;
    this.state = state;
  }

}

function use(Hook, ...args) {
  let id = notify();
  let hooks = interface_current[hookSymbol];
  let hook = hooks.get(id);

  if (!hook) {
    hook = new Hook(id, interface_current, ...args);
    hooks.set(id, hook);
  }

  return hook.update(...args);
}

function hook_hook(Hook) {
  return use.bind(null, Hook);
}


// CONCATENATED MODULE: ./node_modules/haunted/lib/create-effect.js


function createEffect(setEffects) {
  return hook_hook(class extends hook_Hook {
    constructor(id, state, ignored1, ignored2) {
      super(id, state);
      setEffects(state, this);
    }

    update(callback, values) {
      this.callback = callback;
      this.values = values;
    }

    call() {
      if (!this.values || this.hasChanged()) {
        this.run();
      }

      this.lastValues = this.values;
    }

    run() {
      this.teardown();
      this._teardown = this.callback.call(this.state);
    }

    teardown() {
      if (typeof this._teardown === 'function') {
        this._teardown();
      }
    }

    hasChanged() {
      return !this.lastValues || this.values.some((value, i) => this.lastValues[i] !== value);
    }

  });
}


// CONCATENATED MODULE: ./node_modules/haunted/lib/use-effect.js



function use_effect_setEffects(state, cb) {
  state[effectsSymbol].push(cb);
}

const useEffect = createEffect(use_effect_setEffects);

// CONCATENATED MODULE: ./node_modules/haunted/lib/use-context.js



const useContext = hook_hook(class extends hook_Hook {
  constructor(id, state, _) {
    super(id, state);
    this._updater = this._updater.bind(this);
    this._ranEffect = false;
    this._unsubscribe = null;
    use_effect_setEffects(state, this);
  }

  update(Context) {
    if (this.state.virtual) {
      throw new Error('can\'t be used with virtual components');
    }

    if (this.Context !== Context) {
      this._subscribe(Context);

      this.Context = Context;
    }

    return this.value;
  }

  call() {
    if (!this._ranEffect) {
      this._ranEffect = true;
      if (this._unsubscribe) this._unsubscribe();

      this._subscribe(this.Context);

      this.state.update();
    }
  }

  _updater(value) {
    this.value = value;
    this.state.update();
  }

  _subscribe(Context) {
    const detail = {
      Context,
      callback: this._updater
    };
    this.state.host.dispatchEvent(new CustomEvent(contextEvent, {
      detail,
      bubbles: true,
      cancelable: true,
      composed: true
    }));
    const {
      unsubscribe,
      value
    } = detail;
    this.value = unsubscribe ? value : Context.defaultValue;
    this._unsubscribe = unsubscribe;
  }

  teardown() {
    if (this._unsubscribe) {
      this._unsubscribe();
    }
  }

});

// CONCATENATED MODULE: ./node_modules/haunted/lib/create-context.js



function makeContext(component) {
  return defaultValue => {
    const Context = {
      Provider: class extends HTMLElement {
        constructor() {
          super();
          this.listeners = new Set();
          this.addEventListener(contextEvent, this);
        }

        disconnectedCallback() {
          this.removeEventListener(contextEvent, this);
        }

        handleEvent(event) {
          const {
            detail
          } = event;

          if (detail.Context === Context) {
            detail.value = this.value;
            detail.unsubscribe = this.unsubscribe.bind(this, detail.callback);
            this.listeners.add(detail.callback);
            event.stopPropagation();
          }
        }

        unsubscribe(callback) {
          this.listeners.delete(callback);
        }

        set value(value) {
          this._value = value;

          for (let callback of this.listeners) {
            callback(value);
          }
        }

        get value() {
          return this._value;
        }

      },
      Consumer: component(function ({
        render
      }) {
        const context = useContext(Context);
        return render(context);
      }),
      defaultValue
    };
    return Context;
  };
}


// CONCATENATED MODULE: ./node_modules/haunted/lib/use-memo.js

const useMemo = hook_hook(class extends hook_Hook {
  constructor(id, state, fn, values) {
    super(id, state);
    this.value = fn();
    this.values = values;
  }

  update(fn, values) {
    if (this.hasChanged(values)) {
      this.values = values;
      this.value = fn();
    }

    return this.value;
  }

  hasChanged(values = []) {
    return values.some((value, i) => this.values[i] !== value);
  }

});

// CONCATENATED MODULE: ./node_modules/haunted/lib/use-callback.js


const useCallback = (fn, inputs) => useMemo(() => fn, inputs);


// CONCATENATED MODULE: ./node_modules/haunted/lib/use-layout-effect.js



function setLayoutEffects(state, cb) {
  state[layoutEffectsSymbol].push(cb);
}

const useLayoutEffect = createEffect(setLayoutEffects);

// CONCATENATED MODULE: ./node_modules/haunted/lib/use-state.js

const useState = hook_hook(class extends hook_Hook {
  constructor(id, state, initialValue) {
    super(id, state);
    this.updater = this.updater.bind(this);

    if (typeof initialValue === 'function') {
      initialValue = initialValue();
    }

    this.makeArgs(initialValue);
  }

  update() {
    return this.args;
  }

  updater(value) {
    if (typeof value === 'function') {
      const updaterFn = value;
      const [previousValue] = this.args;
      value = updaterFn(previousValue);
    }

    this.makeArgs(value);
    this.state.update();
  }

  makeArgs(value) {
    this.args = Object.freeze([value, this.updater]);
  }

});

// CONCATENATED MODULE: ./node_modules/haunted/lib/use-reducer.js

const useReducer = hook_hook(class extends hook_Hook {
  constructor(id, state, _, initialState, init) {
    super(id, state);
    this.dispatch = this.dispatch.bind(this);
    this.currentState = init !== undefined ? init(initialState) : initialState;
  }

  update(reducer) {
    this.reducer = reducer;
    return [this.currentState, this.dispatch];
  }

  dispatch(action) {
    this.currentState = this.reducer(this.currentState, action);
    this.state.update();
  }

});

// CONCATENATED MODULE: ./node_modules/haunted/lib/use-ref.js


const useRef = initialValue => useMemo(() => ({
  current: initialValue
}), []);


// CONCATENATED MODULE: ./node_modules/haunted/lib/core.js



function haunted({
  render
}) {
  const component = makeComponent(render);
  const createContext = makeContext(component);
  return {
    component,
    createContext
  };
}













// CONCATENATED MODULE: ./node_modules/haunted/lib/virtual.js


const virtual_includes = Array.prototype.includes;

function makeVirtual() {
  const partToScheduler = new WeakMap();
  const schedulerToPart = new WeakMap();

  class Scheduler extends scheduler_BaseScheduler {
    constructor(renderer, part) {
      super(renderer, part);
      this.state.virtual = true;
    }

    render() {
      return this.state.run(() => this.renderer.apply(this.host, this.args));
    }

    commit(result) {
      this.host.setValue(result);
      this.host.commit();
    }

    teardown() {
      super.teardown();
      let part = schedulerToPart.get(this);
      partToScheduler.delete(part);
    }

  }

  function virtual(renderer) {
    function factory(...args) {
      return part => {
        let cont = partToScheduler.get(part);

        if (!cont) {
          cont = new Scheduler(renderer, part);
          partToScheduler.set(part, cont);
          schedulerToPart.set(cont, part);
          teardownOnRemove(cont, part);
        }

        cont.args = args;
        cont.update();
      };
    }

    return directive_directive(factory);
  }

  return virtual;
}

function teardownOnRemove(cont, part, node = part.startNode) {
  let frag = node.parentNode;
  let mo = new MutationObserver(mutations => {
    for (let mutation of mutations) {
      if (virtual_includes.call(mutation.removedNodes, node)) {
        mo.disconnect();

        if (node.parentNode instanceof ShadowRoot) {
          teardownOnRemove(cont, part);
        } else {
          cont.teardown();
        }

        break;
      } else if (virtual_includes.call(mutation.addedNodes, node.nextSibling)) {
        mo.disconnect();
        teardownOnRemove(cont, part, node.nextSibling || undefined);
        break;
      }
    }
  });
  mo.observe(frag, {
    childList: true
  });
}


// CONCATENATED MODULE: ./node_modules/haunted/lib/lit-haunted.js



const {
  component: lit_haunted_component,
  createContext: lit_haunted_createContext
} = haunted({
  render: render_render
});
const lit_haunted_virtual = makeVirtual();

// CONCATENATED MODULE: ./node_modules/haunted/lib/haunted.js



// CONCATENATED MODULE: ./src/components/brand-heading.js



const ConverseBrandHeading = o => {
  const is_fullscreen = converse_core_api.settings.get('view_mode') === 'fullscreen';
  return lit_html_html`
        <a class="brand-heading" href="https://conversejs.org" target="_blank" rel="noopener">
            <span class="brand-name-wrapper ${is_fullscreen ? 'brand-name-wrapper--fullscreen' : ''}">
                <svg class="converse-svg-logo"
                    xmlns:svg="http://www.w3.org/2000/svg"
                    xmlns="http://www.w3.org/2000/svg"
                    xmlns:xlink="http://www.w3.org/1999/xlink"
                    viewBox="0 0 364 364">
                    <title>Converse</title>
                    <g class="cls-1" id="g904">
                        <g data-name="Layer 2">
                            <g data-name="Layer 7">
                                <path
                                    class="cls-3"
                                    d="M221.46,103.71c0,18.83-29.36,18.83-29.12,0C192.1,84.88,221.46,84.88,221.46,103.71Z" />
                                <path
                                    class="cls-4"
                                    d="M179.9,4.15A175.48,175.48,0,1,0,355.38,179.63,175.48,175.48,0,0,0,179.9,4.15Zm-40.79,264.5c-.23-17.82,27.58-17.82,27.58,0S138.88,286.48,139.11,268.65ZM218.6,168.24A79.65,79.65,0,0,1,205.15,174a12.76,12.76,0,0,0-6.29,4.65L167.54,222a1.36,1.36,0,0,1-2.46-.8v-35.8a2.58,2.58,0,0,0-3.06-2.53c-15.43,3-30.23,7.7-42.73,19.94-38.8,38-29.42,105.69,16.09,133.16a162.25,162.25,0,0,1-91.47-67.27C-3.86,182.26,34.5,47.25,138.37,25.66c46.89-9.75,118.25,5.16,123.73,62.83C265.15,120.64,246.56,152.89,218.6,168.24Z" />
                            </g>
                        </g>
                    </g>
                </svg>
                <span class="brand-name">
                    <span class="brand-name__text">converse<span class="subdued">.js</span></span>
                    ${is_fullscreen ? lit_html_html`<p class="byline">messaging freedom</p>` : ''}
                </span>
            </span>
        </a>
        ${is_fullscreen ? lit_html_html`
            <p class="brand-subtitle">${o.version_name}</p>
            <p class="brand-subtitle"><a target="_blank" rel="nofollow" href="https://conversejs.org">Open Source</a> XMPP chat client brought to you by <a target="_blank" rel="nofollow" href="https://opkode.com">Opkode</a> </p>
            <p class="brand-subtitle"><a target="_blank" rel="nofollow" href="https://hosted.weblate.org/projects/conversejs/#languages">Translate</a> it into your own language</p>` : ''}
        `;
};
converse_core_api.elements.define('converse-brand-heading', lit_haunted_component(ConverseBrandHeading, {
  'useShadowDOM': false
}));
// CONCATENATED MODULE: ./src/templates/controlbox.js

/* harmony default export */ var templates_controlbox = (o => lit_html_html`
    <div class="flyout box-flyout">
        <div class="chat-head controlbox-head">
            ${o.sticky_controlbox ? '' : lit_html_html`<a class="chatbox-btn close-chatbox-button fa fa-times"></a>`}
        </div>
        <div class="controlbox-panes"></div>
    </div>`);
// EXTERNAL MODULE: ./src/templates/controlbox_toggle.html
var controlbox_toggle = __webpack_require__(172);
var controlbox_toggle_default = /*#__PURE__*/__webpack_require__.n(controlbox_toggle);

// CONCATENATED MODULE: ./src/templates/login_panel.js





const trust_checkbox = checked => {
  const i18n_hint_trusted = i18n_('To improve performance, we cache your data in this browser. ' + 'Uncheck this box if this is a public computer or if you want your data to be deleted when you log out. ' + 'It\'s important that you explicitly log out, otherwise not all cached data might be deleted. ' + 'Please note, when using an untrusted device, OMEMO encryption is NOT available.');

  const i18n_trusted = i18n_('This is a trusted device');

  return lit_html_html`
        <div class="form-group form-check login-trusted">
            <input id="converse-login-trusted" type="checkbox" class="form-check-input" name="trusted" ?checked=${checked}>
            <label for="converse-login-trusted" class="form-check-label login-trusted__desc">${i18n_trusted}</label>
            <i class="fa fa-info-circle" data-toggle="popover"
                data-title="Trusted device?"
                data-content="${i18n_hint_trusted}"></i>
        </div>
    `;
};

const password_input = () => {
  const i18n_password = i18n_('Password');

  return lit_html_html`
        <div class="form-group">
            <label for="converse-login-password">${i18n_password}</label>
            <input id="converse-login-password" class="form-control" required="required" type="password" name="password" placeholder="${i18n_password}"/>
        </div>
    `;
};

const register_link = () => {
  const i18n_create_account = i18n_("Create an account");

  const i18n_hint_no_account = i18n_("Don't have a chat account?");

  return lit_html_html`
        <fieldset class="switch-form">
            <p>${i18n_hint_no_account}</p>
            <p><a class="register-account toggle-register-login" href="#converse/register">${i18n_create_account}</a></p>
        </fieldset>
    `;
};

const show_register_link = () => {
  return converse_core_converse.allow_registration && !converse_core_api.settings.get("auto_login") && converse_core_converse.pluggable.plugins['converse-register'].enabled(converse_core_converse);
};

const auth_fields = o => {
  const i18n_login = i18n_('Log in');

  const i18n_xmpp_address = i18n_("XMPP Address");

  return lit_html_html`
        <div class="form-group">
            <label for="converse-login-jid">${i18n_xmpp_address}:</label>
            <input id="converse-login-jid"
                ?autofocus=${converse_core_api.settings.get('auto_focus') ? true : false}
                required
                class="form-control"
                type="text"
                name="jid"
                placeholder="${o.placeholder_username}"/>
        </div>
        ${o.authentication !== o.EXTERNAL ? password_input() : ''}
        ${o.show_trust_checkbox ? trust_checkbox(o.show_trust_checkbox === 'off' ? false : true) : ''}
        <fieldset class="buttons">
            <input class="btn btn-primary" type="submit" value="${i18n_login}"/>
        </fieldset>
        ${show_register_link() ? register_link(o) : ''}
    `;
};

const form_fields = o => {
  const i18n_disconnected = i18n_('Disconnected');

  const i18n_anon_login = i18n_('Click here to log in anonymously');

  return lit_html_html`
        ${o.authentication == o.LOGIN || o.authentication == o.EXTERNAL ? auth_fields(o) : ''}
        ${o.authentication == o.ANONYMOUS ? lit_html_html`<input class="btn btn-primary login-anon" type="submit" value="${i18n_anon_login}">` : ''}
        ${o.authentication == o.PREBIND ? lit_html_html`<p>${i18n_disconnected}</p>` : ''}
    `;
};

/* harmony default export */ var templates_login_panel = (o => lit_html_html`
    <converse-brand-heading></converse-brand-heading>
    <form id="converse-login" class="converse-form" method="post">
        <div class="conn-feedback fade-in ${!o.conn_feedback_subject ? 'hidden' : o.conn_feedback_class}">
            <p class="feedback-subject">${o.conn_feedback_subject}</p>
            <p class="feedback-message ${!o.conn_feedback_message ? 'hidden' : ''}">${o.conn_feedback_message}</p>
        </div>
        ${converse_core_converse.CONNECTION_STATUS[o.connection_status] === 'CONNECTING' ? spinner({
  'classes': 'hor_centered'
}) : form_fields(o)}
    </form>
`);
// CONCATENATED MODULE: ./src/converse-controlbox.js
/**
 * @module converse-controlbox
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */












const {
  Strophe: converse_controlbox_Strophe,
  dayjs: converse_controlbox_dayjs
} = converse.env;
const converse_controlbox_u = converse.env.utils;
const CONNECTION_STATUS_CSS_CLASS = {
  'Error': 'error',
  'Connecting': 'info',
  'Connection failure': 'error',
  'Authenticating': 'info',
  'Authentication failure': 'error',
  'Connected': 'info',
  'Disconnected': 'error',
  'Disconnecting': 'warn',
  'Attached': 'info',
  'Redirect': 'info',
  'Reconnecting': 'warn'
};
const PRETTY_CONNECTION_STATUS = {
  0: 'Error',
  1: 'Connecting',
  2: 'Connection failure',
  3: 'Authenticating',
  4: 'Authentication failure',
  5: 'Connected',
  6: 'Disconnected',
  7: 'Disconnecting',
  8: 'Attached',
  9: 'Redirect',
  10: 'Reconnecting'
};
const REPORTABLE_STATUSES = [0, // ERROR'
1, // CONNECTING
2, // CONNFAIL
3, // AUTHENTICATING
4, // AUTHFAIL
7, // DISCONNECTING
10 // RECONNECTING
];
converse.plugins.add('converse-controlbox', {
  /* Plugin dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin.
   *
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found. By default it's
   * false, which means these plugins are only loaded opportunistically.
   *
   * NB: These plugins need to have already been loaded via require.js.
   */
  dependencies: ["converse-modal", "converse-chatboxes", "converse-chat", "converse-rosterview", "converse-chatview"],

  enabled(_converse) {
    return !_converse.api.settings.get("singleton");
  },

  overrides: {
    // Overrides mentioned here will be picked up by converse.js's
    // plugin architecture they will replace existing methods on the
    // relevant objects or classes.
    //
    // New functions which don't exist yet can also be added.
    ChatBoxes: {
      model(attrs, options) {
        const {
          _converse
        } = this.__super__;

        if (attrs && attrs.id == 'controlbox') {
          return new _converse.ControlBox(attrs, options);
        } else {
          return this.__super__.model.apply(this, arguments);
        }
      }

    }
  },

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    converse_core_api.settings.extend({
      allow_logout: true,
      allow_user_trust_override: true,
      default_domain: undefined,
      locked_domain: undefined,
      show_controlbox_by_default: false,
      sticky_controlbox: false
    });
    converse_core_api.promises.add('controlBoxInitialized');
    converse_core_converse.ControlBox = converse_core_converse.ChatBox.extend({
      defaults() {
        return {
          'bookmarked': false,
          'box_id': 'controlbox',
          'chat_state': undefined,
          'closed': !converse_core_api.settings.get('show_controlbox_by_default'),
          'num_unread': 0,
          'time_opened': this.get('time_opened') || new Date().getTime(),
          'type': converse_core_converse.CONTROLBOX_TYPE,
          'url': ''
        };
      },

      initialize() {
        if (this.get('id') === 'controlbox') {
          this.set({
            'time_opened': converse_controlbox_dayjs(0).valueOf()
          });
        } else {
          converse_core_converse.ChatBox.prototype.initialize.apply(this, arguments);
        }
      },

      validate(attrs) {
        if (attrs.type === converse_core_converse.CONTROLBOX_TYPE) {
          if (converse_core_api.settings.get("view_mode") === 'embedded' && converse_core_api.settings.get("singleton")) {
            return 'Controlbox not relevant in embedded view mode';
          }

          return;
        }

        return converse_core_converse.ChatBox.prototype.validate.call(this, attrs);
      },

      maybeShow(force) {
        if (!force && this.get('id') === 'controlbox') {
          // Must return the chatbox
          return this;
        }

        return converse_core_converse.ChatBox.prototype.maybeShow.call(this, force);
      },

      onReconnection: function onReconnection() {}
    });

    function addControlBox() {
      const m = new converse_core_converse.ControlBox({
        'id': 'controlbox'
      });
      return converse_core_converse.chatboxes.add(m);
    }

    converse_core_converse.ControlBoxView = converse_core_converse.ChatBoxView.extend({
      tagName: 'div',
      className: 'chatbox',
      id: 'controlbox',
      events: {
        'click a.close-chatbox-button': 'close'
      },

      initialize() {
        if (converse_core_converse.controlboxtoggle === undefined) {
          converse_core_converse.controlboxtoggle = new converse_core_converse.ControlBoxToggle();
        }

        converse_core_converse.controlboxtoggle.el.insertAdjacentElement('afterend', this.el);

        this.listenTo(this.model, 'change:connected', this.onConnected);
        this.listenTo(this.model, 'destroy', this.hide);
        this.listenTo(this.model, 'hide', this.hide);
        this.listenTo(this.model, 'show', this.show);
        this.listenTo(this.model, 'change:closed', this.ensureClosedState);
        this.render();
        /**
         * Triggered when the _converse.ControlBoxView has been initialized and therefore
         * exists. The controlbox contains the login and register forms when the user is
         * logged out and a list of the user's contacts and group chats when logged in.
         * @event _converse#controlBoxInitialized
         * @type { _converse.ControlBoxView }
         * @example _converse.api.listen.on('controlBoxInitialized', view => { ... });
         */

        converse_core_api.trigger('controlBoxInitialized', this);
      },

      render() {
        if (this.model.get('connected')) {
          if (this.model.get('closed') === undefined) {
            this.model.set('closed', !converse_core_api.settings.get('show_controlbox_by_default'));
          }
        }

        const tpl_result = templates_controlbox({
          'sticky_controlbox': converse_core_api.settings.get('sticky_controlbox'),
          ...this.model.toJSON()
        });
        render_render(tpl_result, this.el);

        if (!this.model.get('closed')) {
          this.show();
        } else {
          this.hide();
        }

        const connection = (converse_core_converse === null || converse_core_converse === void 0 ? void 0 : converse_core_converse.connection) || {};

        if (!connection.connected || !connection.authenticated || connection.disconnecting) {
          this.renderLoginPanel();
        } else if (this.model.get('connected')) {
          this.renderControlBoxPane();
        }

        return this;
      },

      onConnected() {
        if (this.model.get('connected')) {
          this.render();
        }
      },

      renderLoginPanel() {
        this.el.classList.add("logged-out");

        if (this.loginpanel) {
          this.loginpanel.render();
        } else {
          this.loginpanel = new converse_core_converse.LoginPanel({
            'model': new converse_core_converse.LoginPanelModel()
          });
          const panes = this.el.querySelector('.controlbox-panes');
          panes.innerHTML = '';
          panes.appendChild(this.loginpanel.render().el);
        }

        this.loginpanel.initPopovers();
        return this;
      },

      /**
       * Renders the "Contacts" panel of the controlbox.
       * This will only be called after the user has already been logged in.
       * @private
       * @method _converse.ControlBoxView.renderControlBoxPane
       */
      renderControlBoxPane() {
        if (this.loginpanel) {
          this.loginpanel.remove();
          delete this.loginpanel;
        }

        if (this.controlbox_pane && converse_controlbox_u.isVisible(this.controlbox_pane.el)) {
          return;
        }

        this.el.classList.remove("logged-out");
        this.controlbox_pane = new converse_core_converse.ControlBoxPane();
        this.el.querySelector('.controlbox-panes').insertAdjacentElement('afterBegin', this.controlbox_pane.el);
      },

      async close(ev) {
        if (ev && ev.preventDefault) {
          ev.preventDefault();
        }

        if ((ev === null || ev === void 0 ? void 0 : ev.name) === 'closeAllChatBoxes' && (converse_core_converse.disconnection_cause !== converse_core_converse.LOGOUT || converse_core_api.settings.get('show_controlbox_by_default'))) {
          return;
        }

        if (converse_core_api.settings.get('sticky_controlbox')) {
          return;
        }

        const connection = (converse_core_converse === null || converse_core_converse === void 0 ? void 0 : converse_core_converse.connection) || {};

        if (connection.connected && !connection.disconnecting) {
          await new Promise((resolve, reject) => {
            return this.model.save({
              'closed': true
            }, {
              'success': resolve,
              'error': reject,
              'wait': true
            });
          });
        } else {
          this.model.trigger('hide');
        }

        converse_core_api.trigger('controlBoxClosed', this);
        return this;
      },

      ensureClosedState() {
        if (this.model.get('closed')) {
          this.hide();
        } else {
          this.show();
        }
      },

      hide(callback) {
        if (converse_core_api.settings.get('sticky_controlbox')) {
          return;
        }

        converse_controlbox_u.addClass('hidden', this.el);
        converse_core_api.trigger('chatBoxClosed', this);

        if (!converse_core_api.connection.connected()) {
          converse_core_converse.controlboxtoggle.render();
        }

        converse_core_converse.controlboxtoggle.show(callback);

        return this;
      },

      onControlBoxToggleHidden() {
        this.model.set('closed', false);
        this.el.classList.remove('hidden');
        /**
         * Triggered once the controlbox has been opened
         * @event _converse#controlBoxOpened
         * @type {_converse.ControlBox}
         */

        converse_core_api.trigger('controlBoxOpened', this);
      },

      show() {
        converse_core_converse.controlboxtoggle.hide(() => this.onControlBoxToggleHidden());

        return this;
      },

      showHelpMessages() {
        return;
      }

    });
    converse_core_converse.LoginPanelModel = model_Model.extend({
      defaults: {
        // Passed-by-reference. Fine in this case because there's
        // only one such model.
        'errors': []
      }
    });
    converse_core_converse.LoginPanel = View.extend({
      tagName: 'div',
      id: "converse-login-panel",
      className: 'controlbox-pane fade-in row no-gutters',
      events: {
        'submit form#converse-login': 'authenticate',
        'change input': 'validate'
      },

      initialize() {
        this.listenTo(this.model, 'change', this.render);
        this.listenTo(converse_core_converse.connfeedback, 'change', this.render);
        this.render();
      },

      toHTML() {
        const connection_status = converse_core_converse.connfeedback.get('connection_status');

        let feedback_class, pretty_status;

        if (REPORTABLE_STATUSES.includes(connection_status)) {
          pretty_status = PRETTY_CONNECTION_STATUS[connection_status];
          feedback_class = CONNECTION_STATUS_CSS_CLASS[pretty_status];
        }

        return templates_login_panel(Object.assign(this.model.toJSON(), {
          '_converse': converse_core_converse,
          'ANONYMOUS': converse_core_converse.ANONYMOUS,
          'EXTERNAL': converse_core_converse.EXTERNAL,
          'LOGIN': converse_core_converse.LOGIN,
          'PREBIND': converse_core_converse.PREBIND,
          'auto_login': converse_core_api.settings.get('auto_login'),
          'authentication': converse_core_api.settings.get("authentication"),
          'connection_status': connection_status,
          'conn_feedback_class': feedback_class,
          'conn_feedback_subject': pretty_status,
          'conn_feedback_message': converse_core_converse.connfeedback.get('message'),
          'placeholder_username': (converse_core_api.settings.get('locked_domain') || converse_core_api.settings.get('default_domain')) && i18n_('Username') || i18n_('user@domain'),
          'show_trust_checkbox': converse_core_api.settings.get('allow_user_trust_override')
        }));
      },

      initPopovers() {
        Array.from(this.el.querySelectorAll('[data-title]')).forEach(el => {
          new bootstrap_native_default.a.Popover(el, {
            'trigger': converse_core_api.settings.get("view_mode") === 'mobile' && 'click' || 'hover',
            'dismissible': converse_core_api.settings.get("view_mode") === 'mobile' && true || false,
            'container': this.el.parentElement.parentElement.parentElement
          });
        });
      },

      validate() {
        const form = this.el.querySelector('form');
        const jid_element = form.querySelector('input[name=jid]');

        if (jid_element.value && !converse_core_api.settings.get('locked_domain') && !converse_core_api.settings.get('default_domain') && !converse_controlbox_u.isValidJID(jid_element.value)) {
          jid_element.setCustomValidity(i18n_('Please enter a valid XMPP address'));
          return false;
        }

        jid_element.setCustomValidity('');
        return true;
      },

      /**
       * Authenticate the user based on a form submission event.
       * @param { Event } ev
       */
      authenticate(ev) {
        if (ev && ev.preventDefault) {
          ev.preventDefault();
        }

        if (converse_core_api.settings.get("authentication") === converse_core_converse.ANONYMOUS) {
          return this.connect(converse_core_converse.jid, null);
        }

        if (!this.validate()) {
          return;
        }

        const form_data = new FormData(ev.target);

        converse_core_converse.config.save({
          'trusted': form_data.get('trusted') && true || false
        });

        let jid = form_data.get('jid');

        if (converse_core_api.settings.get('locked_domain')) {
          const last_part = '@' + converse_core_api.settings.get('locked_domain');

          if (jid.endsWith(last_part)) {
            jid = jid.substr(0, jid.length - last_part.length);
          }

          jid = converse_controlbox_Strophe.escapeNode(jid) + last_part;
        } else if (converse_core_api.settings.get('default_domain') && !jid.includes('@')) {
          jid = jid + '@' + converse_core_api.settings.get('default_domain');
        }

        this.connect(jid, form_data.get('password'));
      },

      connect(jid, password) {
        if (["converse/login", "converse/register"].includes(converse_core_converse.router.history.getFragment())) {
          converse_core_converse.router.navigate('', {
            'replace': true
          });
        }

        converse_core_converse.connection && converse_core_converse.connection.reset();
        converse_core_api.user.login(jid, password);
      }

    });
    converse_core_converse.ControlBoxPane = View.extend({
      tagName: 'div',
      className: 'controlbox-pane',

      initialize() {
        /**
         * Triggered once the {@link _converse.ControlBoxPane} has been initialized
         * @event _converse#controlBoxPaneInitialized
         * @type { _converse.ControlBoxPane }
         * @example _converse.api.listen.on('controlBoxPaneInitialized', view => { ... });
         */
        converse_core_api.trigger('controlBoxPaneInitialized', this);
      }

    });
    converse_core_converse.ControlBoxToggle = View.extend({
      tagName: 'a',
      className: 'toggle-controlbox hidden',
      id: 'toggle-controlbox',
      events: {
        'click': 'onClick'
      },
      attributes: {
        'href': "#"
      },

      initialize() {
        converse_core_converse.chatboxviews.insertRowColumn(this.render().el);

        converse_core_api.waitUntil('initialized').then(this.render.bind(this)).catch(e => headless_log.fatal(e));
      },

      render() {
        // We let the render method of ControlBoxView decide whether
        // the ControlBox or the Toggle must be shown. This prevents
        // artifacts (i.e. on page load the toggle is shown only to then
        // seconds later be hidden in favor of the controlbox).
        this.el.innerHTML = controlbox_toggle_default()({
          'label_toggle': converse_core_api.connection.connected() ? i18n_('Chat Contacts') : i18n_('Toggle chat')
        });
        return this;
      },

      hide(callback) {
        if (converse_controlbox_u.isVisible(this.el)) {
          converse_controlbox_u.hideElement(this.el);
          callback();
        }
      },

      show(callback) {
        if (!converse_controlbox_u.isVisible(this.el)) {
          converse_controlbox_u.fadeIn(this.el, callback);
        }
      },

      showControlBox() {
        let controlbox = converse_core_converse.chatboxes.get('controlbox');

        if (!controlbox) {
          controlbox = addControlBox();
        }

        if (converse_core_api.connection.connected()) {
          controlbox.save({
            'closed': false
          });
        } else {
          controlbox.trigger('show');
        }
      },

      onClick(e) {
        e.preventDefault();

        if (converse_controlbox_u.isVisible(converse_core_converse.root.querySelector("#controlbox"))) {
          const controlbox = converse_core_converse.chatboxes.get('controlbox');

          if (converse_core_api.connection.connected) {
            controlbox.save({
              closed: true
            });
          } else {
            controlbox.trigger('hide');
          }
        } else {
          this.showControlBox();
        }
      }

    });
    /******************** Event Handlers ********************/

    converse_core_api.listen.on('cleanup', () => delete converse_core_converse.controlboxtoggle);
    converse_core_api.listen.on('chatBoxViewsInitialized', () => {
      converse_core_converse.chatboxes.on('add', item => {
        if (item.get('type') === converse_core_converse.CONTROLBOX_TYPE) {
          const views = converse_core_converse.chatboxviews;
          const view = views.get(item.get('id'));

          if (view) {
            view.model = item;
            view.initialize();
          } else {
            views.add(item.get('id'), new converse_core_converse.ControlBoxView({
              model: item
            }));
          }
        }
      });
    });
    converse_core_api.listen.on('clearSession', () => {
      const chatboxviews = converse_core_converse === null || converse_core_converse === void 0 ? void 0 : converse_core_converse.chatboxviews;
      const view = chatboxviews && chatboxviews.get('controlbox');

      if (view) {
        converse_controlbox_u.safeSave(view.model, {
          'connected': false
        });

        if (view !== null && view !== void 0 && view.controlbox_pane) {
          view.controlbox_pane.remove();
          delete view.controlbox_pane;
        }
      }
    });
    converse_core_api.waitUntil('chatBoxViewsInitialized').then(addControlBox).catch(e => headless_log.fatal(e));
    converse_core_api.listen.on('chatBoxesFetched', () => {
      const controlbox = converse_core_converse.chatboxes.get('controlbox') || addControlBox();
      controlbox.save({
        'connected': true
      });
    });

    const disconnect = function () {
      /* Upon disconnection, set connected to `false`, so that if
       * we reconnect, "onConnected" will be called,
       * to fetch the roster again and to send out a presence stanza.
       */
      const view = converse_core_converse.chatboxviews.get('controlbox');

      view.model.set({
        'connected': false
      });
      return view;
    };

    converse_core_api.listen.on('disconnected', () => disconnect().renderLoginPanel());
    converse_core_api.listen.on('will-reconnect', disconnect);
    /************************ API ************************/

    Object.assign(converse_core_api, {
      /**
       * The "controlbox" namespace groups methods pertaining to the
       * controlbox view
       *
       * @namespace _converse.api.controlbox
       * @memberOf _converse.api
       */
      controlbox: {
        /**
         * Opens the controlbox
         * @method _converse.api.controlbox.open
         * @returns { Promise<_converse.ControlBox> }
         */
        async open() {
          await converse_core_api.waitUntil('chatBoxesFetched');
          const model = (await converse_core_api.chatboxes.get('controlbox')) || converse_core_api.chatboxes.create('controlbox', {}, converse_core_converse.Controlbox);
          model.trigger('show');
          return model;
        },

        /**
         * Returns the controlbox view.
         * @method _converse.api.controlbox.get
         * @returns { View } View representing the controlbox
         * @example const view = _converse.api.controlbox.get();
         */
        get() {
          return converse_core_converse.chatboxviews.get('controlbox');
        }

      }
    });
  }

});
// EXTERNAL MODULE: ./src/templates/dragresize.html
var dragresize = __webpack_require__(173);
var dragresize_default = /*#__PURE__*/__webpack_require__.n(dragresize);

// CONCATENATED MODULE: ./src/converse-dragresize.js
/**
 * @module converse-dragresize
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */





const converse_dragresize_u = converse.env.utils;

function renderDragResizeHandles(_converse, view) {
  const flyout = view.el.querySelector('.box-flyout');
  const div = document.createElement('div');
  div.innerHTML = dragresize_default()();
  flyout.insertBefore(div, flyout.firstChild);
}

converse.plugins.add('converse-dragresize', {
  /* Plugin dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin.
   *
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found. By default it's
   * false, which means these plugins are only loaded opportunistically.
   *
   * NB: These plugins need to have already been loaded via require.js.
   */
  dependencies: ["converse-chatview", "converse-headlines-view", "converse-muc-views"],

  enabled(_converse) {
    return _converse.api.settings.get("view_mode") == 'overlayed';
  },

  overrides: {
    // Overrides mentioned here will be picked up by converse.js's
    // plugin architecture they will replace existing methods on the
    // relevant objects or classes.
    ChatBox: {
      initialize() {
        const result = this.__super__.initialize.apply(this, arguments);

        const height = this.get('height'),
              width = this.get('width');
        const save = this.get('id') === 'controlbox' ? a => this.set(a) : a => this.save(a);
        save({
          'height': converse_dragresize_u.applyDragResistance(height, this.get('default_height')),
          'width': converse_dragresize_u.applyDragResistance(width, this.get('default_width'))
        });
        return result;
      }

    },
    ChatBoxView: {
      events: {
        'mousedown .dragresize-top': 'onStartVerticalResize',
        'mousedown .dragresize-left': 'onStartHorizontalResize',
        'mousedown .dragresize-topleft': 'onStartDiagonalResize'
      },

      render() {
        const result = this.__super__.render.apply(this, arguments);

        renderDragResizeHandles(this.__super__._converse, this);
        this.setWidth();
        return result;
      }

    },
    HeadlinesBoxView: {
      events: {
        'mousedown .dragresize-top': 'onStartVerticalResize',
        'mousedown .dragresize-left': 'onStartHorizontalResize',
        'mousedown .dragresize-topleft': 'onStartDiagonalResize'
      },

      render() {
        const result = this.__super__.render.apply(this, arguments);

        renderDragResizeHandles(this.__super__._converse, this);
        this.setWidth();
        return result;
      }

    },
    ControlBoxView: {
      events: {
        'mousedown .dragresize-top': 'onStartVerticalResize',
        'mousedown .dragresize-left': 'onStartHorizontalResize',
        'mousedown .dragresize-topleft': 'onStartDiagonalResize'
      },

      render() {
        const result = this.__super__.render.apply(this, arguments);

        renderDragResizeHandles(this.__super__._converse, this);
        this.setWidth();
        return result;
      },

      renderLoginPanel() {
        const result = this.__super__.renderLoginPanel.apply(this, arguments);

        this.initDragResize().setDimensions();
        return result;
      },

      renderControlBoxPane() {
        const result = this.__super__.renderControlBoxPane.apply(this, arguments);

        this.initDragResize().setDimensions();
        return result;
      }

    },
    ChatRoomView: {
      events: {
        'mousedown .dragresize-top': 'onStartVerticalResize',
        'mousedown .dragresize-left': 'onStartHorizontalResize',
        'mousedown .dragresize-topleft': 'onStartDiagonalResize'
      },

      render() {
        const result = this.__super__.render.apply(this, arguments);

        renderDragResizeHandles(this.__super__._converse, this);
        this.setWidth();
        return result;
      }

    }
  },

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    converse_core_api.settings.extend({
      'allow_dragresize': true
    });
    const dragResizable = {
      initDragResize() {
        var _converse$connection;

        const view = this;
        const debouncedSetDimensions = lodash_es_debounce(() => view.setDimensions());
        window.addEventListener('resize', view.debouncedSetDimensions);
        this.listenTo(this.model, 'destroy', () => window.removeEventListener('resize', debouncedSetDimensions)); // Determine and store the default box size.
        // We need this information for the drag-resizing feature.

        const flyout = this.el.querySelector('.box-flyout');
        const style = window.getComputedStyle(flyout);

        if (this.model.get('height') === undefined) {
          const height = parseInt(style.height.replace(/px$/, ''), 10);
          const width = parseInt(style.width.replace(/px$/, ''), 10);
          this.model.set('height', height);
          this.model.set('default_height', height);
          this.model.set('width', width);
          this.model.set('default_width', width);
        }

        const min_width = style['min-width'];
        const min_height = style['min-height'];
        this.model.set('min_width', min_width.endsWith('px') ? Number(min_width.replace(/px$/, '')) : 0);
        this.model.set('min_height', min_height.endsWith('px') ? Number(min_height.replace(/px$/, '')) : 0); // Initialize last known mouse position

        this.prev_pageY = 0;
        this.prev_pageX = 0;

        if ((_converse$connection = converse_core_converse.connection) !== null && _converse$connection !== void 0 && _converse$connection.connected) {
          this.height = this.model.get('height');
          this.width = this.model.get('width');
        }

        return this;
      },

      resizeChatBox(ev) {
        let diff;

        if (converse_core_converse.resizing.direction.indexOf('top') === 0) {
          diff = ev.pageY - this.prev_pageY;

          if (diff) {
            this.height = this.height - diff > (this.model.get('min_height') || 0) ? this.height - diff : this.model.get('min_height');
            this.prev_pageY = ev.pageY;
            this.setChatBoxHeight(this.height);
          }
        }

        if (converse_core_converse.resizing.direction.includes('left')) {
          diff = this.prev_pageX - ev.pageX;

          if (diff) {
            this.width = this.width + diff > (this.model.get('min_width') || 0) ? this.width + diff : this.model.get('min_width');
            this.prev_pageX = ev.pageX;
            this.setChatBoxWidth(this.width);
          }
        }
      },

      setWidth() {
        // If a custom width is applied (due to drag-resizing),
        // then we need to set the width of the .chatbox element as well.
        if (this.model.get('width')) {
          this.el.style.width = this.model.get('width');
        }
      },

      setDimensions() {
        // Make sure the chat box has the right height and width.
        this.adjustToViewport();
        this.setChatBoxHeight(this.model.get('height'));
        this.setChatBoxWidth(this.model.get('width'));
      },

      setChatBoxHeight(height) {
        if (height) {
          height = converse_dragresize_u.applyDragResistance(height, this.model.get('default_height')) + 'px';
        } else {
          height = "";
        }

        const flyout_el = this.el.querySelector('.box-flyout');

        if (flyout_el !== null) {
          flyout_el.style.height = height;
        }
      },

      setChatBoxWidth(width) {
        if (width) {
          width = converse_dragresize_u.applyDragResistance(width, this.model.get('default_width')) + 'px';
        } else {
          width = "";
        }

        this.el.style.width = width;
        const flyout_el = this.el.querySelector('.box-flyout');

        if (flyout_el !== null) {
          flyout_el.style.width = width;
        }
      },

      adjustToViewport() {
        /* Event handler called when viewport gets resized. We remove
         * custom width/height from chat boxes.
         */
        const viewport_width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
        const viewport_height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

        if (viewport_width <= 480) {
          this.model.set('height', undefined);
          this.model.set('width', undefined);
        } else if (viewport_width <= this.model.get('width')) {
          this.model.set('width', undefined);
        } else if (viewport_height <= this.model.get('height')) {
          this.model.set('height', undefined);
        }
      },

      onStartVerticalResize(ev, trigger = true) {
        if (!converse_core_api.settings.get('allow_dragresize')) {
          return true;
        }

        ev.preventDefault(); // Record element attributes for mouseMove().

        const flyout = this.el.querySelector('.box-flyout'),
              style = window.getComputedStyle(flyout);
        this.height = parseInt(style.height.replace(/px$/, ''), 10);
        converse_core_converse.resizing = {
          'chatbox': this,
          'direction': 'top'
        };
        this.prev_pageY = ev.pageY;

        if (trigger) {
          /**
           * Triggered once the user starts to vertically resize a {@link _converse.ChatBoxView}
           * @event _converse#startVerticalResize
           * @example _converse.api.listen.on('startVerticalResize', (view) => { ... });
           */
          converse_core_api.trigger('startVerticalResize', this);
        }
      },

      onStartHorizontalResize(ev, trigger = true) {
        if (!converse_core_api.settings.get('allow_dragresize')) {
          return true;
        }

        ev.preventDefault();
        const flyout = this.el.querySelector('.box-flyout'),
              style = window.getComputedStyle(flyout);
        this.width = parseInt(style.width.replace(/px$/, ''), 10);
        converse_core_converse.resizing = {
          'chatbox': this,
          'direction': 'left'
        };
        this.prev_pageX = ev.pageX;

        if (trigger) {
          /**
           * Triggered once the user starts to horizontally resize a {@link _converse.ChatBoxView}
           * @event _converse#startHorizontalResize
           * @example _converse.api.listen.on('startHorizontalResize', (view) => { ... });
           */
          converse_core_api.trigger('startHorizontalResize', this);
        }
      },

      onStartDiagonalResize(ev) {
        this.onStartHorizontalResize(ev, false);
        this.onStartVerticalResize(ev, false);
        converse_core_converse.resizing.direction = 'topleft';
        /**
         * Triggered once the user starts to diagonally resize a {@link _converse.ChatBoxView}
         * @event _converse#startDiagonalResize
         * @example _converse.api.listen.on('startDiagonalResize', (view) => { ... });
         */

        converse_core_api.trigger('startDiagonalResize', this);
      }

    };
    Object.assign(converse_core_converse.ChatBoxView.prototype, dragResizable);

    converse_dragresize_u.applyDragResistance = function (value, default_value) {
      /* This method applies some resistance around the
      * default_value. If value is close enough to
      * default_value, then default_value is returned instead.
      */
      if (value === undefined) {
        return undefined;
      } else if (default_value === undefined) {
        return value;
      }

      const resistance = 10;

      if (value !== default_value && Math.abs(value - default_value) < resistance) {
        return default_value;
      }

      return value;
    };

    function onMouseMove(ev) {
      if (!converse_core_converse.resizing || !converse_core_api.settings.get('allow_dragresize')) {
        return true;
      }

      ev.preventDefault();

      converse_core_converse.resizing.chatbox.resizeChatBox(ev);
    }

    function onMouseUp(ev) {
      if (!converse_core_converse.resizing || !converse_core_api.settings.get('allow_dragresize')) {
        return true;
      }

      ev.preventDefault();
      const height = converse_dragresize_u.applyDragResistance(converse_core_converse.resizing.chatbox.height, converse_core_converse.resizing.chatbox.model.get('default_height'));
      const width = converse_dragresize_u.applyDragResistance(converse_core_converse.resizing.chatbox.width, converse_core_converse.resizing.chatbox.model.get('default_width'));

      if (converse_core_api.connection.connected()) {
        converse_core_converse.resizing.chatbox.model.save({
          'height': height
        });

        converse_core_converse.resizing.chatbox.model.save({
          'width': width
        });
      } else {
        converse_core_converse.resizing.chatbox.model.set({
          'height': height
        });

        converse_core_converse.resizing.chatbox.model.set({
          'width': width
        });
      }

      converse_core_converse.resizing = null;
    }
    /************************ BEGIN Event Handlers ************************/


    function registerGlobalEventHandlers() {
      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', onMouseUp);
    }

    function unregisterGlobalEventHandlers() {
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
    }

    converse_core_api.listen.on('registeredGlobalEventHandlers', registerGlobalEventHandlers);
    converse_core_api.listen.on('unregisteredGlobalEventHandlers', unregisterGlobalEventHandlers);
    converse_core_api.listen.on('beforeShowingChatView', view => view.initDragResize().setDimensions());
    /************************ END Event Handlers ************************/
  }

});
// CONCATENATED MODULE: ./src/converse-singleton.js
/**
 * @module converse-singleton
 * @copyright JC Brand
 * @license Mozilla Public License (MPLv2)
 * @description A plugin which restricts Converse to only one chat.
 */

converse.plugins.add('converse-singleton', {
  enabled(_converse) {
    return _converse.api.settings.get("singleton");
  },

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    converse_core_api.settings.extend({
      'allow_logout': false,
      // No point in logging out when we have auto_login as true.
      'allow_muc_invitations': false,
      // Doesn't make sense to allow because only
      // roster contacts can be invited
      'hide_muc_server': true
    });

    if (!Array.isArray(converse_core_api.settings.get('auto_join_rooms')) && !Array.isArray(converse_core_api.settings.get('auto_join_private_chats'))) {
      throw new Error("converse-singleton: auto_join_rooms must be an Array");
    }

    if (converse_core_api.settings.get('auto_join_rooms').length > 1 || converse_core_api.settings.get('auto_join_private_chats').length > 1) {
      throw new Error("It doesn't make sense to have singleton set to true and " + "auto_join_rooms or auto_join_private_chats set to more then one, " + "since only one chat room may be open at any time.");
    }
  }

});
// CONCATENATED MODULE: ./src/converse-fullscreen.js
/**
 * @module converse-fullscreen
 * @license Mozilla Public License (MPLv2)
 * @copyright 2020, the Converse.js contributors
 */





converse.plugins.add('converse-fullscreen', {
  enabled(_converse) {
    return _converse.isUniView();
  },

  initialize() {
    converse_core_api.settings.extend({
      chatview_avatar_height: 50,
      chatview_avatar_width: 50,
      hide_open_bookmarks: true,
      show_controlbox_by_default: true,
      sticky_controlbox: true
    });
  }

});
// CONCATENATED MODULE: ./src/converse-mam-views.js
/**
 * @module converse-mam-views
 * @description
 * Views for XEP-0313 Message Archive Management
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */

converse.plugins.add('converse-mam-views', {
  dependencies: ['converse-mam', 'converse-chatview', 'converse-muc-views'],

  initialize() {
    converse_core_api.listen.on('chatBoxScrolledUp', async view => {
      if (view.model.messages.length) {
        const is_groupchat = view.model.get('type') === converse_core_converse.CHATROOMS_TYPE;

        const oldest_message = view.model.getOldestMessage();

        if (oldest_message) {
          const by_jid = is_groupchat ? view.model.get('jid') : converse_core_converse.bare_jid;
          const stanza_id = oldest_message && oldest_message.get(`stanza_id ${by_jid}`);
          view.addSpinner();

          if (stanza_id) {
            await view.model.fetchArchivedMessages({
              'before': stanza_id
            });
          } else {
            await view.model.fetchArchivedMessages({
              'end': oldest_message.get('time')
            });
          }

          view.clearSpinner();

          converse_core_converse.router.history.navigate(`#${oldest_message.get('msgid')}`);
        }
      }
    });
  }

});
// CONCATENATED MODULE: ./src/templates/trimmed_chat.js


/* harmony default export */ var trimmed_chat = (o => {
  const i18n_tooltip = i18n_('Click to restore this chat');

  return lit_html_html`
        <div class="chat-head-${o.type} chat-head row no-gutters">
            <a class="restore-chat w-100 align-self-center" title="${i18n_tooltip}" @click=${o.restore}>
                ${o.num_unread ? lit_html_html`<span class="message-count badge badge-light">${o.num_unread}</span>` : ''}
                ${o.title}
            </a>
            <a class="chatbox-btn close-chatbox-button fa fa-times" @click=${o.close}></a>
        </div>`;
});
// CONCATENATED MODULE: ./src/components/minimized_chat.js



class minimized_chat_MinimizedChat extends element_CustomElement {
  static get properties() {
    return {
      model: {
        type: Object
      },
      title: {
        type: String
      },
      type: {
        type: String
      },
      num_unread: {
        type: Number
      }
    };
  }

  render() {
    const data = {
      'close': ev => this.close(ev),
      'num_unread': this.num_unread,
      'restore': ev => this.restore(ev),
      'title': this.title,
      'type': this.type
    };
    return trimmed_chat(data);
  }

  close(ev) {
    ev === null || ev === void 0 ? void 0 : ev.preventDefault();

    const view = converse_core_converse.chatboxviews.get(this.model.get('id'));

    if (view) {
      // This will call model.destroy(), removing it from the
      // collection and will also emit 'chatBoxClosed'
      view.close();
    } else {
      this.model.destroy();
      converse_core_api.trigger('chatBoxClosed', this);
    }
  }

  restore(ev) {
    ev === null || ev === void 0 ? void 0 : ev.preventDefault();
    this.model.maximize();
  }

}
converse_core_api.elements.define('converse-minimized-chat', minimized_chat_MinimizedChat);
// CONCATENATED MODULE: ./src/templates/chats_panel.js


/* harmony default export */ var chats_panel = (o => lit_html_html`<div id="minimized-chats" class="${o.chats.length ? '' : 'hidden'}">
        <a id="toggle-minimized-chats" class="row no-gutters" @click=${o.toggle}>
            ${o.num_minimized} ${i18n_('Minimized')}
            <span class="unread-message-count ${!o.num_unread ? 'unread-message-count-hidden' : ''}" href="#">${o.num_unread}</span>
        </a>
        <div class="flyout minimized-chats-flyout row no-gutters ${o.collapsed ? 'hidden' : ''}">
            ${o.chats.map(chat => lit_html_html`<converse-minimized-chat
                        .model=${chat}
                        title=${chat.getDisplayName()}
                        type=${chat.get('type')}
                        num_unread=${chat.get('num_unread')}></converse-minimized-chat>`)}
        </div>
    </div>`);
// CONCATENATED MODULE: ./src/converse-minimize.js
/**
 * @module converse-minimize
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */









const {
  dayjs: converse_minimize_dayjs
} = converse.env;
const converse_minimize_u = converse.env.utils;
converse.plugins.add('converse-minimize', {
  /* Optional dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin. They are called "optional" because they might not be
   * available, in which case any overrides applicable to them will be
   * ignored.
   *
   * It's possible however to make optional dependencies non-optional.
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found.
   *
   * NB: These plugins need to have already been loaded via require.js.
   */
  dependencies: ["converse-chatview", "converse-controlbox", "converse-muc-views", "converse-headlines-view", "converse-dragresize"],

  enabled(_converse) {
    return _converse.api.settings.get("view_mode") === 'overlayed';
  },

  overrides: {
    // Overrides mentioned here will be picked up by converse.js's
    // plugin architecture they will replace existing methods on the
    // relevant objects or classes.
    //
    // New functions which don't exist yet can also be added.
    ChatBox: {
      initialize() {
        this.__super__.initialize.apply(this, arguments);

        this.on('show', this.maximize, this);

        if (this.get('id') === 'controlbox') {
          return;
        }

        this.save({
          'minimized': this.get('minimized') || false,
          'time_minimized': this.get('time_minimized') || converse_minimize_dayjs()
        });
      },

      maybeShow(force) {
        if (!force && this.get('minimized')) {
          // Must return the chatbox
          return this;
        }

        return this.__super__.maybeShow.apply(this, arguments);
      },

      isHidden() {
        return this.__super__.isHidden.call(this) || this.get('minimized');
      }

    },
    ChatBoxView: {
      show() {
        const {
          _converse
        } = this.__super__;

        if (_converse.api.settings.get("view_mode") === 'overlayed' && this.model.get('minimized')) {
          this.model.minimize();
          return this;
        } else {
          return this.__super__.show.apply(this, arguments);
        }
      },

      isNewMessageHidden() {
        return this.model.get('minimized') || this.__super__.isNewMessageHidden.apply(this, arguments);
      },

      setChatBoxHeight(height) {
        if (!this.model.get('minimized')) {
          return this.__super__.setChatBoxHeight.call(this, height);
        }
      },

      setChatBoxWidth(width) {
        if (!this.model.get('minimized')) {
          return this.__super__.setChatBoxWidth.call(this, width);
        }
      }

    }
  },

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by Converse.js's plugin machinery.
     */
    converse_core_api.settings.extend({
      'no_trimming': false
    });
    const minimizableChatBox = {
      maximize() {
        converse_minimize_u.safeSave(this, {
          'minimized': false,
          'time_opened': new Date().getTime()
        });
      },

      minimize() {
        converse_minimize_u.safeSave(this, {
          'minimized': true,
          'time_minimized': new Date().toISOString()
        });
      }

    };
    Object.assign(converse_core_converse.ChatBox.prototype, minimizableChatBox);
    const minimizableChatBoxView = {
      /**
       * Handler which gets called when a {@link _converse#ChatBox} has it's
       * `minimized` property set to false.
       *
       * Will trigger {@link _converse#chatBoxMaximized}
       * @private
       * @returns {_converse.ChatBoxView|_converse.ChatRoomView}
       */
      onMaximized() {
        const {
          _converse
        } = this.__super__;
        this.insertIntoDOM();

        if (!this.model.isScrolledUp()) {
          this.model.clearUnreadMsgCounter();
        }

        this.model.setChatState(_converse.ACTIVE);
        this.show();
        /**
         * Triggered when a previously minimized chat gets maximized
         * @event _converse#chatBoxMaximized
         * @type { _converse.ChatBoxView }
         * @example _converse.api.listen.on('chatBoxMaximized', view => { ... });
         */

        converse_core_api.trigger('chatBoxMaximized', this);
        return this;
      },

      /**
       * Handler which gets called when a {@link _converse#ChatBox} has it's
       * `minimized` property set to true.
       *
       * Will trigger {@link _converse#chatBoxMinimized}
       * @private
       * @returns {_converse.ChatBoxView|_converse.ChatRoomView}
       */
      onMinimized(ev) {
        const {
          _converse
        } = this.__super__;

        if (ev && ev.preventDefault) {
          ev.preventDefault();
        } // save the scroll position to restore it on maximize


        if (this.model.collection && this.model.collection.browserStorage) {
          this.model.save({
            'scroll': this.content.scrollTop
          });
        } else {
          this.model.set({
            'scroll': this.content.scrollTop
          });
        }

        this.model.setChatState(_converse.INACTIVE);
        this.hide();
        /**
         * Triggered when a previously maximized chat gets Minimized
         * @event _converse#chatBoxMinimized
         * @type { _converse.ChatBoxView }
         * @example _converse.api.listen.on('chatBoxMinimized', view => { ... });
         */

        converse_core_api.trigger('chatBoxMinimized', this);
        return this;
      },

      /**
       * Minimizes a chat box.
       * @returns {_converse.ChatBoxView|_converse.ChatRoomView}
       */
      minimize(ev) {
        if (ev && ev.preventDefault) {
          ev.preventDefault();
        }

        this.model.minimize();
        return this;
      },

      onMinimizedChanged(item) {
        if (item.get('minimized')) {
          this.onMinimized();
        } else {
          this.onMaximized();
        }
      }

    };
    Object.assign(converse_core_converse.ChatBoxView.prototype, minimizableChatBoxView);
    const chatTrimmer = {
      getChatBoxWidth(view) {
        if (view.model.get('id') === 'controlbox') {
          const controlbox = this.get('controlbox'); // We return the width of the controlbox or its toggle,
          // depending on which is visible.

          if (!controlbox || !converse_minimize_u.isVisible(controlbox.el)) {
            return converse_minimize_u.getOuterWidth(converse_core_converse.controlboxtoggle.el, true);
          } else {
            return converse_minimize_u.getOuterWidth(controlbox.el, true);
          }
        } else if (!view.model.get('minimized') && converse_minimize_u.isVisible(view.el)) {
          return converse_minimize_u.getOuterWidth(view.el, true);
        }

        return 0;
      },

      getShownChats() {
        return this.filter(view => // The controlbox can take a while to close,
        // so we need to check its state. That's why we checked
        // the 'closed' state.
        !view.model.get('minimized') && !view.model.get('closed') && converse_minimize_u.isVisible(view.el));
      },

      getMinimizedWidth() {
        var _converse$minimized_c;

        const minimized_el = (_converse$minimized_c = converse_core_converse.minimized_chats) === null || _converse$minimized_c === void 0 ? void 0 : _converse$minimized_c.el;
        return this.model.pluck('minimized').includes(true) ? converse_minimize_u.getOuterWidth(minimized_el, true) : 0;
      },

      getBoxesWidth(newchat) {
        const new_id = newchat ? newchat.model.get('id') : null;
        const newchat_width = newchat ? converse_minimize_u.getOuterWidth(newchat.el, true) : 0;
        return Object.values(this.xget(new_id)).reduce((memo, view) => memo + this.getChatBoxWidth(view), newchat_width);
      },

      /**
       * This method is called when a newly created chat box will be shown.
       * It checks whether there is enough space on the page to show
       * another chat box. Otherwise it minimizes the oldest chat box
       * to create space.
       * @private
       * @method _converse.ChatBoxViews#trimChats
       * @param { _converse.ChatBoxView|_converse.ChatRoomView|_converse.ControlBoxView|_converse.HeadlinesBoxView } [newchat]
       */
      async trimChats(newchat) {
        var _converse$minimized_c2;

        if (converse_core_api.settings.get('no_trimming') || !converse_core_api.connection.connected() || converse_core_api.settings.get("view_mode") !== 'overlayed') {
          return;
        }

        const shown_chats = this.getShownChats();

        if (shown_chats.length <= 1) {
          return;
        }

        const body_width = converse_minimize_u.getOuterWidth(document.querySelector('body'), true);

        if (this.getChatBoxWidth(shown_chats[0]) === body_width) {
          // If the chats shown are the same width as the body,
          // then we're in responsive mode and the chats are
          // fullscreen. In this case we don't trim.
          return;
        }

        await converse_core_api.waitUntil('minimizedChatsInitialized');
        const minimized_el = (_converse$minimized_c2 = converse_core_converse.minimized_chats) === null || _converse$minimized_c2 === void 0 ? void 0 : _converse$minimized_c2.el;

        if (minimized_el) {
          while (this.getMinimizedWidth() + this.getBoxesWidth(newchat) > body_width) {
            const new_id = newchat ? newchat.model.get('id') : null;
            const oldest_chat = this.getOldestMaximizedChat([new_id]);

            if (oldest_chat) {
              // We hide the chat immediately, because waiting
              // for the event to fire (and letting the
              // ChatBoxView hide it then) causes race
              // conditions.
              const view = this.get(oldest_chat.get('id'));

              if (view) {
                view.hide();
              }

              oldest_chat.minimize();
            } else {
              break;
            }
          }
        }
      },

      getOldestMaximizedChat(exclude_ids) {
        // Get oldest view (if its id is not excluded)
        exclude_ids.push('controlbox');
        let i = 0;
        let model = this.model.sort().at(i);

        while (exclude_ids.includes(model.get('id')) || model.get('minimized') === true) {
          i++;
          model = this.model.at(i);

          if (!model) {
            return null;
          }
        }

        return model;
      }

    };
    Object.assign(converse_core_converse.ChatBoxViews.prototype, chatTrimmer);
    converse_core_api.promises.add('minimizedChatsInitialized');
    converse_core_converse.MinimizedChatsToggle = model_Model.extend({
      defaults: {
        'collapsed': false
      }
    });
    converse_core_converse.MinimizedChats = View.extend({
      tagName: 'span',

      async initialize() {
        await this.initToggle();
        this.render();
        this.listenTo(this.minchats, 'change:collapsed', this.render);
        this.listenTo(this.model, 'add', this.render);
        this.listenTo(this.model, 'change:fullname', this.render);
        this.listenTo(this.model, 'change:jid', this.render);
        this.listenTo(this.model, 'change:minimized', this.render);
        this.listenTo(this.model, 'change:name', this.render);
        this.listenTo(this.model, 'change:num_unread', this.render);
        this.listenTo(this.model, 'remove', this.render);
      },

      render() {
        const chats = this.model.where({
          'minimized': true
        });
        const num_unread = chats.reduce((acc, chat) => acc + chat.get('num_unread'), 0);
        const num_minimized = chats.reduce((acc, chat) => acc + (chat.get('minimized') ? 1 : 0), 0);
        const collapsed = this.minchats.get('collapsed');
        const data = {
          chats,
          num_unread,
          num_minimized,
          collapsed
        };

        data.toggle = ev => this.toggle(ev);

        render_render(chats_panel(data), this.el);

        if (!this.el.parentElement) {
          converse_core_converse.chatboxviews.insertRowColumn(this.el);
        }
      },

      async initToggle() {
        const id = `converse.minchatstoggle-${converse_core_converse.bare_jid}`;
        this.minchats = new converse_core_converse.MinimizedChatsToggle({
          id
        });
        this.minchats.browserStorage = converse_core_converse.createStore(id);
        await new Promise(resolve => this.minchats.fetch({
          'success': resolve,
          'error': resolve
        }));
      },

      toggle(ev) {
        ev === null || ev === void 0 ? void 0 : ev.preventDefault();
        this.minchats.save({
          'collapsed': !this.minchats.get('collapsed')
        });
      }

    });

    function initMinimizedChats() {
      var _converse$minimized_c3;

      (_converse$minimized_c3 = converse_core_converse.minimized_chats) === null || _converse$minimized_c3 === void 0 ? void 0 : _converse$minimized_c3.remove();
      converse_core_converse.minimized_chats = new converse_core_converse.MinimizedChats({
        model: converse_core_converse.chatboxes
      });
      /**
       * Triggered once the _converse.MinimizedChats instance has been initialized
       * @event _converse#minimizedChatsInitialized
       * @example _converse.api.listen.on('minimizedChatsInitialized', () => { ... });
       */

      converse_core_api.trigger('minimizedChatsInitialized');
    }

    function addMinimizeButtonToChat(view, buttons) {
      const data = {
        'a_class': 'toggle-chatbox-button',
        'handler': ev => view.minimize(ev),
        'i18n_text': i18n_('Minimize'),
        'i18n_title': i18n_('Minimize this chat'),
        'icon_class': "fa-minus",
        'name': 'minimize',
        'standalone': converse_core_converse.api.settings.get("view_mode") === 'overlayed'
      };
      const names = buttons.map(t => t.name);
      const idx = names.indexOf('close');
      return idx > -1 ? [...buttons.slice(0, idx), data, ...buttons.slice(idx)] : [data, ...buttons];
    }

    function addMinimizeButtonToMUC(view, buttons) {
      const data = {
        'a_class': 'toggle-chatbox-button',
        'handler': ev => view.minimize(ev),
        'i18n_text': i18n_('Minimize'),
        'i18n_title': i18n_('Minimize this groupchat'),
        'icon_class': "fa-minus",
        'name': 'minimize',
        'standalone': converse_core_converse.api.settings.get("view_mode") === 'overlayed'
      };
      const names = buttons.map(t => t.name);
      const idx = names.indexOf('signout');
      return idx > -1 ? [...buttons.slice(0, idx), data, ...buttons.slice(idx)] : [data, ...buttons];
    }
    /************************ BEGIN Event Handlers ************************/


    converse_core_api.listen.on('chatBoxInsertedIntoDOM', view => converse_core_converse.chatboxviews.trimChats(view));
    converse_core_api.listen.on('connected', () => initMinimizedChats());
    converse_core_api.listen.on('controlBoxOpened', view => converse_core_converse.chatboxviews.trimChats(view));
    converse_core_api.listen.on('chatBoxViewInitialized', v => v.listenTo(v.model, 'change:minimized', v.onMinimizedChanged));
    converse_core_api.listen.on('chatRoomViewInitialized', view => {
      view.listenTo(view.model, 'change:minimized', view.onMinimizedChanged);
      view.model.get('minimized') && view.hide();
    });
    converse_core_api.listen.on('getHeadingButtons', (view, buttons) => {
      if (view.model.get('type') === converse_core_converse.CHATROOMS_TYPE) {
        return addMinimizeButtonToMUC(view, buttons);
      } else {
        return addMinimizeButtonToChat(view, buttons);
      }
    });
    const debouncedTrimChats = lodash_es_debounce(() => converse_core_converse.chatboxviews.trimChats(), 250);
    converse_core_api.listen.on('registeredGlobalEventHandlers', () => window.addEventListener("resize", debouncedTrimChats));
    converse_core_api.listen.on('unregisteredGlobalEventHandlers', () => window.removeEventListener("resize", debouncedTrimChats));
    /************************ END Event Handlers ************************/
  }

});
// CONCATENATED MODULE: ./src/components/autocomplete.js




class autocomplete_AutoCompleteComponent extends element_CustomElement {
  static get properties() {
    return {
      'getAutoCompleteList': {
        type: Function
      },
      'auto_evaluate': {
        type: Boolean
      },
      'auto_first': {
        type: Boolean
      },
      // Should the first element be automatically selected?
      'filter': {
        type: String
      },
      'include_triggers': {
        type: String
      },
      'min_chars': {
        type: Number
      },
      'name': {
        type: String
      },
      'placeholder': {
        type: String
      },
      'triggers': {
        type: String
      }
    };
  }

  constructor() {
    super();
    this.auto_evaluate = true; // Should evaluation happen automatically without any particular key as trigger?

    this.auto_first = false; // Should the first element be automatically selected?

    this.filter = 'contains';
    this.include_triggers = ''; // Space separated chars which should be included in the returned value

    this.match_current_word = false; // Match only the current word, otherwise all input is matched

    this.max_items = 10;
    this.min_chars = 1;
    this.triggers = ''; // String of space separated chars
  }

  render() {
    return lit_html_html`
            <div class="suggestion-box suggestion-box__name">
                <ul class="suggestion-box__results suggestion-box__results--above" hidden=""></ul>
                <input type="text" name="${this.name}"
                       autocomplete="off"
                       @keydown=${this.onKeyDown}
                       @keyup=${this.onKeyUp}
                       class="form-control suggestion-box__input"
                       placeholder="${this.placeholder}"/>
                <span class="suggestion-box__additions visually-hidden" role="status" aria-live="assertive" aria-relevant="additions"></span>
            </div>
        `;
  }

  firstUpdated() {
    this.auto_complete = new converse_autocomplete_AutoComplete(this.firstElementChild, {
      'ac_triggers': this.triggers.split(' '),
      'auto_evaluate': this.auto_evaluate,
      'auto_first': this.auto_first,
      'filter': this.filter == 'contains' ? FILTER_CONTAINS : FILTER_STARTSWITH,
      'include_triggers': [],
      'list': () => this.getAutoCompleteList(),
      'match_current_word': true,
      'max_items': this.max_items,
      'min_chars': this.min_chars
    });
    this.auto_complete.on('suggestion-box-selectcomplete', () => this.auto_completing = false);
  }

  onKeyDown(ev) {
    this.auto_complete.onKeyDown(ev);
  }

  onKeyUp(ev) {
    this.auto_complete.evaluate(ev);
  }

}
converse_core_api.elements.define('converse-autocomplete', autocomplete_AutoCompleteComponent);
// CONCATENATED MODULE: ./src/templates/occupant.js



const occupant_title = o => {
  const i18n_moderator_hint = i18n_('This user is a moderator.');

  const i18n_participant_hint = i18n_('This user can send messages in this groupchat.');

  const i18n_visitor_hint = i18n_('This user can NOT send messages in this groupchat.');

  const spaced_jid = `${o.jid} ` || '';

  if (o.role === "moderator") {
    return `${spaced_jid}${i18n_moderator_hint} ${o.hint_occupant}`;
  } else if (o.role === "participant") {
    return `${spaced_jid}${i18n_participant_hint} ${o.hint_occupant}`;
  } else if (o.role === "visitor") {
    return `${spaced_jid}${i18n_visitor_hint} ${o.hint_occupant}`;
  } else if (!["visitor", "participant", "moderator"].includes(o.role)) {
    return `${spaced_jid}${o.hint_occupant}`;
  }
};

/* harmony default export */ var templates_occupant = (o => {
  const i18n_owner = i18n_('Owner');

  const i18n_admin = i18n_('Admin');

  const i18n_member = i18n_('Member');

  const i18n_moderator = i18n_('Moderator');

  const i18n_visitor = i18n_('Visitor');

  return lit_html_html`
        <li class="occupant" id="${o.id}" title="${occupant_title(o)}">
            <div class="row no-gutters">
                <div class="col-auto">
                    <div class="occupant-status occupant-${o.show} circle" title="${o.hint_show}"></div>
                </div>
                <div class="col occupant-nick-badge">
                    <span class="occupant-nick">${o.nick || o.jid}</span>
                    <span class="occupant-badges">
                        ${o.affiliation === "owner" ? lit_html_html`<span class="badge badge-groupchat">${i18n_owner}</span>` : ''}
                        ${o.affiliation === "admin" ? lit_html_html`<span class="badge badge-info">${i18n_admin}</span>` : ''}
                        ${o.affiliation === "member" ? lit_html_html`<span class="badge badge-info">${i18n_member}</span>` : ''}
                        ${o.role === "moderator" ? lit_html_html`<span class="badge badge-info">${i18n_moderator}</span>` : ''}
                        ${o.role === "visitor" ? lit_html_html`<span class="badge badge-secondary">${i18n_visitor}</span>` : ''}
                    </span>
                </div>
            </div>
        </li>
    `;
});
// CONCATENATED MODULE: ./src/templates/muc_sidebar.js



const PRETTY_CHAT_STATUS = {
  'offline': 'Offline',
  'unavailable': 'Unavailable',
  'xa': 'Extended Away',
  'away': 'Away',
  'dnd': 'Do not disturb',
  'chat': 'Chattty',
  'online': 'Online'
};
/* harmony default export */ var muc_sidebar = (o => {
  const i18n_occupant_hint = occupant => i18n_('Click to mention %1$s in your message.', occupant.get('nick'));

  const i18n_participants = i18n_('Participants');

  const occupant_tpls = o.occupants.map(occupant => {
    return templates_occupant(Object.assign({
      'jid': '',
      'hint_show': PRETTY_CHAT_STATUS[occupant.get('show')],
      'hint_occupant': i18n_occupant_hint(occupant)
    }, occupant.toJSON()));
  });
  return lit_html_html`
        <div class="occupants-header">
            <i class="hide-occupants fa fa-times"></i>
            <div class="occupants-header--title">
                <span class="occupants-heading">${i18n_participants}</span>
            </div>
        </div>
        <div class="dragresize dragresize-occupants-left"></div>
        <ul class="occupant-list">${occupant_tpls}</ul>
    `;
});
// CONCATENATED MODULE: ./src/components/muc-sidebar.js




const muc_sidebar_u = converse.env.utils;
class muc_sidebar_MUCSidebar extends element_CustomElement {
  static get properties() {
    return {
      chatroom: {
        type: Object
      },
      occupants: {
        type: Object
      }
    };
  }

  connectedCallback() {
    super.connectedCallback();
    this.listenTo(this.occupants, 'add', this.requestUpdate);
    this.listenTo(this.occupants, 'remove', this.requestUpdate);
    this.listenTo(this.occupants, 'change', this.requestUpdate);
  }

  render() {
    const tpl = muc_sidebar(Object.assign(this.chatroom.toJSON(), {
      'occupants': [...this.occupants.models]
    }));
    return tpl;
  }

  shouldShow() {
    return !this.chatroom.get('hidden_occupants') && this.chatroom.session.get('connection_status') === converse.ROOMSTATUS.ENTERED;
  }

  setVisibility() {
    // TODO: We're still manually showing/hiding stuff in ChatRoomView,
    // eventually we want everything to render declaratively, after which this
    // method won't be necessary anymore
    this.shouldShow() ? muc_sidebar_u.showElement(this) : muc_sidebar_u.hideElement(this);
  }

}
converse_core_api.elements.define('converse-muc-sidebar', muc_sidebar_MUCSidebar);
// CONCATENATED MODULE: ./src/templates/add_chatroom_modal.js






const nickname_input = o => {
  const i18n_nickname = i18n_('Nickname');

  const i18n_required_field = i18n_('This field is required');

  return lit_html_html`
        <div class="form-group" >
            <label for="nickname">${i18n_nickname}:</label>
            <input type="text" title="${i18n_required_field}" required="required" name="nickname" value="${o.nick || ''}" class="form-control"/>
        </div>
    `;
};

/* harmony default export */ var add_chatroom_modal = (o => {
  const i18n_join = i18n_('Join');

  const i18n_enter = i18n_('Enter a new Groupchat');

  return lit_html_html`
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="add-chatroom-modal-label">${i18n_enter}</h5>
                    ${modal_header_close_button}
                </div>
                <div class="modal-body">
                    <span class="modal-alert"></span>
                    <form class="converse-form add-chatroom">
                        <div class="form-group">
                            <label for="chatroom">${o.label_room_address}:</label>
                            ${o.muc_roomid_policy_error_msg ? lit_html_html`<label class="roomid-policy-error">${o.muc_roomid_policy_error_msg}</label>` : ''}
                            <input type="text" required="required" name="chatroom" class="form-control roomjid-input" placeholder="${o.chatroom_placeholder}"/>
                        </div>
                        ${o.muc_roomid_policy_hint ? lit_html_html`<div class="form-group">${unsafeHTML(xss_default.a.filterXSS(o.muc_roomid_policy_hint, {
    'whiteList': {
      b: [],
      br: [],
      em: []
    }
  }))}</div>` : ''}
                        ${!o._converse.locked_muc_nickname ? nickname_input(o) : ''}
                        <input type="submit" class="btn btn-primary" name="join" value="${i18n_join || ''}" ?disabled=${o.muc_roomid_policy_error_msg}>
                    </form>
                </div>
            </div>
        </div>
    `;
});
// CONCATENATED MODULE: ./src/modals/add-muc.js




const {
  u: add_muc_u,
  Strophe: add_muc_Strophe
} = converse.env;
/* harmony default export */ var add_muc = (BootstrapModal.extend({
  id: 'add-chatroom-modal',
  events: {
    'submit form.add-chatroom': 'openChatRoom',
    'keyup .roomjid-input': 'checkRoomidPolicy',
    'change .roomjid-input': 'checkRoomidPolicy'
  },

  initialize() {
    BootstrapModal.prototype.initialize.apply(this, arguments);
    this.listenTo(this.model, 'change:muc_domain', this.render);
    this.muc_roomid_policy_error_msg = null;
  },

  toHTML() {
    let placeholder = '';

    if (!converse_core_api.settings.get('locked_muc_domain')) {
      const muc_domain = this.model.get('muc_domain') || converse_core_api.settings.get('muc_domain');
      placeholder = muc_domain ? `name@${muc_domain}` : i18n_('name@conference.example.org');
    }

    return add_chatroom_modal(Object.assign(this.model.toJSON(), {
      '_converse': converse_core_converse,
      'label_room_address': converse_core_api.settings.get('muc_domain') ? i18n_('Groupchat name') : i18n_('Groupchat address'),
      'chatroom_placeholder': placeholder,
      'muc_roomid_policy_error_msg': this.muc_roomid_policy_error_msg,
      'muc_roomid_policy_hint': converse_core_api.settings.get('muc_roomid_policy_hint')
    }));
  },

  afterRender() {
    this.el.addEventListener('shown.bs.modal', () => {
      this.el.querySelector('input[name="chatroom"]').focus();
    }, false);
  },

  parseRoomDataFromEvent(form) {
    const data = new FormData(form);
    const jid = data.get('chatroom');
    let nick;

    if (converse_core_api.settings.get('locked_muc_nickname')) {
      nick = converse_core_converse.getDefaultMUCNickname();

      if (!nick) {
        throw new Error("Using locked_muc_nickname but no nickname found!");
      }
    } else {
      nick = data.get('nickname').trim();
    }

    return {
      'jid': jid,
      'nick': nick
    };
  },

  openChatRoom(ev) {
    ev.preventDefault();
    const data = this.parseRoomDataFromEvent(ev.target);

    if (data.nick === "") {
      // Make sure defaults apply if no nick is provided.
      data.nick = undefined;
    }

    let jid;

    if (converse_core_api.settings.get('locked_muc_domain') || converse_core_api.settings.get('muc_domain') && !add_muc_u.isValidJID(data.jid)) {
      jid = `${add_muc_Strophe.escapeNode(data.jid)}@${converse_core_api.settings.get('muc_domain')}`;
    } else {
      jid = data.jid;
      this.model.setDomain(jid);
    }

    converse_core_api.rooms.open(jid, Object.assign(data, {
      jid
    }), true);
    this.modal.hide();
    ev.target.reset();
  },

  checkRoomidPolicy() {
    if (converse_core_api.settings.get('muc_roomid_policy') && converse_core_api.settings.get('muc_domain')) {
      let jid = this.el.querySelector('.roomjid-input').value;

      if (converse.locked_muc_domain || !add_muc_u.isValidJID(jid)) {
        jid = `${add_muc_Strophe.escapeNode(jid)}@${converse_core_api.settings.get('muc_domain')}`;
      }

      const roomid = add_muc_Strophe.getNodeFromJid(jid);
      const roomdomain = add_muc_Strophe.getDomainFromJid(jid);

      if (converse_core_api.settings.get('muc_domain') !== roomdomain || converse_core_api.settings.get('muc_roomid_policy').test(roomid)) {
        this.muc_roomid_policy_error_msg = null;
      } else {
        this.muc_roomid_policy_error_msg = i18n_('Groupchat id is invalid.');
      }

      this.render();
    }
  }

}));
// CONCATENATED MODULE: ./src/templates/muc_invite_modal.js



/* harmony default export */ var muc_invite_modal = (o => {
  const i18n_invite = i18n_('Invite');

  const i18n_invite_heading = i18n_('Invite someone to this groupchat');

  const i18n_jid_placeholder = i18n_('user@example.org');

  const i18n_error_message = i18n_('Please enter a valid XMPP address');

  const i18n_invite_label = i18n_('XMPP Address');

  const i18n_reason = i18n_('Optional reason for the invitation');

  return lit_html_html`
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="add-chatroom-modal-label">${i18n_invite_heading}</h5>
                    ${modal_header_close_button}
                </div>
                <div class="modal-body">
                    <span class="modal-alert"></span>
                    <div class="suggestion-box room-invite">
                        <form @submit=${o.submitInviteForm}>
                            <div class="form-group">
                                <label class="clearfix" for="invitee_jids">${i18n_invite_label}:</label>
                                ${o.invalid_invite_jid ? lit_html_html`<div class="error error-feedback">${i18n_error_message}</div>` : ''}
                                <input class="form-control suggestion-box__input"
                                    required="required"
                                    name="invitee_jids"
                                    id="invitee_jids"
                                    placeholder="${i18n_jid_placeholder}"
                                    type="text"/>
                                <span class="suggestion-box__additions visually-hidden" role="status" aria-live="assertive" aria-relevant="additions"></span>
                                <ul class="suggestion-box__results suggestion-box__results--below" hidden=""></ul>
                            </div>
                            <div class="form-group">
                                <label>${i18n_reason}:</label>
                                <textarea class="form-control" name="reason"></textarea>
                            </div>
                            <div class="form-group">
                                <button type="submit" class="btn btn-primary">${i18n_invite}</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    `;
});
// CONCATENATED MODULE: ./src/modals/muc-invite.js



const muc_invite_u = converse.env.utils;
/* harmony default export */ var muc_invite = (BootstrapModal.extend({
  id: "muc-invite-modal",

  initialize() {
    BootstrapModal.prototype.initialize.apply(this, arguments);
    this.listenTo(this.model, 'change', this.render);
    this.initInviteWidget();
  },

  toHTML() {
    return muc_invite_modal(Object.assign(this.model.toJSON(), {
      'submitInviteForm': ev => this.submitInviteForm(ev)
    }));
  },

  initInviteWidget() {
    if (this.invite_auto_complete) {
      this.invite_auto_complete.destroy();
    }

    const list = converse_core_converse.roster.map(i => ({
      'label': i.getDisplayName(),
      'value': i.get('jid')
    }));

    const el = this.el.querySelector('.suggestion-box').parentElement;
    this.invite_auto_complete = new converse_core_converse.AutoComplete(el, {
      'min_chars': 1,
      'list': list
    });
  },

  submitInviteForm(ev) {
    ev.preventDefault(); // TODO: Add support for sending an invite to multiple JIDs

    const data = new FormData(ev.target);
    const jid = data.get('invitee_jids');
    const reason = data.get('reason');

    if (muc_invite_u.isValidJID(jid)) {
      // TODO: Create and use API here
      this.chatroomview.model.directInvite(jid, reason);
      this.modal.hide();
    } else {
      this.model.set({
        'invalid_invite_jid': true
      });
    }
  }

}));
// CONCATENATED MODULE: ./src/templates/list_chatrooms_modal.js






const list_chatrooms_modal_form = o => {
  const i18n_query = i18n_('Show groupchats');

  const i18n_server_address = i18n_('Server address');

  return lit_html_html`
        <form class="converse-form list-chatrooms"
            @submit=${o.submitForm}>
            <div class="form-group">
                <label for="chatroom">${i18n_server_address}:</label>
                <input type="text"
                    @change=${o.setDomainFromEvent}
                    value="${o.muc_domain || ''}"
                    required="required"
                    name="server"
                    class="form-control"
                    placeholder="${o.server_placeholder}"/>
            </div>
            <input type="submit" class="btn btn-primary" name="list" value="${i18n_query}"/>
        </form>
    `;
};

const tpl_item = (o, item) => {
  const i18n_info_title = i18n_('Show more information on this groupchat');

  const i18n_open_title = i18n_('Click to open this groupchat');

  return lit_html_html`
        <li class="room-item list-group-item">
            <div class="available-chatroom d-flex flex-row">
                <a class="open-room available-room w-100"
                @click=${o.openRoom}
                data-room-jid="${item.jid}"
                data-room-name="${item.name}"
                title="${i18n_open_title}"
                href="#">${item.name || item.jid}</a>
                <a class="right room-info icon-room-info"
                @click=${o.toggleRoomInfo}
                data-room-jid="${item.jid}"
                title="${i18n_info_title}"
                href="#"></a>
            </div>
        </li>
    `;
};

/* harmony default export */ var list_chatrooms_modal = (o => {
  const i18n_list_chatrooms = i18n_('Query for Groupchats');

  return lit_html_html`
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="list-chatrooms-modal-label">${i18n_list_chatrooms}</h5>
                    ${modal_header_close_button}
                </div>
                <div class="modal-body d-flex flex-column">
                    <span class="modal-alert"></span>
                    ${o.show_form ? list_chatrooms_modal_form(o) : ''}
                    <ul class="available-chatrooms list-group">
                        ${o.loading_items ? lit_html_html`<li class="list-group-item"> ${spinner()} </li>` : ''}
                        ${o.feedback_text ? lit_html_html`<li class="list-group-item active">${o.feedback_text}</li>` : ''}
                        ${repeat(o.items, item => item.jid, item => tpl_item(o, item))}
                    </ul>
                </div>
                <div class="modal-footer">${modal_close_button}</div>
            </div>
        </div>
    `;
});
// EXTERNAL MODULE: ./src/templates/room_description.html
var room_description = __webpack_require__(174);
var room_description_default = /*#__PURE__*/__webpack_require__.n(room_description);

// CONCATENATED MODULE: ./src/modals/muc-list.js









const {
  u: muc_list_u,
  Strophe: muc_list_Strophe,
  $iq: muc_list_$iq,
  sizzle: muc_list_sizzle
} = converse.env;
/* Insert groupchat info (based on returned #disco IQ stanza)
 * @function insertRoomInfo
 * @param { HTMLElement } el - The HTML DOM element that contains the info.
 * @param { XMLElement } stanza - The IQ stanza containing the groupchat info.
 */

function insertRoomInfo(el, stanza) {
  var _head, _head2;

  // All MUC features found here: https://xmpp.org/registrar/disco-features.html
  el.querySelector('span.spinner').remove();
  el.querySelector('a.room-info').classList.add('selected');
  el.insertAdjacentHTML('beforeEnd', room_description_default()({
    'jid': stanza.getAttribute('from'),
    'desc': (_head = lodash_es_head(muc_list_sizzle('field[var="muc#roominfo_description"] value', stanza))) === null || _head === void 0 ? void 0 : _head.textContent,
    'occ': (_head2 = lodash_es_head(muc_list_sizzle('field[var="muc#roominfo_occupants"] value', stanza))) === null || _head2 === void 0 ? void 0 : _head2.textContent,
    'hidden': muc_list_sizzle('feature[var="muc_hidden"]', stanza).length,
    'membersonly': muc_list_sizzle('feature[var="muc_membersonly"]', stanza).length,
    'moderated': muc_list_sizzle('feature[var="muc_moderated"]', stanza).length,
    'nonanonymous': muc_list_sizzle('feature[var="muc_nonanonymous"]', stanza).length,
    'open': muc_list_sizzle('feature[var="muc_open"]', stanza).length,
    'passwordprotected': muc_list_sizzle('feature[var="muc_passwordprotected"]', stanza).length,
    'persistent': muc_list_sizzle('feature[var="muc_persistent"]', stanza).length,
    'publicroom': muc_list_sizzle('feature[var="muc_publicroom"]', stanza).length,
    'semianonymous': muc_list_sizzle('feature[var="muc_semianonymous"]', stanza).length,
    'temporary': muc_list_sizzle('feature[var="muc_temporary"]', stanza).length,
    'unmoderated': muc_list_sizzle('feature[var="muc_unmoderated"]', stanza).length,
    'label_desc': i18n_('Description:'),
    'label_jid': i18n_('Groupchat Address (JID):'),
    'label_occ': i18n_('Participants:'),
    'label_features': i18n_('Features:'),
    'label_requires_auth': i18n_('Requires authentication'),
    'label_hidden': i18n_('Hidden'),
    'label_requires_invite': i18n_('Requires an invitation'),
    'label_moderated': i18n_('Moderated'),
    'label_non_anon': i18n_('Non-anonymous'),
    'label_open_room': i18n_('Open'),
    'label_permanent_room': i18n_('Permanent'),
    'label_public': i18n_('Public'),
    'label_semi_anon': i18n_('Semi-anonymous'),
    'label_temp_room': i18n_('Temporary'),
    'label_unmoderated': i18n_('Unmoderated')
  }));
}
/**
 * Show/hide extra information about a groupchat in a listing.
 * @function toggleRoomInfo
 * @param { Event }
 */


function toggleRoomInfo(ev) {
  const parent_el = muc_list_u.ancestor(ev.target, '.room-item');
  const div_el = parent_el.querySelector('div.room-info');

  if (div_el) {
    muc_list_u.slideIn(div_el).then(muc_list_u.removeElement);
    parent_el.querySelector('a.room-info').classList.remove('selected');
  } else {
    parent_el.insertAdjacentElement('beforeend', muc_list_u.getElementFromTemplateResult(spinner()));
    converse_core_api.disco.info(ev.target.getAttribute('data-room-jid'), null).then(stanza => insertRoomInfo(parent_el, stanza)).catch(e => headless_log.error(e));
  }
}

/* harmony default export */ var muc_list = (BootstrapModal.extend({
  id: "list-chatrooms-modal",

  initialize() {
    this.items = [];
    this.loading_items = false;
    BootstrapModal.prototype.initialize.apply(this, arguments);

    if (converse_core_api.settings.get('muc_domain') && !this.model.get('muc_domain')) {
      this.model.save('muc_domain', converse_core_api.settings.get('muc_domain'));
    }

    this.listenTo(this.model, 'change:muc_domain', this.onDomainChange);
    this.el.addEventListener('shown.bs.modal', () => converse_core_api.settings.get('locked_muc_domain') ? this.updateRoomsList() : this.el.querySelector('input[name="server"]').focus());
  },

  toHTML() {
    const muc_domain = this.model.get('muc_domain') || converse_core_api.settings.get('muc_domain');
    return list_chatrooms_modal(Object.assign(this.model.toJSON(), {
      'show_form': !converse_core_api.settings.get('locked_muc_domain'),
      'server_placeholder': muc_domain ? muc_domain : i18n_('conference.example.org'),
      'items': this.items,
      'loading_items': this.loading_items,
      'openRoom': ev => this.openRoom(ev),
      'setDomainFromEvent': ev => this.setDomainFromEvent(ev),
      'submitForm': ev => this.showRooms(ev),
      'toggleRoomInfo': ev => this.toggleRoomInfo(ev)
    }));
  },

  openRoom(ev) {
    ev.preventDefault();
    const jid = ev.target.getAttribute('data-room-jid');
    const name = ev.target.getAttribute('data-room-name');
    this.modal.hide();
    converse_core_api.rooms.open(jid, {
      'name': name
    }, true);
  },

  toggleRoomInfo(ev) {
    ev.preventDefault();
    toggleRoomInfo(ev);
  },

  onDomainChange() {
    converse_core_api.settings.get('auto_list_rooms') && this.updateRoomsList();
  },

  /**
   * Handle the IQ stanza returned from the server, containing
   * all its public groupchats.
   * @private
   * @method _converse.ChatRoomView#onRoomsFound
   * @param { HTMLElement } iq
   */
  onRoomsFound(iq) {
    this.loading_items = false;
    const rooms = iq ? muc_list_sizzle('query item', iq) : [];

    if (rooms.length) {
      this.model.set({
        'feedback_text': i18n_('Groupchats found')
      }, {
        'silent': true
      });
      this.items = rooms.map(utils_stanza.getAttributes);
    } else {
      this.items = [];
      this.model.set({
        'feedback_text': i18n_('No groupchats found')
      }, {
        'silent': true
      });
    }

    this.render();
    return true;
  },

  /**
   * Send an IQ stanza to the server asking for all groupchats
   * @private
   * @method _converse.ChatRoomView#updateRoomsList
   */
  updateRoomsList() {
    const iq = muc_list_$iq({
      'to': this.model.get('muc_domain'),
      'from': converse_core_converse.connection.jid,
      'type': "get"
    }).c("query", {
      xmlns: muc_list_Strophe.NS.DISCO_ITEMS
    });
    converse_core_api.sendIQ(iq).then(iq => this.onRoomsFound(iq)).catch(() => this.onRoomsFound());
  },

  showRooms(ev) {
    ev.preventDefault();
    this.loading_items = true;
    this.render();
    const data = new FormData(ev.target);
    this.model.setDomain(data.get('server'));
    this.updateRoomsList();
  },

  setDomainFromEvent(ev) {
    this.model.setDomain(ev.target.value);
  },

  setNick(ev) {
    this.model.save({
      nick: ev.target.value
    });
  }

}));
// CONCATENATED MODULE: ./src/templates/moderator_tools_modal.js





function getRoleHelpText(role) {
  if (role === 'moderator') {
    return i18n_("Moderators are privileged users who can change the roles of other users (except those with admin or owner affiliations.");
  } else if (role === 'participant') {
    return i18n_("The default role, implies that you can read and write messages.");
  } else if (role == 'visitor') {
    return i18n_("Visitors aren't allowed to write messages in a moderated multi-user chat.");
  }
}

function getAffiliationHelpText(aff) {
  if (aff === 'owner') {
    return i18n_("Owner is the highest affiliation. Owners can modify roles and affiliations of all other users.");
  } else if (aff === 'admin') {
    return i18n_("Admin is the 2nd highest affiliation. Admins can modify roles and affiliations of all other users except owners.");
  } else if (aff === 'outcast') {
    return i18n_("To ban a user, you give them the affiliation of \"outcast\".");
  }
}

const role_option = o => lit_html_html`
    <option value="${o.item || ''}"
            ?selected=${o.item === o.role}
            title="${getRoleHelpText(o.item)}">${o.item}</option>
`;

const affiliation_option = o => lit_html_html`
    <option value="${o.item || ''}"
            ?selected=${o.item === o.affiliation}
            title="${getAffiliationHelpText(o.item)}">${o.item}</option>
`;

const tpl_set_role_form = o => {
  const i18n_change_role = i18n_('Change role');

  const i18n_new_role = i18n_('New Role');

  const i18n_reason = i18n_('Reason');

  return lit_html_html`
        <form class="role-form hidden" @submit=${o.assignRole}>
            <div class="form-group">
                <input type="hidden" name="jid" value="${o.item.jid}"/>
                <input type="hidden" name="nick" value="${o.item.nick}"/>
                <div class="row">
                    <div class="col">
                        <label><strong>${i18n_new_role}:</strong></label>
                        <select class="custom-select select-role" name="role">
                            ${o.assignable_roles.map(role => lit_html_html`<option value="${role}" ?selected=${role === o.item.role}>${role}</option>`)}
                        </select>
                    </div>
                    <div class="col">
                        <label><strong>${i18n_reason}:</strong></label>
                        <input class="form-control" type="text" name="reason"/>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-primary" value="${i18n_change_role}"/>
            </div>
        </form>
    `;
};

const role_list_item = o => lit_html_html`
    <li class="list-group-item" data-nick="${o.item.nick}">
        <ul class="list-group">
            <li class="list-group-item active">
                <div><strong>JID:</strong> ${o.item.jid}</div>
            </li>
            <li class="list-group-item">
                <div><strong>Nickname:</strong> ${o.item.nick}</div>
            </li>
            <li class="list-group-item">
                <div><strong>Role:</strong> ${o.item.role} ${o.assignable_roles.length ? lit_html_html`<a href="#" data-form="role-form" class="toggle-form right fa fa-wrench" @click=${o.toggleForm}></a>` : ''}</div>
                ${o.assignable_roles.length ? tpl_set_role_form(o) : ''}
            </li>
        </ul>
    </li>
`;

const tpl_set_affiliation_form = o => {
  const i18n_change_affiliation = i18n_('Change affiliation');

  const i18n_new_affiliation = i18n_('New affiliation');

  const i18n_reason = i18n_('Reason');

  return lit_html_html`
        <form class="affiliation-form hidden" @submit=${o.assignAffiliation}>
            <div class="form-group">
                <input type="hidden" name="jid" value="${o.item.jid}"/>
                <input type="hidden" name="nick" value="${o.item.nick}"/>
                <div class="row">
                    <div class="col">
                        <label><strong>${i18n_new_affiliation}:</strong></label>
                        <select class="custom-select select-affiliation" name="affiliation">
                            ${o.assignable_affiliations.map(aff => lit_html_html`<option value="${aff}" ?selected=${aff === o.item.affiliation}>${aff}</option>`)}
                        </select>
                    </div>
                    <div class="col">
                        <label><strong>${i18n_reason}:</strong></label>
                        <input class="form-control" type="text" name="reason"/>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-primary" name="change" value="${i18n_change_affiliation}"/>
            </div>
        </form>
    `;
};

const affiliation_list_item = o => lit_html_html`
    <li class="list-group-item" data-nick="${o.item.nick}">
        <ul class="list-group">
            <li class="list-group-item active">
                <div><strong>JID:</strong> ${o.item.jid}</div>
            </li>
            <li class="list-group-item">
                <div><strong>Nickname:</strong> ${o.item.nick}</div>
            </li>
            <li class="list-group-item">
                <div><strong>Affiliation:</strong> ${o.item.affiliation} ${o.assignable_affiliations.length ? lit_html_html`<a href="#" data-form="affiliation-form" class="toggle-form right fa fa-wrench" @click=${o.toggleForm}></a>` : ''}</div>
                ${o.assignable_affiliations.length ? tpl_set_affiliation_form(o) : ''}
            </li>
        </ul>
    </li>
`;

const tpl_navigation = o => lit_html_html`
    <ul class="nav nav-pills justify-content-center">
        <li role="presentation" class="nav-item">
            <a class="nav-link active" id="affiliations-tab" href="#affiliations-tabpanel" aria-controls="affiliations-tabpanel" role="tab" data-toggle="tab" @click=${o.switchTab}>Affiliations</a>
        </li>
        <li role="presentation" class="nav-item">
            <a class="nav-link" id="roles-tab" href="#roles-tabpanel" aria-controls="roles-tabpanel" role="tab" data-toggle="tab" @click=${o.switchTab}>Roles</a>
        </li>
    </ul>
`;

/* harmony default export */ var moderator_tools_modal = (o => {
  const i18n_affiliation = i18n_('Affiliation');

  const i18n_moderator_tools = i18n_('Moderator Tools');

  const i18n_no_users_with_aff = i18n_('No users with that affiliation found.');

  const i18n_no_users_with_role = i18n_('No users with that role found.');

  const i18n_filter = i18n_('Type here to filter the search results');

  const i18n_role = i18n_('Role');

  const i18n_show_users = i18n_('Show users');

  const i18n_helptext_role = i18n_("Roles are assigned to users to grant or deny them certain abilities in a multi-user chat. " + "They're assigned either explicitly or implicitly as part of an affiliation. " + "A role that's not due to an affiliation, is only valid for the duration of the user's session.");

  const i18n_helptext_affiliation = i18n_("An affiliation is a long-lived entitlement which typically implies a certain role and which " + "grants privileges and responsibilities. For example admins and owners automatically have the " + "moderator role.");

  const show_both_tabs = o.queryable_roles.length && o.queryable_affiliations.length;
  return lit_html_html`
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="converse-modtools-modal-label">${i18n_moderator_tools}</h5>
                ${modal_header_close_button}
            </div>
            <div class="modal-body d-flex flex-column">
                <span class="modal-alert"></span>

                ${show_both_tabs ? tpl_navigation(o) : ''}

                <div class="tab-content">
                    <div class="tab-pane tab-pane--columns ${o.queryable_affiliations.length ? 'active' : ''}" id="affiliations-tabpanel" role="tabpanel" aria-labelledby="affiliations-tab">
                        <form class="converse-form query-affiliation" @submit=${o.queryAffiliation}>
                            <p class="helptext pb-3">${i18n_helptext_affiliation}</p>
                            <div class="form-group">
                                <label for="affiliation">
                                    <strong>${i18n_affiliation}:</strong>
                                </label>
                                <div class="row">
                                    <div class="col">
                                        <select class="custom-select select-affiliation" name="affiliation">
                                            ${o.queryable_affiliations.map(item => affiliation_option(Object.assign({
    item
  }, o)))}
                                        </select>
                                    </div>
                                    <div class="col">
                                        <input type="submit" class="btn btn-primary" name="users_with_affiliation" value="${i18n_show_users}"/>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col mt-3">
                                        ${Array.isArray(o.users_with_affiliation) && o.users_with_affiliation.length > 5 ? lit_html_html`<input class="form-control" .value="${o.affiliations_filter}" @keyup=${o.filterAffiliationResults} type="text" name="filter" placeholder="${i18n_filter}"/>` : ''}
                                    </div>
                                </div>

                                ${getAffiliationHelpText(o.affiliation) ? lit_html_html`<div class="row"><div class="col pt-2"><p class="helptext pb-3">${getAffiliationHelpText(o.affiliation)}</p></div></div>` : ''}
                            </div>
                        </form>
                        <div class="scrollable-container">
                            <ul class="list-group list-group--users">
                                ${o.loading_users_with_affiliation ? lit_html_html`<li class="list-group-item"> ${spinner()} </li>` : ''}
                                ${Array.isArray(o.users_with_affiliation) && o.users_with_affiliation.length === 0 ? lit_html_html`<li class="list-group-item">${i18n_no_users_with_aff}</li>` : ''}

                                ${o.users_with_affiliation instanceof Error ? lit_html_html`<li class="list-group-item">${o.users_with_affiliation.message}</li>` : (o.users_with_affiliation || []).map(item => (item.nick || item.jid).match(new RegExp(o.affiliations_filter, 'i')) ? affiliation_list_item(Object.assign({
    item
  }, o)) : '')}
                            </ul>
                        </div>
                    </div>

                    <div class="tab-pane tab-pane--columns ${!show_both_tabs && o.queryable_roles.length ? 'active' : ''}" id="roles-tabpanel" role="tabpanel" aria-labelledby="roles-tab">
                        <form class="converse-form query-role" @submit=${o.queryRole}>
                            <p class="helptext pb-3">${i18n_helptext_role}</p>
                            <div class="form-group">
                                <label for="role"><strong>${i18n_role}:</strong></label>
                                <div class="row">
                                    <div class="col">
                                        <select class="custom-select select-role" name="role">
                                            ${o.queryable_roles.map(item => role_option(Object.assign({
    item
  }, o)))}
                                        </select>
                                    </div>
                                    <div class="col">
                                        <input type="submit" class="btn btn-primary" name="users_with_role" value="${i18n_show_users}"/>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col mt-3">
                                        ${Array.isArray(o.users_with_role) && o.users_with_role.length > 5 ? lit_html_html`<input class="form-control" .value="${o.roles_filter}" @keyup=${o.filterRoleResults} type="text" name="filter" placeholder="${i18n_filter}"/>` : ''}
                                    </div>
                                </div>

                                ${getRoleHelpText(o.role) ? lit_html_html`<div class="row"><div class="col pt-2"><p class="helptext pb-3">${getRoleHelpText(o.role)}</p></div></div>` : ''}
                            </div>
                        </form>
                        <div class="scrollable-container">
                            <ul class="list-group list-group--users">
                                ${o.loading_users_with_role ? lit_html_html`<li class="list-group-item"> ${spinner()} </li>` : ''}
                                ${o.users_with_role && o.users_with_role.length === 0 ? lit_html_html`<li class="list-group-item">${i18n_no_users_with_role}</li>` : ''}
                                ${(o.users_with_role || []).map(item => item.nick.match(o.roles_filter) ? role_list_item(Object.assign({
    item
  }, o)) : '')}
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>`;
});
// CONCATENATED MODULE: ./src/modals/moderator-tools.js






const {
  Strophe: moderator_tools_Strophe,
  sizzle: moderator_tools_sizzle,
  u: moderator_tools_u
} = converse.env;

let moderator_tools_converse;

/* harmony default export */ var moderator_tools = (BootstrapModal.extend({
  id: "converse-modtools-modal",

  initialize(attrs) {
    moderator_tools_converse = attrs._converse;
    this.chatroomview = attrs.chatroomview;
    BootstrapModal.prototype.initialize.apply(this, arguments);
    this.affiliations_filter = '';
    this.roles_filter = '';
    this.listenTo(this.model, 'change:role', () => {
      this.users_with_role = this.chatroomview.model.getOccupantsWithRole(this.model.get('role'));
      this.render();
    });
    this.listenTo(this.model, 'change:affiliation', async () => {
      this.loading_users_with_affiliation = true;
      this.users_with_affiliation = null;
      this.render();
      const chatroom = this.chatroomview.model;
      const affiliation = this.model.get('affiliation');

      if (this.shouldFetchAffiliationsList()) {
        this.users_with_affiliation = await chatroom.getAffiliationList(affiliation);
      } else {
        this.users_with_affiliation = chatroom.getOccupantsWithAffiliation(affiliation);
      }

      this.loading_users_with_affiliation = false;
      this.render();
    });
  },

  toHTML() {
    const occupant = this.chatroomview.model.occupants.findWhere({
      'jid': moderator_tools_converse.bare_jid
    });
    return moderator_tools_modal(Object.assign(this.model.toJSON(), {
      'affiliations_filter': this.affiliations_filter,
      'assignAffiliation': ev => this.assignAffiliation(ev),
      'assignRole': ev => this.assignRole(ev),
      'assignable_affiliations': this.getAssignableAffiliations(occupant),
      'assignable_roles': this.getAssignableRoles(occupant),
      'filterAffiliationResults': ev => this.filterAffiliationResults(ev),
      'filterRoleResults': ev => this.filterRoleResults(ev),
      'loading_users_with_affiliation': this.loading_users_with_affiliation,
      'queryAffiliation': ev => this.queryAffiliation(ev),
      'queryRole': ev => this.queryRole(ev),
      'queryable_affiliations': AFFILIATIONS.filter(a => !moderator_tools_converse.modtools_disable_query.includes(a)),
      'queryable_roles': ROLES.filter(a => !moderator_tools_converse.modtools_disable_query.includes(a)),
      'roles_filter': this.roles_filter,
      'switchTab': ev => this.switchTab(ev),
      'toggleForm': ev => this.toggleForm(ev),
      'users_with_affiliation': this.users_with_affiliation,
      'users_with_role': this.users_with_role
    }));
  },

  getAssignableAffiliations(occupant) {
    let disabled = converse_core_api.settings.get('modtools_disable_assign');

    if (!Array.isArray(disabled)) {
      disabled = disabled ? AFFILIATIONS : [];
    }

    if (occupant.get('affiliation') === 'owner') {
      return AFFILIATIONS.filter(a => !disabled.includes(a));
    } else if (occupant.get('affiliation') === 'admin') {
      return AFFILIATIONS.filter(a => !['owner', 'admin', ...disabled].includes(a));
    } else {
      return [];
    }
  },

  getAssignableRoles(occupant) {
    let disabled = converse_core_api.settings.get('modtools_disable_assign');

    if (!Array.isArray(disabled)) {
      disabled = disabled ? ROLES : [];
    }

    if (occupant.get('role') === 'moderator') {
      return ROLES.filter(r => !disabled.includes(r));
    } else {
      return [];
    }
  },

  shouldFetchAffiliationsList() {
    const affiliation = this.model.get('affiliation');

    if (affiliation === 'none') {
      return false;
    }

    const chatroom = this.chatroomview.model;
    const auto_fetched_affs = chatroom.occupants.getAutoFetchedAffiliationLists();

    if (auto_fetched_affs.includes(affiliation)) {
      return false;
    } else {
      return true;
    }
  },

  toggleForm(ev) {
    ev.stopPropagation();
    ev.preventDefault();
    const form_class = ev.target.getAttribute('data-form');
    const form = moderator_tools_u.ancestor(ev.target, '.list-group-item').querySelector(`.${form_class}`);

    if (moderator_tools_u.hasClass('hidden', form)) {
      moderator_tools_u.removeClass('hidden', form);
    } else {
      moderator_tools_u.addClass('hidden', form);
    }
  },

  filterRoleResults(ev) {
    this.roles_filter = ev.target.value;
    this.render();
  },

  filterAffiliationResults(ev) {
    this.affiliations_filter = ev.target.value;
    this.render();
  },

  queryRole(ev) {
    ev.stopPropagation();
    ev.preventDefault();
    const data = new FormData(ev.target);
    const role = data.get('role');
    this.model.set({
      'role': null
    }, {
      'silent': true
    });
    this.model.set({
      'role': role
    });
  },

  queryAffiliation(ev) {
    ev.stopPropagation();
    ev.preventDefault();
    const data = new FormData(ev.target);
    const affiliation = data.get('affiliation');
    this.model.set({
      'affiliation': null
    }, {
      'silent': true
    });
    this.model.set({
      'affiliation': affiliation
    });
  },

  async assignAffiliation(ev) {
    ev.stopPropagation();
    ev.preventDefault();
    const data = new FormData(ev.target);
    const affiliation = data.get('affiliation');
    const attrs = {
      'jid': data.get('jid'),
      'reason': data.get('reason')
    };
    const current_affiliation = this.model.get('affiliation');

    try {
      await this.chatroomview.model.setAffiliation(affiliation, [attrs]);
    } catch (e) {
      if (e === null) {
        this.alert(i18n_('Timeout error while trying to set the affiliation'), 'danger');
      } else if (moderator_tools_sizzle(`not-allowed[xmlns="${moderator_tools_Strophe.NS.STANZAS}"]`, e).length) {
        this.alert(i18n_('Sorry, you\'re not allowed to make that change'), 'danger');
      } else {
        this.alert(i18n_('Sorry, something went wrong while trying to set the affiliation'), 'danger');
      }

      headless_log.error(e);
      return;
    }

    this.alert(i18n_('Affiliation changed'), 'primary');
    await this.chatroomview.model.occupants.fetchMembers();
    this.model.set({
      'affiliation': null
    }, {
      'silent': true
    });
    this.model.set({
      'affiliation': current_affiliation
    });
  },

  assignRole(ev) {
    ev.stopPropagation();
    ev.preventDefault();
    const data = new FormData(ev.target);
    const occupant = this.chatroomview.model.getOccupant(data.get('jid') || data.get('nick'));
    const role = data.get('role');
    const reason = data.get('reason');
    const current_role = this.model.get('role');
    this.chatroomview.model.setRole(occupant, role, reason, () => {
      this.alert(i18n_('Role changed'), 'primary');
      this.model.set({
        'role': null
      }, {
        'silent': true
      });
      this.model.set({
        'role': current_role
      });
    }, e => {
      if (moderator_tools_sizzle(`not-allowed[xmlns="${moderator_tools_Strophe.NS.STANZAS}"]`, e).length) {
        this.alert(i18n_('You\'re not allowed to make that change'), 'danger');
      } else {
        this.alert(i18n_('Sorry, something went wrong while trying to set the role'), 'danger');

        if (moderator_tools_u.isErrorObject(e)) {
          headless_log.error(e);
        }
      }
    });
  }

}));
// CONCATENATED MODULE: ./src/templates/chatroom_details_modal.js






const chatroom_details_modal_subject = o => {
  const i18n_topic = i18n_('Topic');

  const i18n_topic_author = i18n_('Topic author');

  return lit_html_html`
        <p class="room-info"><strong>${i18n_topic}</strong>: ${unsafeHTML(xss_default.a.filterXSS(o.subject.text, {
    'whiteList': {}
  }))}</p>
            <p class="room-info"><strong>${i18n_topic_author}</strong>: ${o.subject && o.subject.author}</p>
    `;
};

/* harmony default export */ var chatroom_details_modal = (o => {
  const i18n_address = i18n_('Groupchat address (JID)');

  const i18n_archiving = i18n_('Message archiving');

  const i18n_archiving_help = i18n_('Messages are archived on the server');

  const i18n_desc = i18n_('Description');

  const i18n_features = i18n_('Features');

  const i18n_hidden = i18n_('Hidden');

  const i18n_hidden_help = i18n_('This groupchat is not publicly searchable');

  const i18n_members_help = i18n_('This groupchat is restricted to members only');

  const i18n_members_only = i18n_('Members only');

  const i18n_moderated = i18n_('Moderated');

  const i18n_moderated_help = i18n_('Participants entering this groupchat need to request permission to write');

  const i18n_name = i18n_('Name');

  const i18n_no_pass_help = i18n_('This groupchat does not require a password upon entry');

  const i18n_no_password_required = i18n_('No password required');

  const i18n_not_anonymous = i18n_('Not anonymous');

  const i18n_not_anonymous_help = i18n_('All other groupchat participants can see your XMPP address');

  const i18n_not_moderated = i18n_('Not moderated');

  const i18n_not_moderated_help = i18n_('Participants entering this groupchat can write right away');

  const i18n_online_users = i18n_('Online users');

  const i18n_open = i18n_('Open');

  const i18n_open_help = i18n_('Anyone can join this groupchat');

  const i18n_password_help = i18n_('This groupchat requires a password before entry');

  const i18n_password_protected = i18n_('Password protected');

  const i18n_persistent = i18n_('Persistent');

  const i18n_persistent_help = i18n_('This groupchat persists even if it\'s unoccupied');

  const i18n_public = i18n_('Public');

  const i18n_semi_anon = i18n_('Semi-anonymous');

  const i18n_semi_anon_help = i18n_('Only moderators can see your XMPP address');

  const i18n_temporary = i18n_('Temporary');

  const i18n_temporary_help = i18n_('This groupchat will disappear once the last person leaves');

  return lit_html_html`
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="room-details-modal-label">${o.display_name}</h5>
                    ${modal_header_close_button}
                </div>
                <div class="modal-body">
                    <span class="modal-alert"></span>
                    <div class="room-info">
                        <p class="room-info"><strong>${i18n_name}</strong>: ${o.name}</p>
                        <p class="room-info"><strong>${i18n_address}</strong>: ${o.jid}</p>
                        <p class="room-info"><strong>${i18n_desc}</strong>: ${o.config.description}</p>
                        ${o.subject ? chatroom_details_modal_subject(o) : ''}
                        <p class="room-info"><strong>${i18n_online_users}</strong>: ${o.num_occupants}</p>
                        <p class="room-info"><strong>${i18n_features}</strong>:
                            <div class="chatroom-features">
                            <ul class="features-list">
                                ${o.features.passwordprotected ? lit_html_html`<li class="feature" ><span class="fa fa-lock"></span>${i18n_password_protected} - <em>${i18n_password_help}</em></li>` : ''}
                                ${o.features.unsecured ? lit_html_html`<li class="feature" ><span class="fa fa-unlock"></span>${i18n_no_password_required} - <em>${i18n_no_pass_help}</em></li>` : ''}
                                ${o.features.hidden ? lit_html_html`<li class="feature" ><span class="fa fa-eye-slash"></span>${i18n_hidden} - <em>${i18n_hidden_help}</em></li>` : ''}
                                ${o.features.public_room ? lit_html_html`<li class="feature" ><span class="fa fa-eye"></span>${i18n_public} - <em>${o.__('This groupchat is publicly searchable')}</em></li>` : ''}
                                ${o.features.membersonly ? lit_html_html`<li class="feature" ><span class="fa fa-address-book"></span>${i18n_members_only} - <em>${i18n_members_help}</em></li>` : ''}
                                ${o.features.open ? lit_html_html`<li class="feature" ><span class="fa fa-globe"></span>${i18n_open} - <em>${i18n_open_help}</em></li>` : ''}
                                ${o.features.persistent ? lit_html_html`<li class="feature" ><span class="fa fa-save"></span>${i18n_persistent} - <em>${i18n_persistent_help}</em></li>` : ''}
                                ${o.features.temporary ? lit_html_html`<li class="feature" ><span class="fa fa-snowflake-o"></span>${i18n_temporary} - <em>${i18n_temporary_help}</em></li>` : ''}
                                ${o.features.nonanonymous ? lit_html_html`<li class="feature" ><span class="fa fa-id-card"></span>${i18n_not_anonymous} - <em>${i18n_not_anonymous_help}</em></li>` : ''}
                                ${o.features.semianonymous ? lit_html_html`<li class="feature" ><span class="fa fa-user-secret"></span>${i18n_semi_anon} - <em>${i18n_semi_anon_help}</em></li>` : ''}
                                ${o.features.moderated ? lit_html_html`<li class="feature" ><span class="fa fa-gavel"></span>${i18n_moderated} - <em>${i18n_moderated_help}</em></li>` : ''}
                                ${o.features.unmoderated ? lit_html_html`<li class="feature" ><span class="fa fa-info-circle"></span>${i18n_not_moderated} - <em>${i18n_not_moderated_help}</em></li>` : ''}
                                ${o.features.mam_enabled ? lit_html_html`<li class="feature" ><span class="fa fa-database"></span>${i18n_archiving} - <em>${i18n_archiving_help}</em></li>` : ''}
                            </ul>
                            </div>
                        </p>
                    </div>
                </div>
                <div class="modal-footer">${modal_close_button}</div>
            </div>
        </div>
    `;
});
// CONCATENATED MODULE: ./src/modals/muc-details.js



/* harmony default export */ var muc_details = (BootstrapModal.extend({
  id: "room-details-modal",

  initialize() {
    BootstrapModal.prototype.initialize.apply(this, arguments);
    this.listenTo(this.model, 'change', this.render);
    this.listenTo(this.model.features, 'change', this.render);
    this.listenTo(this.model.occupants, 'add', this.render);
    this.listenTo(this.model.occupants, 'change', this.render);
  },

  toHTML() {
    return chatroom_details_modal(Object.assign(this.model.toJSON(), {
      'config': this.model.config.toJSON(),
      'display_name': i18n_('Groupchat info for %1$s', this.model.getDisplayName()),
      'features': this.model.features.toJSON(),
      'num_occupants': this.model.occupants.length
    }));
  }

}));
// CONCATENATED MODULE: ./src/templates/chatroom.js

/* harmony default export */ var templates_chatroom = (o => lit_html_html`
    <div class="flyout box-flyout">
        <div class="chat-head chat-head-chatroom row no-gutters"></div>
        <div class="chat-body chatroom-body row no-gutters">
            <div class="chat-area col">
                <div class="chat-content ${o.show_send_button ? 'chat-content-sendbutton' : ''}" aria-live="polite">
                    <div class="chat-content__messages" @scroll=${o.markScrolled}></div>
                    <div class="chat-content__help"></div>
                </div>
                <div class="bottom-panel"></div>
            </div>
            <div class="disconnect-container hidden"></div>
            <converse-muc-sidebar class="occupants col-md-3 col-4 ${o.sidebar_hidden ? 'hidden' : ''}"
                .occupants=${o.occupants}
                .chatroom=${o.model}></converse-muc-sidebar>
        </div>
    </div>
`);
// CONCATENATED MODULE: ./src/templates/muc_bottom_panel.js



const tpl_can_edit = () => lit_html_html`
    <div class="emoji-picker__container dropup"></div>
    <div class="message-form-container">`;

/* harmony default export */ var muc_bottom_panel = (o => {
  const i18n_not_allowed = i18n_("You're not allowed to send messages in this room");

  if (o.entered) {
    return o.can_edit ? tpl_can_edit() : lit_html_html`<div class="muc-bottom-panel">${i18n_not_allowed}</div>`;
  } else {
    return lit_html_html`<div class="muc-bottom-panel"></div>`;
  }
});
// CONCATENATED MODULE: ./src/templates/muc_destroyed.js



const tpl_moved = jid => {
  const i18n_moved = i18n_('The conversation has moved. Click below to enter.');

  return lit_html_html`
        <p class="moved-label">${i18n_moved}</p>
        <p class="moved-link"><a class="switch-chat" href="#">${jid}</a></p>`;
};

/* harmony default export */ var muc_destroyed = ((jid, reason) => {
  const i18n_non_existent = i18n_('This groupchat no longer exists');

  return lit_html_html`
        <div class="alert alert-danger">
            <h3 class="alert-heading disconnect-msg">${i18n_non_existent}</h3>
            ${reason ? lit_html_html`<p class="destroyed-reason">"${reason}"</p>` : ''}
            ${jid ? tpl_moved(jid) : ''}
        </div>`;
});
// CONCATENATED MODULE: ./src/templates/muc_disconnect.js

/* harmony default export */ var muc_disconnect = (messages => {
  return lit_html_html`
        <div class="alert alert-danger">
            <h3 class="alert-heading disconnect-msg">${messages[0]}</h3>
            ${messages.slice(1).map(m => lit_html_html`<p class="disconnect-msg">${m}</p>`)}
        </div>`;
});
// CONCATENATED MODULE: ./src/templates/chatroom_head.js





const chatroom_head_u = converse.env.utils;

const chatroom_head_tpl_standalone_btns = o => o.standalone_btns.reverse().map(b => until(b, ''));

/* harmony default export */ var chatroom_head = (o => {
  const i18n_hide_topic = i18n_('Hide the groupchat topic');

  const i18n_bookmarked = i18n_('This groupchat is bookmarked');

  const subject = o.subject ? chatroom_head_u.addHyperlinks(o.subject.text) : '';
  const show_subject = subject && !o.subject_hidden;
  return lit_html_html`
        <div class="chatbox-title ${show_subject ? '' : "chatbox-title--no-desc"}">
            ${!o._converse.api.settings.get("singleton") ? lit_html_html`<div class="chatbox-navback"><i class="fa fa-arrow-left"></i></div>` : ''}
            <div class="chatbox-title__text" title="${o._converse.locked_muc_domain !== 'hidden' ? o.jid : ''}">${o.title}
                ${o.bookmarked ? lit_html_html`<i class="fa fa-bookmark chatbox-title__text--bookmarked" title="${i18n_bookmarked}"></i>` : ''}
            </div>
            <div class="chatbox-title__buttons row no-gutters">
                ${o.standalone_btns.length ? chatroom_head_tpl_standalone_btns(o) : ''}
                ${o.dropdown_btns.length ? lit_html_html`<converse-dropdown .items=${o.dropdown_btns}></converse-dropdown>` : ''}
            </div>
        </div>
        ${show_subject ? lit_html_html`<p class="chat-head__desc" title="${i18n_hide_topic}">${subject}</p>` : ''}
    `;
});
// CONCATENATED MODULE: ./src/templates/muc_nickname_form.js



/* harmony default export */ var muc_nickname_form = (o => {
  const i18n_nickname = i18n_('Nickname');

  const i18n_join = i18n_('Enter groupchat');

  const i18n_heading = converse_core_api.settings.get('muc_show_logs_before_join') ? i18n_('Choose a nickname to enter') : i18n_('Please choose your nickname');
  return lit_html_html`
        <div class="chatroom-form-container muc-nickname-form">
            <form class="converse-form chatroom-form converse-centered-form">
                <fieldset class="form-group">
                    <label>${i18n_heading}</label>
                    <p class="validation-message">${o.nickname_validation_message}</p>
                    <input type="text"
                        required="required"
                        name="nick"
                        value="${o.nick || ''}"
                        class="form-control ${o.nickname_validation_message ? 'error' : ''}"
                        placeholder="${i18n_nickname}"/>
                </fieldset>
                <fieldset class="form-group">
                    <input type="submit" class="btn btn-primary" name="join" value="${i18n_join}"/>
                </fieldset>
            </form>
        </div>`;
});
// CONCATENATED MODULE: ./src/templates/muc_config_form.js



/* harmony default export */ var muc_config_form = (o => {
  const i18n_save = i18n_('Save');

  const i18n_cancel = i18n_('Cancel');

  return lit_html_html`
        <form class="converse-form chatroom-form" autocomplete="off" @submit=${o.submitConfigForm}>
            <fieldset class="form-group">
                <legend>${o.title}</legend>
                ${o.title !== o.instructions ? lit_html_html`<p class="form-help">${o.instructions}</p>` : ''}
                <!-- Fields are generated internally, with xForm2webForm -->
                ${o.fields.map(field => unsafeHTML(field))}
            </fieldset>
            <fieldset>
                <input type="submit" class="btn btn-primary" value="${i18n_save}">
                <input type="button" class="btn btn-secondary button-cancel" value="${i18n_cancel}" @click=${o.closeConfigForm}>
            </fieldset>
        </form>
    `;
});
// CONCATENATED MODULE: ./src/templates/muc_password_form.js


/* harmony default export */ var muc_password_form = (o => {
  const i18n_heading = i18n_('This groupchat requires a password');

  const i18n_password = i18n_('Password: ');

  const i18n_submit = i18n_('Submit');

  return lit_html_html`
        <form class="converse-form chatroom-form converse-centered-form" @submit=${o.submitPassword}>
            <fieldset class="form-group">
                <label>${i18n_heading}</label>
                <p class="validation-message">${o.validation_message}</p>
                <input class="hidden-username" type="text" autocomplete="username" value="${o.jid}"></input>
                <input type="password"
                    name="password"
                    required="required"
                    class="form-control ${o.validation_message ? 'error' : ''}"
                    placeholder="${i18n_password}"/>
            </fieldset>
            <fieldset class="form-group">
                <input class="btn btn-primary" type="submit" value="${i18n_submit}"/>
            </fieldset>
        </form>
    `;
});
// CONCATENATED MODULE: ./src/templates/room_panel.js

/* harmony default export */ var room_panel = (o => lit_html_html`
    <div class="d-flex controlbox-padded">
        <span class="w-100 controlbox-heading controlbox-heading--groupchats">${o.heading_chatrooms}</span>
        <a class="controlbox-heading__btn show-list-muc-modal fa fa-list-ul" title="${o.title_list_rooms}" data-toggle="modal" data-target="#list-chatrooms-modal"></a>
        <a class="controlbox-heading__btn show-add-muc-modal fa fa-plus" title="${o.title_new_room}" data-toggle="modal" data-target="#add-chatrooms-modal"></a>
    </div>
    <div class="list-container list-container--openrooms hidden"></div>
    <div class="list-container list-container--bookmarks hidden"></div>`);
// CONCATENATED MODULE: ./src/converse-muc-views.js
/**
 * @module converse-muc-views
 * @copyright 2020, the Converse.js contributors
 * @description XEP-0045 Multi-User Chat Views
 * @license Mozilla Public License (MPLv2)
 */


























const {
  Strophe: converse_muc_views_Strophe,
  sizzle: converse_muc_views_sizzle,
  $pres: converse_muc_views_$pres
} = converse.env;
const converse_muc_views_u = converse.env.utils;
const OWNER_COMMANDS = ['owner'];
const ADMIN_COMMANDS = ['admin', 'ban', 'deop', 'destroy', 'member', 'op', 'revoke'];
const MODERATOR_COMMANDS = ['kick', 'mute', 'voice', 'modtools'];
const VISITOR_COMMANDS = ['nick'];
const COMMAND_TO_ROLE = {
  'deop': 'participant',
  'kick': 'none',
  'mute': 'visitor',
  'op': 'moderator',
  'voice': 'participant'
};
const COMMAND_TO_AFFILIATION = {
  'admin': 'admin',
  'ban': 'outcast',
  'member': 'member',
  'owner': 'owner',
  'revoke': 'none'
};
/**
 * NativeView which renders a groupchat, based upon
 * { @link _converse.ChatBoxView } for normal one-on-one chat boxes.
 * @class
 * @namespace _converse.ChatRoomView
 * @memberOf _converse
 */

const ChatRoomView = ChatBoxView.extend({
  length: 300,
  tagName: 'div',
  className: 'chatbox chatroom hidden',
  is_chatroom: true,
  events: {
    'click .chatbox-navback': 'showControlBox',
    'click .hide-occupants': 'hideOccupants',
    'click .new-msgs-indicator': 'viewUnreadMessages',
    // Arrow functions don't work here because you can't bind a different `this` param to them.
    'click .occupant-nick': function (ev) {
      this.insertIntoTextArea(ev.target.textContent);
    },
    'click .send-button': 'onFormSubmitted',
    'dragover .chat-textarea': 'onDragOver',
    'drop .chat-textarea': 'onDrop',
    'input .chat-textarea': 'inputChanged',
    'keydown .chat-textarea': 'onKeyDown',
    'keyup .chat-textarea': 'onKeyUp',
    'mousedown .dragresize-occupants-left': 'onStartResizeOccupants',
    'paste .chat-textarea': 'onPaste',
    'submit .muc-nickname-form': 'submitNickname'
  },

  async initialize() {
    this.initDebounced();
    this.listenTo(this.model, 'change', lodash_es_debounce(() => this.renderHeading(), 250));
    this.listenTo(this.model, 'change:composing_spoiler', this.renderMessageForm);
    this.listenTo(this.model, 'change:hidden', m => m.get('hidden') ? this.hide() : this.show());
    this.listenTo(this.model, 'change:hidden_occupants', this.onSidebarToggle);
    this.listenTo(this.model, 'configurationNeeded', this.getAndRenderConfigurationForm);
    this.listenTo(this.model, 'destroy', this.hide);
    this.listenTo(this.model, 'show', this.show);
    this.listenTo(this.model.features, 'change:moderated', this.renderBottomPanel);
    this.listenTo(this.model.features, 'change:open', this.renderHeading);
    this.listenTo(this.model.messages, 'rendered', this.maybeScrollDown);
    this.listenTo(this.model.session, 'change:connection_status', this.onConnectionStatusChanged); // Bind so that we can pass it to addEventListener and removeEventListener

    this.onMouseMove = this.onMouseMove.bind(this);
    this.onMouseUp = this.onMouseUp.bind(this);
    await this.render(); // Need to be registered after render has been called.

    this.listenTo(this.model, 'change:show_help_messages', this.renderHelpMessages);
    this.listenTo(this.model.messages, 'add', this.onMessageAdded);
    this.listenTo(this.model.messages, 'change', this.renderChatHistory);
    this.listenTo(this.model.messages, 'remove', this.renderChatHistory);
    this.listenTo(this.model.messages, 'reset', this.renderChatHistory);
    this.listenTo(this.model.notifications, 'change', this.renderNotifications);
    this.model.occupants.forEach(o => this.onOccupantAdded(o));
    this.listenTo(this.model.occupants, 'add', this.onOccupantAdded);
    this.listenTo(this.model.occupants, 'change', this.renderChatHistory);
    this.listenTo(this.model.occupants, 'change:affiliation', this.onOccupantAffiliationChanged);
    this.listenTo(this.model.occupants, 'change:role', this.onOccupantRoleChanged);
    this.listenTo(this.model.occupants, 'change:show', this.showJoinOrLeaveNotification);
    this.listenTo(this.model.occupants, 'remove', this.onOccupantRemoved);
    this.renderChatContent();
    this.insertIntoDOM(); // Register later due to await

    const user_settings = await converse_core_converse.api.user.settings.getModel();
    this.listenTo(user_settings, 'change:mucs_with_hidden_subject', this.renderHeading);
    this.onConnectionStatusChanged();
    this.model.maybeShow();
    this.scrollDown();
    /**
     * Triggered once a { @link _converse.ChatRoomView } has been opened
     * @event _converse#chatRoomViewInitialized
     * @type { _converse.ChatRoomView }
     * @example _converse.api.listen.on('chatRoomViewInitialized', view => { ... });
     */

    converse_core_api.trigger('chatRoomViewInitialized', this);
  },

  async render() {
    const sidebar_hidden = !this.shouldShowSidebar();
    this.el.setAttribute('id', this.model.get('box_id'));
    render_render(templates_chatroom({
      sidebar_hidden,
      'model': this.model,
      'occupants': this.model.occupants,
      'show_sidebar': !this.model.get('hidden_occupants') && this.model.session.get('connection_status') === converse.ROOMSTATUS.ENTERED,
      'markScrolled': ev => this.markScrolled(ev),
      'muc_show_logs_before_join': converse_core_api.settings.get('muc_show_logs_before_join'),
      'show_send_button': converse_core_converse.show_send_button
    }), this.el);
    this.notifications = this.el.querySelector('.chat-content__notifications');
    this.content = this.el.querySelector('.chat-content');
    this.msgs_container = this.el.querySelector('.chat-content__messages');
    this.help_container = this.el.querySelector('.chat-content__help');
    this.renderBottomPanel();

    if (!converse_core_api.settings.get('muc_show_logs_before_join') && this.model.session.get('connection_status') !== converse.ROOMSTATUS.ENTERED) {
      this.showSpinner();
    } // Render header as late as possible since it's async and we
    // want the rest of the DOM elements to be available ASAP.
    // Otherwise e.g. this.notifications is not yet defined when accessed elsewhere.


    await this.renderHeading();
    !this.model.get('hidden') && this.show();
  },

  getNotifications() {
    const actors_per_state = this.model.notifications.toJSON();
    const states = converse_core_api.settings.get('muc_show_join_leave') ? [...converse.CHAT_STATES, ...converse.MUC_TRAFFIC_STATES, ...converse.MUC_ROLE_CHANGES] : converse.CHAT_STATES;
    return states.reduce((result, state) => {
      const existing_actors = actors_per_state[state];

      if (!(existing_actors !== null && existing_actors !== void 0 && existing_actors.length)) {
        return result;
      }

      const actors = existing_actors.map(a => {
        var _this$model$getOccupa;

        return ((_this$model$getOccupa = this.model.getOccupant(a)) === null || _this$model$getOccupa === void 0 ? void 0 : _this$model$getOccupa.getDisplayName()) || a;
      });

      if (actors.length === 1) {
        if (state === 'composing') {
          return `${result}${i18n_('%1$s is typing', actors[0])}\n`;
        } else if (state === 'paused') {
          return `${result}${i18n_('%1$s has stopped typing', actors[0])}\n`;
        } else if (state === converse_core_converse.GONE) {
          return `${result}${i18n_('%1$s has gone away', actors[0])}\n`;
        } else if (state === 'entered') {
          return `${result}${i18n_('%1$s has entered the groupchat', actors[0])}\n`;
        } else if (state === 'exited') {
          return `${result}${i18n_('%1$s has left the groupchat', actors[0])}\n`;
        } else if (state === 'op') {
          return `${result}${i18n_("%1$s is now a moderator", actors[0])}\n`;
        } else if (state === 'deop') {
          return `${result}${i18n_("%1$s is no longer a moderator", actors[0])}\n`;
        } else if (state === 'voice') {
          return `${result}${i18n_("%1$s has been given a voice", actors[0])}\n`;
        } else if (state === 'mute') {
          return `${result}${i18n_("%1$s has been muted", actors[0])}\n`;
        }
      } else if (actors.length > 1) {
        let actors_str;

        if (actors.length > 3) {
          actors_str = `${Array.from(actors).slice(0, 2).join(', ')} and others`;
        } else {
          const last_actor = actors.pop();
          actors_str = i18n_('%1$s and %2$s', actors.join(', '), last_actor);
        }

        if (state === 'composing') {
          return `${result}${i18n_('%1$s are typing', actors_str)}\n`;
        } else if (state === 'paused') {
          return `${result}${i18n_('%1$s have stopped typing', actors_str)}\n`;
        } else if (state === converse_core_converse.GONE) {
          return `${result}${i18n_('%1$s have gone away', actors_str)}\n`;
        } else if (state === 'entered') {
          return `${result}${i18n_('%1$s have entered the groupchat', actors_str)}\n`;
        } else if (state === 'exited') {
          return `${result}${i18n_('%1$s have left the groupchat', actors_str)}\n`;
        } else if (state === 'op') {
          return `${result}${i18n_("%1$s are now moderators", actors[0])}\n`;
        } else if (state === 'deop') {
          return `${result}${i18n_("%1$s are no longer moderators", actors[0])}\n`;
        } else if (state === 'voice') {
          return `${result}${i18n_("%1$s have been given voices", actors[0])}\n`;
        } else if (state === 'mute') {
          return `${result}${i18n_("%1$s have been muted", actors[0])}\n`;
        }
      }

      return result;
    }, '');
  },

  getHelpMessages() {
    const setting = converse_core_api.settings.get("muc_disable_slash_commands");
    const disabled_commands = Array.isArray(setting) ? setting : [];
    return [`<strong>/admin</strong>: ${i18n_("Change user's affiliation to admin")}`, `<strong>/ban</strong>: ${i18n_('Ban user by changing their affiliation to outcast')}`, `<strong>/clear</strong>: ${i18n_('Clear the chat area')}`, `<strong>/close</strong>: ${i18n_('Close this groupchat')}`, `<strong>/deop</strong>: ${i18n_('Change user role to participant')}`, `<strong>/destroy</strong>: ${i18n_('Remove this groupchat')}`, `<strong>/help</strong>: ${i18n_('Show this menu')}`, `<strong>/kick</strong>: ${i18n_('Kick user from groupchat')}`, `<strong>/me</strong>: ${i18n_('Write in 3rd person')}`, `<strong>/member</strong>: ${i18n_('Grant membership to a user')}`, `<strong>/modtools</strong>: ${i18n_('Opens up the moderator tools GUI')}`, `<strong>/mute</strong>: ${i18n_("Remove user's ability to post messages")}`, `<strong>/nick</strong>: ${i18n_('Change your nickname')}`, `<strong>/op</strong>: ${i18n_('Grant moderator role to user')}`, `<strong>/owner</strong>: ${i18n_('Grant ownership of this groupchat')}`, `<strong>/register</strong>: ${i18n_("Register your nickname")}`, `<strong>/revoke</strong>: ${i18n_("Revoke the user's current affiliation")}`, `<strong>/subject</strong>: ${i18n_('Set groupchat subject')}`, `<strong>/topic</strong>: ${i18n_('Set groupchat subject (alias for /subject)')}`, `<strong>/voice</strong>: ${i18n_('Allow muted user to post messages')}`].filter(line => disabled_commands.every(c => !line.startsWith(c + '<', 9))).filter(line => this.getAllowedCommands().some(c => line.startsWith(c + '<', 9)));
  },

  /**
   * Renders the MUC heading if any relevant attributes have changed.
   * @private
   * @method _converse.ChatRoomView#renderHeading
   * @param { _converse.ChatRoom } [item]
   */
  async renderHeading() {
    const tpl = await this.generateHeadingTemplate();
    render_render(tpl, this.el.querySelector('.chat-head-chatroom'));
  },

  renderBottomPanel() {
    const container = this.el.querySelector('.bottom-panel');
    const entered = this.model.session.get('connection_status') === converse.ROOMSTATUS.ENTERED;
    const can_edit = entered && !(this.model.features.get('moderated') && this.model.getOwnRole() === 'visitor');
    render_render(muc_bottom_panel({
      can_edit,
      entered
    }), container);

    if (entered && can_edit) {
      this.renderMessageForm();
      this.initMentionAutoComplete();
    }
  },

  onStartResizeOccupants(ev) {
    this.resizing = true;
    this.el.addEventListener('mousemove', this.onMouseMove);
    this.el.addEventListener('mouseup', this.onMouseUp);
    const sidebar_el = this.el.querySelector('converse-muc-sidebar');
    const style = window.getComputedStyle(sidebar_el);
    this.width = parseInt(style.width.replace(/px$/, ''), 10);
    this.prev_pageX = ev.pageX;
  },

  onMouseMove(ev) {
    if (this.resizing) {
      ev.preventDefault();
      const delta = this.prev_pageX - ev.pageX;
      this.resizeSidebarView(delta, ev.pageX);
      this.prev_pageX = ev.pageX;
    }
  },

  onMouseUp(ev) {
    if (this.resizing) {
      ev.preventDefault();
      this.resizing = false;
      this.el.removeEventListener('mousemove', this.onMouseMove);
      this.el.removeEventListener('mouseup', this.onMouseUp);
      const sidebar_el = this.el.querySelector('converse-muc-sidebar');
      const element_position = sidebar_el.getBoundingClientRect();
      const occupants_width = this.calculateSidebarWidth(element_position, 0);
      const attrs = {
        occupants_width
      };
      converse_core_converse.connection.connected ? this.model.save(attrs) : this.model.set(attrs);
    }
  },

  resizeSidebarView(delta, current_mouse_position) {
    const sidebar_el = this.el.querySelector('converse-muc-sidebar');
    const element_position = sidebar_el.getBoundingClientRect();

    if (this.is_minimum) {
      this.is_minimum = element_position.left < current_mouse_position;
    } else if (this.is_maximum) {
      this.is_maximum = element_position.left > current_mouse_position;
    } else {
      const occupants_width = this.calculateSidebarWidth(element_position, delta);
      sidebar_el.style.flex = "0 0 " + occupants_width + "px";
    }
  },

  calculateSidebarWidth(element_position, delta) {
    let occupants_width = element_position.width + delta;
    const room_width = this.el.clientWidth; // keeping display in boundaries

    if (occupants_width < room_width * 0.20) {
      // set pixel to 20% width
      occupants_width = room_width * 0.20;
      this.is_minimum = true;
    } else if (occupants_width > room_width * 0.75) {
      // set pixel to 75% width
      occupants_width = room_width * 0.75;
      this.is_maximum = true;
    } else if (room_width - occupants_width < 250) {
      // resize occupants if chat-area becomes smaller than 250px (min-width property set in css)
      occupants_width = room_width - 250;
      this.is_maximum = true;
    } else {
      this.is_maximum = false;
      this.is_minimum = false;
    }

    return occupants_width;
  },

  getAutoCompleteList() {
    return this.model.getAllKnownNicknames().map(nick => ({
      'label': nick,
      'value': `@${nick}`
    }));
  },

  getAutoCompleteListItem(text, input) {
    input = input.trim();
    const element = document.createElement("li");
    element.setAttribute("aria-selected", "false");

    if (converse_core_api.settings.get('muc_mention_autocomplete_show_avatar')) {
      const img = document.createElement("img");
      let dataUri = "data:" + converse_core_converse.DEFAULT_IMAGE_TYPE + ";base64," + converse_core_converse.DEFAULT_IMAGE;

      if (converse_core_converse.vcards) {
        const vcard = converse_core_converse.vcards.findWhere({
          'nickname': text
        });

        if (vcard) dataUri = "data:" + vcard.get('image_type') + ";base64," + vcard.get('image');
      }

      img.setAttribute("src", dataUri);
      img.setAttribute("width", "22");
      img.setAttribute("class", "avatar avatar-autocomplete");
      element.appendChild(img);
    }

    const regex = new RegExp("(" + input + ")", "ig");
    const parts = input ? text.split(regex) : [text];
    parts.forEach(txt => {
      if (input && txt.match(regex)) {
        const match = document.createElement("mark");
        match.textContent = txt;
        element.appendChild(match);
      } else {
        element.appendChild(document.createTextNode(txt));
      }
    });
    return element;
  },

  initMentionAutoComplete() {
    this.mention_auto_complete = new converse_core_converse.AutoComplete(this.el, {
      'auto_first': true,
      'auto_evaluate': false,
      'min_chars': converse_core_api.settings.get('muc_mention_autocomplete_min_chars'),
      'match_current_word': true,
      'list': () => this.getAutoCompleteList(),
      'filter': converse_core_api.settings.get('muc_mention_autocomplete_filter') == 'contains' ? converse_core_converse.FILTER_CONTAINS : converse_core_converse.FILTER_STARTSWITH,
      'ac_triggers': ["Tab", "@"],
      'include_triggers': [],
      'item': this.getAutoCompleteListItem
    });
    this.mention_auto_complete.on('suggestion-box-selectcomplete', () => this.auto_completing = false);
  },

  /**
   * Get the nickname value from the form and then join the groupchat with it.
   * @private
   * @method _converse.ChatRoomView#submitNickname
   * @param { Event }
   */
  submitNickname(ev) {
    ev.preventDefault();
    const nick = ev.target.nick.value.trim();
    nick && this.model.join(nick);
  },

  onKeyDown(ev) {
    if (this.mention_auto_complete.onKeyDown(ev)) {
      return;
    }

    return converse_core_converse.ChatBoxView.prototype.onKeyDown.call(this, ev);
  },

  onKeyUp(ev) {
    this.mention_auto_complete.evaluate(ev);
    return converse_core_converse.ChatBoxView.prototype.onKeyUp.call(this, ev);
  },

  async onMessageRetractButtonClicked(message) {
    const retraction_warning = i18n_("Be aware that other XMPP/Jabber clients (and servers) may " + "not yet support retractions and that this message may not " + "be removed everywhere.");

    if (message.mayBeRetracted()) {
      const messages = [i18n_('Are you sure you want to retract this message?')];

      if (converse_core_api.settings.get('show_retraction_warning')) {
        messages[1] = retraction_warning;
      }

      !!(await converse_core_api.confirm(i18n_('Confirm'), messages)) && this.model.retractOwnMessage(message);
    } else if (await message.mayBeModerated()) {
      if (message.get('sender') === 'me') {
        let messages = [i18n_('Are you sure you want to retract this message?')];

        if (converse_core_api.settings.get('show_retraction_warning')) {
          messages = [messages[0], retraction_warning, messages[1]];
        }

        !!(await converse_core_api.confirm(i18n_('Confirm'), messages)) && this.retractOtherMessage(message);
      } else {
        let messages = [i18n_('You are about to retract this message.'), i18n_('You may optionally include a message, explaining the reason for the retraction.')];

        if (converse_core_api.settings.get('show_retraction_warning')) {
          messages = [messages[0], retraction_warning, messages[1]];
        }

        const reason = await converse_core_api.prompt(i18n_('Message Retraction'), messages, i18n_('Optional reason'));
        reason !== false && this.retractOtherMessage(message, reason);
      }
    } else {
      const err_msg = i18n_(`Sorry, you're not allowed to retract this message`);

      converse_core_api.alert('error', i18n_('Error'), err_msg);
    }
  },

  /**
   * Retract someone else's message in this groupchat.
   * @private
   * @method _converse.ChatRoomView#retractOtherMessage
   * @param { _converse.Message } message - The message which we're retracting.
   * @param { string } [reason] - The reason for retracting the message.
   */
  async retractOtherMessage(message, reason) {
    const result = await this.model.retractOtherMessage(message, reason);

    if (result === null) {
      const err_msg = i18n_(`A timeout occurred while trying to retract the message`);

      converse_core_api.alert('error', i18n_('Error'), err_msg);
      headless_log(err_msg, converse_muc_views_Strophe.LogLevel.WARN);
    } else if (converse_muc_views_u.isErrorStanza(result)) {
      const err_msg = i18n_(`Sorry, you're not allowed to retract this message.`);

      converse_core_api.alert('error', i18n_('Error'), err_msg);
      headless_log(err_msg, converse_muc_views_Strophe.LogLevel.WARN);
      headless_log(result, converse_muc_views_Strophe.LogLevel.WARN);
    }
  },

  showModeratorToolsModal(affiliation) {
    if (!this.verifyRoles(['moderator'])) {
      return;
    }

    if (typeof this.model.modtools_modal === 'undefined') {
      const model = new model_Model({
        'affiliation': affiliation
      });
      this.modtools_modal = new moderator_tools({
        model,
        _converse: converse_core_converse,
        'chatroomview': this
      });
    } else {
      this.modtools_modal.set('affiliation', affiliation);
    }

    this.modtools_modal.show();
  },

  showRoomDetailsModal(ev) {
    ev.preventDefault();

    if (this.model.room_details_modal === undefined) {
      this.model.room_details_modal = new muc_details({
        'model': this.model
      });
    }

    this.model.room_details_modal.show(ev);
  },

  showChatStateNotification(message) {
    if (message.get('sender') === 'me') {
      return;
    }

    return converse_core_converse.ChatBoxView.prototype.showChatStateNotification.apply(this, arguments);
  },

  shouldShowSidebar() {
    return !this.model.get('hidden_occupants') && this.model.session.get('connection_status') === converse.ROOMSTATUS.ENTERED;
  },

  onSidebarToggle() {
    var _this$el$querySelecto;

    this.renderToolbar();
    (_this$el$querySelecto = this.el.querySelector('.occupants')) === null || _this$el$querySelecto === void 0 ? void 0 : _this$el$querySelecto.setVisibility();
  },

  onOccupantAffiliationChanged(occupant) {
    if (occupant.get('jid') === converse_core_converse.bare_jid) {
      this.renderHeading();
    }
  },

  onOccupantRoleChanged(occupant) {
    if (occupant.get('jid') === converse_core_converse.bare_jid) {
      this.renderBottomPanel();
    }
  },

  /**
   * Returns a list of objects which represent buttons for the groupchat header.
   * @emits _converse#getHeadingButtons
   * @private
   * @method _converse.ChatRoomView#getHeadingButtons
   */
  getHeadingButtons(subject_hidden) {
    const buttons = [];
    buttons.push({
      'i18n_text': i18n_('Details'),
      'i18n_title': i18n_('Show more information about this groupchat'),
      'handler': ev => this.showRoomDetailsModal(ev),
      'a_class': 'show-room-details-modal',
      'icon_class': 'fa-info-circle',
      'name': 'details'
    });

    if (this.model.getOwnAffiliation() === 'owner') {
      buttons.push({
        'i18n_text': i18n_('Configure'),
        'i18n_title': i18n_('Configure this groupchat'),
        'handler': ev => this.getAndRenderConfigurationForm(ev),
        'a_class': 'configure-chatroom-button',
        'icon_class': 'fa-wrench',
        'name': 'configure'
      });
    }

    if (this.model.invitesAllowed()) {
      buttons.push({
        'i18n_text': i18n_('Invite'),
        'i18n_title': i18n_('Invite someone to join this groupchat'),
        'handler': ev => this.showInviteModal(ev),
        'a_class': 'open-invite-modal',
        'icon_class': 'fa-user-plus',
        'name': 'invite'
      });
    }

    const subject = this.model.get('subject');

    if (subject && subject.text) {
      buttons.push({
        'i18n_text': subject_hidden ? i18n_('Show topic') : i18n_('Hide topic'),
        'i18n_title': subject_hidden ? i18n_('Show the topic message in the heading') : i18n_('Hide the topic in the heading'),
        'handler': ev => this.toggleTopic(ev),
        'a_class': 'hide-topic',
        'icon_class': 'fa-minus-square',
        'name': 'toggle-topic'
      });
    }

    const conn_status = this.model.session.get('connection_status');

    if (conn_status === converse.ROOMSTATUS.ENTERED) {
      const allowed_commands = this.getAllowedCommands();

      if (allowed_commands.includes('modtools')) {
        buttons.push({
          'i18n_text': i18n_('Moderate'),
          'i18n_title': i18n_('Moderate this groupchat'),
          'handler': () => this.showModeratorToolsModal(),
          'a_class': 'moderate-chatroom-button',
          'icon_class': 'fa-user-cog',
          'name': 'moderate'
        });
      }

      if (allowed_commands.includes('destroy')) {
        buttons.push({
          'i18n_text': i18n_('Destroy'),
          'i18n_title': i18n_('Remove this groupchat'),
          'handler': ev => this.destroy(ev),
          'a_class': 'destroy-chatroom-button',
          'icon_class': 'fa-trash',
          'name': 'destroy'
        });
      }
    }

    if (!converse_core_api.settings.get("singleton")) {
      buttons.push({
        'i18n_text': i18n_('Leave'),
        'i18n_title': i18n_('Leave and close this groupchat'),
        'handler': async ev => {
          ev.stopPropagation();
          const messages = [i18n_('Are you sure you want to leave this groupchat?')];
          const result = await converse_core_api.confirm(i18n_('Confirm'), messages);
          result && this.close(ev);
        },
        'a_class': 'close-chatbox-button',
        'standalone': converse_core_api.settings.get("view_mode") === 'overlayed',
        'icon_class': 'fa-sign-out-alt',
        'name': 'signout'
      });
    }

    return converse_core_converse.api.hook('getHeadingButtons', this, buttons);
  },

  /**
   * Returns the groupchat heading TemplateResult to be rendered.
   * @private
   * @method _converse.ChatRoomView#generateHeadingTemplate
   */
  async generateHeadingTemplate() {
    const subject_hidden = await this.model.isSubjectHidden();
    const heading_btns = await this.getHeadingButtons(subject_hidden);
    const standalone_btns = heading_btns.filter(b => b.standalone);
    const dropdown_btns = heading_btns.filter(b => !b.standalone);
    return chatroom_head(Object.assign(this.model.toJSON(), {
      _converse: converse_core_converse,
      subject_hidden,
      'dropdown_btns': dropdown_btns.map(b => this.getHeadingDropdownItem(b)),
      'standalone_btns': standalone_btns.map(b => this.getHeadingStandaloneButton(b)),
      'title': this.model.getDisplayName()
    }));
  },

  toggleTopic() {
    this.model.toggleSubjectHiddenState();
  },

  showInviteModal(ev) {
    ev.preventDefault();

    if (this.muc_invite_modal === undefined) {
      this.muc_invite_modal = new muc_invite({
        'model': new model_Model()
      }); // TODO: remove once we have API for sending direct invite

      this.muc_invite_modal.chatroomview = this;
    }

    this.muc_invite_modal.show(ev);
  },

  /**
   * Callback method that gets called after the chat has become visible.
   * @private
   * @method _converse.ChatRoomView#afterShown
   */
  afterShown() {
    // Override from converse-chatview, specifically to avoid
    // the 'active' chat state from being sent out prematurely.
    // This is instead done in `onConnectionStatusChanged` below.
    if (converse_muc_views_u.isPersistableModel(this.model)) {
      this.model.clearUnreadMsgCounter();
    }

    this.scrollDown();
  },

  onConnectionStatusChanged() {
    const conn_status = this.model.session.get('connection_status');

    if (conn_status === converse.ROOMSTATUS.NICKNAME_REQUIRED) {
      this.renderNicknameForm();
    } else if (conn_status === converse.ROOMSTATUS.PASSWORD_REQUIRED) {
      this.renderPasswordForm();
    } else if (conn_status === converse.ROOMSTATUS.CONNECTING) {
      this.showSpinner();
    } else if (conn_status === converse.ROOMSTATUS.ENTERED) {
      this.renderBottomPanel();
      this.hideSpinner();
      this.maybeFocus();
    } else if (conn_status === converse.ROOMSTATUS.DISCONNECTED) {
      this.showDisconnectMessage();
    } else if (conn_status === converse.ROOMSTATUS.DESTROYED) {
      this.showDestroyedMessage();
    }
  },

  getToolbarOptions() {
    return Object.assign(converse_core_converse.ChatBoxView.prototype.getToolbarOptions.apply(this, arguments), {
      'is_groupchat': true,
      'label_hide_occupants': i18n_('Hide the list of participants'),
      'show_occupants_toggle': converse_core_converse.visible_toolbar_buttons.toggle_occupants
    });
  },

  /**
   * Closes this chat box, which implies leaving the groupchat as well.
   * @private
   * @method _converse.ChatRoomView#close
   */
  async close() {
    this.hide();

    if (converse_core_converse.router.history.getFragment() === "converse/room?jid=" + this.model.get('jid')) {
      converse_core_converse.router.navigate('');
    }

    await this.model.leave();
    return converse_core_converse.ChatBoxView.prototype.close.apply(this, arguments);
  },

  /**
   * Hide the right sidebar containing the chat occupants.
   * @private
   * @method _converse.ChatRoomView#hideOccupants
   */
  hideOccupants(ev) {
    if (ev) {
      ev.preventDefault();
      ev.stopPropagation();
    }

    this.model.save({
      'hidden_occupants': true
    });
    this.scrollDown();
  },

  verifyRoles(roles, occupant, show_error = true) {
    if (!Array.isArray(roles)) {
      throw new TypeError('roles must be an Array');
    }

    if (!roles.length) {
      return true;
    }

    occupant = occupant || this.model.occupants.findWhere({
      'jid': converse_core_converse.bare_jid
    });

    if (occupant) {
      const role = occupant.get('role');

      if (roles.includes(role)) {
        return true;
      }
    }

    if (show_error) {
      const message = i18n_('Forbidden: you do not have the necessary role in order to do that.');

      this.model.createMessage({
        message,
        'type': 'error'
      });
    }

    return false;
  },

  verifyAffiliations(affiliations, occupant, show_error = true) {
    if (!Array.isArray(affiliations)) {
      throw new TypeError('affiliations must be an Array');
    }

    if (!affiliations.length) {
      return true;
    }

    occupant = occupant || this.model.occupants.findWhere({
      'jid': converse_core_converse.bare_jid
    });

    if (occupant) {
      const a = occupant.get('affiliation');

      if (affiliations.includes(a)) {
        return true;
      }
    }

    if (show_error) {
      const message = i18n_('Forbidden: you do not have the necessary affiliation in order to do that.');

      this.model.createMessage({
        message,
        'type': 'error'
      });
    }

    return false;
  },

  validateRoleOrAffiliationChangeArgs(command, args) {
    if (!args) {
      const message = i18n_('Error: the "%1$s" command takes two arguments, the user\'s nickname and optionally a reason.', command);

      this.model.createMessage({
        message,
        'type': 'error'
      });
      return false;
    }

    return true;
  },

  getNickOrJIDFromCommandArgs(args) {
    if (converse_muc_views_u.isValidJID(args.trim())) {
      return args.trim();
    }

    if (!args.startsWith('@')) {
      args = '@' + args;
    }

    const [text, references] = this.model.parseTextForReferences(args); // eslint-disable-line no-unused-vars

    if (!references.length) {
      const message = i18n_("Error: couldn't find a groupchat participant based on your arguments");

      this.model.createMessage({
        message,
        'type': 'error'
      });
      return;
    }

    if (references.length > 1) {
      const message = i18n_("Error: found multiple groupchat participant based on your arguments");

      this.model.createMessage({
        message,
        'type': 'error'
      });
      return;
    }

    const nick_or_jid = references.pop().value;
    const reason = args.split(nick_or_jid, 2)[1];

    if (reason && !reason.startsWith(' ')) {
      const message = i18n_("Error: couldn't find a groupchat participant based on your arguments");

      this.model.createMessage({
        message,
        'type': 'error'
      });
      return;
    }

    return nick_or_jid;
  },

  setAffiliation(command, args, required_affiliations) {
    const affiliation = COMMAND_TO_AFFILIATION[command];

    if (!affiliation) {
      throw Error(`ChatRoomView#setAffiliation called with invalid command: ${command}`);
    }

    if (!this.verifyAffiliations(required_affiliations)) {
      return false;
    }

    if (!this.validateRoleOrAffiliationChangeArgs(command, args)) {
      return false;
    }

    const nick_or_jid = this.getNickOrJIDFromCommandArgs(args);

    if (!nick_or_jid) {
      return false;
    }

    let jid;
    const reason = args.split(nick_or_jid, 2)[1].trim();
    const occupant = this.model.getOccupant(nick_or_jid);

    if (occupant) {
      jid = occupant.get('jid');
    } else {
      if (converse_muc_views_u.isValidJID(nick_or_jid)) {
        jid = nick_or_jid;
      } else {
        const message = i18n_("Couldn't find a participant with that nickname. " + "They might have left the groupchat.");

        this.model.createMessage({
          message,
          'type': 'error'
        });
        return;
      }
    }

    const attrs = {
      jid,
      reason
    };

    if (occupant && converse_core_api.settings.get('auto_register_muc_nickname')) {
      attrs['nick'] = occupant.get('nick');
    }

    this.model.setAffiliation(affiliation, [attrs]).then(() => this.model.occupants.fetchMembers()).catch(err => this.onCommandError(err));
  },

  getReason(args) {
    return args.includes(',') ? args.slice(args.indexOf(',') + 1).trim() : null;
  },

  setRole(command, args, required_affiliations = [], required_roles = []) {
    /* Check that a command to change a groupchat user's role or
     * affiliation has anough arguments.
     */
    const role = COMMAND_TO_ROLE[command];

    if (!role) {
      throw Error(`ChatRoomView#setRole called with invalid command: ${command}`);
    }

    if (!this.verifyAffiliations(required_affiliations) || !this.verifyRoles(required_roles)) {
      return false;
    }

    if (!this.validateRoleOrAffiliationChangeArgs(command, args)) {
      return false;
    }

    const nick_or_jid = this.getNickOrJIDFromCommandArgs(args);

    if (!nick_or_jid) {
      return false;
    }

    const reason = args.split(nick_or_jid, 2)[1].trim(); // We're guaranteed to have an occupant due to getNickOrJIDFromCommandArgs

    const occupant = this.model.getOccupant(nick_or_jid);
    this.model.setRole(occupant, role, reason, undefined, this.onCommandError.bind(this));
    return true;
  },

  onCommandError(err) {
    headless_log.fatal(err);

    const message = i18n_("Sorry, an error happened while running the command.") + " " + i18n_("Check your browser's developer console for details.");

    this.model.createMessage({
      message,
      'type': 'error'
    });
  },

  getAllowedCommands() {
    let allowed_commands = ['clear', 'help', 'me', 'nick', 'register'];

    if (this.model.config.get('changesubject') || ['owner', 'admin'].includes(this.model.getOwnAffiliation())) {
      allowed_commands = [...allowed_commands, ...['subject', 'topic']];
    }

    const occupant = this.model.occupants.findWhere({
      'jid': converse_core_converse.bare_jid
    });

    if (this.verifyAffiliations(['owner'], occupant, false)) {
      allowed_commands = allowed_commands.concat(OWNER_COMMANDS).concat(ADMIN_COMMANDS);
    } else if (this.verifyAffiliations(['admin'], occupant, false)) {
      allowed_commands = allowed_commands.concat(ADMIN_COMMANDS);
    }

    if (this.verifyRoles(['moderator'], occupant, false)) {
      allowed_commands = allowed_commands.concat(MODERATOR_COMMANDS).concat(VISITOR_COMMANDS);
    } else if (!this.verifyRoles(['visitor', 'participant', 'moderator'], occupant, false)) {
      allowed_commands = allowed_commands.concat(VISITOR_COMMANDS);
    }

    allowed_commands.sort();

    if (Array.isArray(converse_core_api.settings.get('muc_disable_slash_commands'))) {
      return allowed_commands.filter(c => !converse_core_api.settings.get('muc_disable_slash_commands').includes(c));
    } else {
      return allowed_commands;
    }
  },

  async destroy() {
    const messages = [i18n_('Are you sure you want to destroy this groupchat?')];
    let fields = [{
      'name': 'challenge',
      'label': i18n_('Please enter the XMPP address of this groupchat to confirm'),
      'challenge': this.model.get('jid'),
      'placeholder': i18n_('name@example.org'),
      'required': true
    }, {
      'name': 'reason',
      'label': i18n_('Optional reason for destroying this groupchat'),
      'placeholder': i18n_('Reason')
    }, {
      'name': 'newjid',
      'label': i18n_('Optional XMPP address for a new groupchat that replaces this one'),
      'placeholder': i18n_('replacement@example.org')
    }];

    try {
      var _fields$filter$pop, _fields$filter$pop2;

      fields = await converse_core_api.confirm(i18n_('Confirm'), messages, fields);
      const reason = (_fields$filter$pop = fields.filter(f => f.name === 'reason').pop()) === null || _fields$filter$pop === void 0 ? void 0 : _fields$filter$pop.value;
      const newjid = (_fields$filter$pop2 = fields.filter(f => f.name === 'newjid').pop()) === null || _fields$filter$pop2 === void 0 ? void 0 : _fields$filter$pop2.value;
      return this.model.sendDestroyIQ(reason, newjid).then(() => this.close());
    } catch (e) {
      headless_log.error(e);
    }
  },

  parseMessageForCommands(text) {
    if (converse_core_api.settings.get('muc_disable_slash_commands') && !Array.isArray(converse_core_api.settings.get('muc_disable_slash_commands'))) {
      return converse_core_converse.ChatBoxView.prototype.parseMessageForCommands.apply(this, arguments);
    }

    text = text.replace(/^\s*/, "");
    const command = (text.match(/^\/([a-zA-Z]*) ?/) || ['']).pop().toLowerCase();

    if (!command) {
      return false;
    }

    const args = text.slice(('/' + command).length + 1).trim();

    if (!this.getAllowedCommands().includes(command)) {
      return false;
    }

    switch (command) {
      case 'admin':
        {
          this.setAffiliation(command, args, ['owner']);
          break;
        }

      case 'ban':
        {
          this.setAffiliation(command, args, ['admin', 'owner']);
          break;
        }

      case 'modtools':
        {
          this.showModeratorToolsModal(args);
          break;
        }

      case 'deop':
        {
          // FIXME: /deop only applies to setting a moderators
          // role to "participant" (which only admin/owner can
          // do). Moderators can however set non-moderator's role
          // to participant (e.g. visitor => participant).
          // Currently we don't distinguish between these two
          // cases.
          this.setRole(command, args, ['admin', 'owner']);
          break;
        }

      case 'destroy':
        {
          if (!this.verifyAffiliations(['owner'])) {
            break;
          }

          this.destroy().catch(e => this.onCommandError(e));
          break;
        }

      case 'help':
        {
          this.model.set({
            'show_help_messages': true
          });
          break;
        }

      case 'kick':
        {
          this.setRole(command, args, [], ['moderator']);
          break;
        }

      case 'mute':
        {
          this.setRole(command, args, [], ['moderator']);
          break;
        }

      case 'member':
        {
          this.setAffiliation(command, args, ['admin', 'owner']);
          break;
        }

      case 'nick':
        {
          if (!this.verifyRoles(['visitor', 'participant', 'moderator'])) {
            break;
          } else if (args.length === 0) {
            // e.g. Your nickname is "coolguy69"
            const message = i18n_('Your nickname is "%1$s"', this.model.get('nick'));

            this.model.createMessage({
              message,
              'type': 'error'
            });
          } else {
            const jid = converse_muc_views_Strophe.getBareJidFromJid(this.model.get('jid'));
            converse_core_api.send(converse_muc_views_$pres({
              from: converse_core_converse.connection.jid,
              to: `${jid}/${args}`,
              id: converse_muc_views_u.getUniqueId()
            }).tree());
          }

          break;
        }

      case 'owner':
        this.setAffiliation(command, args, ['owner']);
        break;

      case 'op':
        {
          this.setRole(command, args, ['admin', 'owner']);
          break;
        }

      case 'register':
        {
          if (args.length > 1) {
            this.model.createMessage({
              'message': i18n_('Error: invalid number of arguments'),
              'type': 'error'
            });
          } else {
            this.model.registerNickname().then(err_msg => {
              err_msg && this.model.createMessage({
                'message': err_msg,
                'type': 'error'
              });
            });
          }

          break;
        }

      case 'revoke':
        {
          this.setAffiliation(command, args, ['admin', 'owner']);
          break;
        }

      case 'topic':
      case 'subject':
        this.model.setSubject(args);
        break;

      case 'voice':
        {
          this.setRole(command, args, [], ['moderator']);
          break;
        }

      default:
        return converse_core_converse.ChatBoxView.prototype.parseMessageForCommands.apply(this, arguments);
    }

    return true;
  },

  /**
   * Renders a form given an IQ stanza containing the current
   * groupchat configuration.
   * Returns a promise which resolves once the user has
   * either submitted the form, or canceled it.
   * @private
   * @method _converse.ChatRoomView#renderConfigurationForm
   * @param { XMLElement } stanza: The IQ stanza containing the groupchat config.
   */
  renderConfigurationForm(stanza) {
    this.hideChatRoomContents();
    this.model.save('config_stanza', stanza.outerHTML);

    if (!this.config_form) {
      this.config_form = new converse_core_converse.MUCConfigForm({
        'model': this.model,
        'chatroomview': this
      });
      const container_el = this.el.querySelector('.chatroom-body');
      container_el.insertAdjacentElement('beforeend', this.config_form.el);
    }

    converse_muc_views_u.showElement(this.config_form.el);
  },

  /**
   * Renders a form which allows the user to choose theirnickname.
   * @private
   * @method _converse.ChatRoomView#renderNicknameForm
   */
  renderNicknameForm() {
    const tpl_result = muc_nickname_form(this.model.toJSON());

    if (converse_core_api.settings.get('muc_show_logs_before_join')) {
      const container = this.el.querySelector('.muc-bottom-panel');
      render_render(tpl_result, container);
      converse_muc_views_u.addClass('muc-bottom-panel--nickname', container);
    } else {
      const form = this.el.querySelector('.muc-nickname-form');
      const form_el = converse_muc_views_u.getElementFromTemplateResult(tpl_result);

      if (form) {
        converse_muc_views_sizzle('.spinner', this.el).forEach(converse_muc_views_u.removeElement);
        form.outerHTML = form_el.outerHTML;
      } else {
        this.hideChatRoomContents();
        const container = this.el.querySelector('.chatroom-body');
        container.insertAdjacentElement('beforeend', form_el);
      }
    }

    converse_muc_views_u.safeSave(this.model.session, {
      'connection_status': converse.ROOMSTATUS.NICKNAME_REQUIRED
    });
  },

  /**
   * Remove the configuration form without submitting and return to the chat view.
   * @private
   * @method _converse.ChatRoomView#closeForm
   */
  closeForm() {
    converse_muc_views_sizzle('.chatroom-form-container', this.el).forEach(e => converse_muc_views_u.addClass('hidden', e));
    this.renderAfterTransition();
  },

  /**
   * Start the process of configuring a groupchat, either by
   * rendering a configuration form, or by auto-configuring
   * based on the "roomconfig" data stored on the
   * {@link _converse.ChatRoom}.
   * Stores the new configuration on the {@link _converse.ChatRoom}
   * once completed.
   * @private
   * @method _converse.ChatRoomView#getAndRenderConfigurationForm
   * @param { Event } ev - DOM event that might be passed in if this
   *   method is called due to a user action. In this
   *   case, auto-configure won't happen, regardless of
   *   the settings.
   */
  getAndRenderConfigurationForm() {
    if (!this.config_form || !converse_muc_views_u.isVisible(this.config_form.el)) {
      this.showSpinner();
      this.model.fetchRoomConfiguration().then(iq => this.renderConfigurationForm(iq)).catch(e => headless_log.error(e));
    } else {
      this.closeForm();
    }
  },

  hideChatRoomContents() {
    const container_el = this.el.querySelector('.chatroom-body');

    if (container_el !== null) {
      [].forEach.call(container_el.children, child => child.classList.add('hidden'));
    }
  },

  renderPasswordForm() {
    this.hideChatRoomContents();
    const message = this.model.get('password_validation_message');
    this.model.save('password_validation_message', undefined);

    if (!this.password_form) {
      this.password_form = new converse_core_converse.MUCPasswordForm({
        'model': new model_Model({
          'validation_message': message
        }),
        'chatroomview': this
      });
      const container_el = this.el.querySelector('.chatroom-body');
      container_el.insertAdjacentElement('beforeend', this.password_form.el);
    } else {
      this.password_form.model.set('validation_message', message);
    }

    converse_muc_views_u.showElement(this.password_form.el);
    this.model.session.save('connection_status', converse.ROOMSTATUS.PASSWORD_REQUIRED);
  },

  showDestroyedMessage() {
    converse_muc_views_u.hideElement(this.el.querySelector('.chat-area'));
    converse_muc_views_u.hideElement(this.el.querySelector('.occupants'));
    converse_muc_views_sizzle('.spinner', this.el).forEach(converse_muc_views_u.removeElement);
    const reason = this.model.get('destroyed_reason');
    const moved_jid = this.model.get('moved_jid');
    this.model.save({
      'destroyed_reason': undefined,
      'moved_jid': undefined
    });
    const container = this.el.querySelector('.disconnect-container');
    render_render(muc_destroyed(moved_jid, reason), container);
    const switch_el = container.querySelector('a.switch-chat');

    if (switch_el) {
      switch_el.addEventListener('click', async ev => {
        ev.preventDefault();
        const room = await converse_core_api.rooms.get(moved_jid, null, true);
        room.maybeShow(true);
        this.model.destroy();
      });
    }

    converse_muc_views_u.showElement(container);
  },

  showDisconnectMessage() {
    const message = this.model.get('disconnection_message');

    if (!message) {
      return;
    }

    converse_muc_views_u.hideElement(this.el.querySelector('.chat-area'));
    converse_muc_views_u.hideElement(this.el.querySelector('.occupants'));
    converse_muc_views_sizzle('.spinner', this.el).forEach(converse_muc_views_u.removeElement);
    const messages = [message];
    const actor = this.model.get('disconnection_actor');

    if (actor) {
      messages.push(i18n_('This action was done by %1$s.', actor));
    }

    const reason = this.model.get('disconnection_reason');

    if (reason) {
      messages.push(i18n_('The reason given is: "%1$s".', reason));
    }

    this.model.save({
      'disconnection_message': undefined,
      'disconnection_reason': undefined,
      'disconnection_actor': undefined
    });
    const container = this.el.querySelector('.disconnect-container');
    render_render(muc_disconnect(messages), container);
    converse_muc_views_u.showElement(container);
  },

  onOccupantAdded(occupant) {
    if (occupant.get('jid') === converse_core_converse.bare_jid) {
      this.renderHeading();
      this.renderBottomPanel();
    }
  },

  /**
   * Working backwards, get today's most recent join/leave notification
   * from the same user (if any exists) after the most recent chat message.
   * @private
   * @method _converse.ChatRoomView#getPreviousJoinOrLeaveNotification
   * @param {HTMLElement} el
   * @param {string} nick
   */
  getPreviousJoinOrLeaveNotification(el, nick) {
    const today = new Date().toISOString().split('T')[0];

    while (el !== null) {
      var _el;

      if (!el.classList.contains('chat-info')) {
        return;
      } // Check whether el is still from today.
      // We don't use `Dayjs.same` here, since it's about 4 times slower.


      const date = el.getAttribute('data-isodate');

      if (date && date.split('T')[0] !== today) {
        return;
      }

      const data = ((_el = el) === null || _el === void 0 ? void 0 : _el.dataset) || {};

      if (data.join === nick || data.leave === nick || data.leavejoin === nick || data.joinleave === nick) {
        return el;
      }

      el = el.previousElementSibling;
    }
  },

  /**
   * Rerender the groupchat after some kind of transition. For
   * example after the spinner has been removed or after a
   * form has been submitted and removed.
   * @private
   * @method _converse.ChatRoomView#renderAfterTransition
   */
  renderAfterTransition() {
    const conn_status = this.model.session.get('connection_status');

    if (conn_status == converse.ROOMSTATUS.NICKNAME_REQUIRED) {
      this.renderNicknameForm();
    } else if (conn_status == converse.ROOMSTATUS.PASSWORD_REQUIRED) {
      this.renderPasswordForm();
    } else if (conn_status == converse.ROOMSTATUS.ENTERED) {
      var _this$el$querySelecto2;

      this.hideChatRoomContents();
      converse_muc_views_u.showElement(this.el.querySelector('.chat-area'));
      (_this$el$querySelecto2 = this.el.querySelector('.occupants')) === null || _this$el$querySelecto2 === void 0 ? void 0 : _this$el$querySelecto2.setVisibility();
      this.scrollDown();
    }
  },

  showSpinner() {
    converse_muc_views_sizzle('.spinner', this.el).forEach(converse_muc_views_u.removeElement);
    this.hideChatRoomContents();
    const container_el = this.el.querySelector('.chatroom-body');
    container_el.insertAdjacentElement('afterbegin', converse_muc_views_u.getElementFromTemplateResult(spinner()));
  },

  /**
   * Check if the spinner is being shown and if so, hide it.
   * Also make sure then that the chat area and occupants
   * list are both visible.
   * @private
   * @method _converse.ChatRoomView#hideSpinner
   */
  hideSpinner() {
    const spinner = this.el.querySelector('.spinner');

    if (spinner !== null) {
      converse_muc_views_u.removeElement(spinner);
      this.renderAfterTransition();
    }

    return this;
  }

});
/**
 * View which renders MUC section of the control box.
 * @class
 * @namespace _converse.RoomsPanel
 * @memberOf _converse
 */

const RoomsPanel = View.extend({
  tagName: 'div',
  className: 'controlbox-section',
  id: 'chatrooms',
  events: {
    'click a.controlbox-heading__btn.show-add-muc-modal': 'showAddRoomModal',
    'click a.controlbox-heading__btn.show-list-muc-modal': 'showMUCListModal'
  },

  toHTML() {
    return room_panel({
      'heading_chatrooms': i18n_('Groupchats'),
      'title_new_room': i18n_('Add a new groupchat'),
      'title_list_rooms': i18n_('Query for groupchats')
    });
  },

  showAddRoomModal(ev) {
    if (this.add_room_modal === undefined) {
      this.add_room_modal = new add_muc({
        'model': this.model
      });
    }

    this.add_room_modal.show(ev);
  },

  showMUCListModal(ev) {
    if (this.muc_list_modal === undefined) {
      this.muc_list_modal = new muc_list({
        'model': this.model
      });
    }

    this.muc_list_modal.show(ev);
  }

});
converse.plugins.add('converse-muc-views', {
  /* Dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin. They are "optional" because they might not be
   * available, in which case any overrides applicable to them will be
   * ignored.
   *
   * NB: These plugins need to have already been loaded via require.js.
   *
   * It's possible to make these dependencies "non-optional".
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found.
   */
  dependencies: ["converse-autocomplete", "converse-modal", "converse-controlbox", "converse-chatview"],
  overrides: {
    ControlBoxView: {
      renderControlBoxPane() {
        this.__super__.renderControlBoxPane.apply(this, arguments);

        if (converse_core_api.settings.get('allow_muc')) {
          this.renderRoomsPanel();
        }
      }

    }
  },

  initialize() {
    const {
      _converse
    } = this;
    converse_core_api.promises.add(['roomsPanelRendered']); // Configuration values for this plugin
    // ====================================
    // Refer to docs/source/configuration.rst for explanations of these
    // configuration settings.

    converse_core_api.settings.extend({
      'auto_list_rooms': false,
      'cache_muc_messages': true,
      'locked_muc_nickname': false,
      'modtools_disable_query': [],
      'modtools_disable_assign': false,
      'muc_disable_slash_commands': false,
      'muc_mention_autocomplete_filter': 'contains',
      'muc_mention_autocomplete_min_chars': 0,
      'muc_mention_autocomplete_show_avatar': true,
      'muc_roomid_policy': null,
      'muc_roomid_policy_hint': null,
      'roomconfig_whitelist': [],
      'show_retraction_warning': true,
      'visible_toolbar_buttons': {
        'toggle_occupants': true
      }
    });
    _converse.ChatRoomView = ChatRoomView;
    _converse.RoomsPanel = RoomsPanel;
    const viewWithRoomsPanel = {
      renderRoomsPanel() {
        if (this.roomspanel && converse_muc_views_u.isInDOM(this.roomspanel.el)) {
          return this.roomspanel;
        }

        const id = `converse.roomspanel${_converse.bare_jid}`;
        this.roomspanel = new _converse.RoomsPanel({
          'model': new (_converse.RoomsPanelModel.extend({
            id,
            'browserStorage': _converse.createStore(id)
          }))()
        });
        this.roomspanel.model.fetch();
        this.el.querySelector('.controlbox-pane').insertAdjacentElement('beforeEnd', this.roomspanel.render().el);
        /**
         * Triggered once the section of the { @link _converse.ControlBoxView }
         * which shows gropuchats has been rendered.
         * @event _converse#roomsPanelRendered
         * @example _converse.api.listen.on('roomsPanelRendered', () => { ... });
         */

        converse_core_api.trigger('roomsPanelRendered');
        return this.roomspanel;
      },

      getRoomsPanel() {
        if (this.roomspanel && converse_muc_views_u.isInDOM(this.roomspanel.el)) {
          return this.roomspanel;
        } else {
          return this.renderRoomsPanel();
        }
      }

    };

    if (_converse.ControlBoxView) {
      Object.assign(_converse.ControlBoxView.prototype, viewWithRoomsPanel);
    }

    _converse.MUCConfigForm = View.extend({
      className: 'chatroom-form-container muc-config-form',

      initialize(attrs) {
        this.chatroomview = attrs.chatroomview;
        this.listenTo(this.chatroomview.model.features, 'change:passwordprotected', this.render);
        this.listenTo(this.chatroomview.model.features, 'change:config_stanza', this.render);
        this.render();
      },

      toHTML() {
        var _stanza$querySelector, _stanza$querySelector2;

        const stanza = converse_muc_views_u.toStanza(this.model.get('config_stanza'));
        const whitelist = converse_core_api.settings.get('roomconfig_whitelist');
        let fields = converse_muc_views_sizzle('field', stanza);

        if (whitelist.length) {
          fields = fields.filter(f => whitelist.includes(f.getAttribute('var')));
        }

        const password_protected = this.model.features.get('passwordprotected');
        const options = {
          'new_password': !password_protected,
          'fixed_username': this.model.get('jid')
        };
        return muc_config_form({
          'closeConfigForm': ev => this.closeConfigForm(ev),
          'fields': fields.map(f => converse_muc_views_u.xForm2webForm(f, stanza, options)),
          'instructions': (_stanza$querySelector = stanza.querySelector('instructions')) === null || _stanza$querySelector === void 0 ? void 0 : _stanza$querySelector.textContent,
          'submitConfigForm': ev => this.submitConfigForm(ev),
          'title': (_stanza$querySelector2 = stanza.querySelector('title')) === null || _stanza$querySelector2 === void 0 ? void 0 : _stanza$querySelector2.textContent
        });
      },

      async submitConfigForm(ev) {
        ev.preventDefault();
        const inputs = converse_muc_views_sizzle(':input:not([type=button]):not([type=submit])', ev.target);
        const config_array = inputs.map(converse_muc_views_u.webForm2xForm).filter(f => f);

        try {
          await this.model.sendConfiguration(config_array);
        } catch (e) {
          headless_log.error(e);

          const message = i18n_("Sorry, an error occurred while trying to submit the config form.") + " " + i18n_("Check your browser's developer console for details.");

          converse_core_api.alert('error', i18n_('Error'), message);
        }

        await this.model.refreshDiscoInfo();
        this.chatroomview.closeForm();
      },

      closeConfigForm(ev) {
        ev.preventDefault();
        this.chatroomview.closeForm();
      }

    });
    _converse.MUCPasswordForm = View.extend({
      className: 'chatroom-form-container muc-password-form',

      initialize(attrs) {
        this.chatroomview = attrs.chatroomview;
        this.listenTo(this.model, 'change:validation_message', this.render);
        this.render();
      },

      toHTML() {
        return muc_password_form({
          'jid': this.model.get('jid'),
          'submitPassword': ev => this.submitPassword(ev),
          'validation_message': this.model.get('validation_message')
        });
      },

      submitPassword(ev) {
        ev.preventDefault();
        const password = this.el.querySelector('input[type=password]').value;
        this.chatroomview.model.join(this.chatroomview.model.get('nick'), password);
        this.model.set('validation_message', null);
      }

    });

    function setMUCDomain(domain, controlboxview) {
      controlboxview.getRoomsPanel().model.save('muc_domain', converse_muc_views_Strophe.getDomainFromJid(domain));
    }

    function setMUCDomainFromDisco(controlboxview) {
      /* Check whether service discovery for the user's domain
       * returned MUC information and use that to automatically
       * set the MUC domain in the "Add groupchat" modal.
       */
      function featureAdded(feature) {
        if (!feature) {
          return;
        }

        if (feature.get('var') === converse_muc_views_Strophe.NS.MUC) {
          feature.entity.getIdentity('conference', 'text').then(identity => {
            if (identity) {
              setMUCDomain(feature.get('from'), controlboxview);
            }
          });
        }
      }

      converse_core_api.waitUntil('discoInitialized').then(() => {
        converse_core_api.listen.on('serviceDiscovered', featureAdded); // Features could have been added before the controlbox was
        // initialized. We're only interested in MUC

        _converse.disco_entities.each(entity => featureAdded(entity.features.findWhere({
          'var': converse_muc_views_Strophe.NS.MUC
        })));
      }).catch(e => headless_log.error(e));
    }

    function fetchAndSetMUCDomain(controlboxview) {
      if (controlboxview.model.get('connected')) {
        if (!controlboxview.getRoomsPanel().model.get('muc_domain')) {
          if (converse_core_api.settings.get('muc_domain') === undefined) {
            setMUCDomainFromDisco(controlboxview);
          } else {
            setMUCDomain(converse_core_api.settings.get('muc_domain'), controlboxview);
          }
        }
      }
    }
    /************************ BEGIN Event Handlers ************************/


    converse_core_api.listen.on('chatBoxViewsInitialized', () => {
      function openChatRoomFromURIClicked(ev) {
        ev.preventDefault();
        converse_core_api.rooms.open(ev.target.href);
      }

      _converse.chatboxviews.delegate('click', 'a.open-chatroom', openChatRoomFromURIClicked);

      async function addView(model) {
        const views = _converse.chatboxviews;

        if (!views.get(model.get('id')) && model.get('type') === _converse.CHATROOMS_TYPE && model.isValid()) {
          await model.initialized;
          return views.add(model.get('id'), new _converse.ChatRoomView({
            model
          }));
        }
      }

      _converse.chatboxes.on('add', addView);
    });
    converse_core_api.listen.on('clearSession', () => {
      const view = _converse.chatboxviews.get('controlbox');

      if (view && view.roomspanel) {
        view.roomspanel.model.destroy();
        view.roomspanel.remove();
        delete view.roomspanel;
      }
    });
    converse_core_api.listen.on('controlBoxInitialized', view => {
      if (!converse_core_api.settings.get('allow_muc')) {
        return;
      }

      fetchAndSetMUCDomain(view);
      view.model.on('change:connected', () => fetchAndSetMUCDomain(view));
    });
    /************************ END Event Handlers ************************/

    /************************ BEGIN API ************************/

    Object.assign(_converse.api, {
      /**
       * The "roomviews" namespace groups methods relevant to chatroom
       * (aka groupchats) views.
       *
       * @namespace _converse.api.roomviews
       * @memberOf _converse.api
       */
      roomviews: {
        /**
         * Retrieves a groupchat (aka chatroom) view. The chat should already be open.
         *
         * @method _converse.api.roomviews.get
         * @param {String|string[]} name - e.g. 'coven@conference.shakespeare.lit' or
         *  ['coven@conference.shakespeare.lit', 'cave@conference.shakespeare.lit']
         * @returns {View} View representing the groupchat
         *
         * @example
         * // To return a single view, provide the JID of the groupchat
         * const view = _converse.api.roomviews.get('coven@conference.shakespeare.lit');
         *
         * @example
         * // To return an array of views, provide an array of JIDs:
         * const views = _converse.api.roomviews.get(['coven@conference.shakespeare.lit', 'cave@conference.shakespeare.lit']);
         *
         * @example
         * // To return views of all open groupchats, call the method without any parameters::
         * const views = _converse.api.roomviews.get();
         *
         */
        get(jids) {
          if (Array.isArray(jids)) {
            const views = converse_core_api.chatviews.get(jids);
            return views.filter(v => v.model.get('type') === _converse.CHATROOMS_TYPE);
          } else {
            const view = converse_core_api.chatviews.get(jids);

            if (view.model.get('type') === _converse.CHATROOMS_TYPE) {
              return view;
            } else {
              return null;
            }
          }
        },

        /**
         * Lets you close open chatrooms.
         *
         * You can call this method without any arguments to close
         * all open chatrooms, or you can specify a single JID or
         * an array of JIDs.
         *
         * @method _converse.api.roomviews.close
         * @param {(String[]|String)} jids The JID or array of JIDs of the chatroom(s)
         * @returns { Promise } - Promise which resolves once the views have been closed.
         */
        close(jids) {
          let views;

          if (jids === undefined) {
            views = _converse.chatboxviews;
          } else if (typeof jids === 'string') {
            views = [_converse.chatboxviews.get(jids)].filter(v => v);
          } else if (Array.isArray(jids)) {
            views = jids.map(jid => _converse.chatboxviews.get(jid));
          }

          return Promise.all(views.map(v => v.is_chatroom && v.model && v.close()));
        }

      }
    });
  }

});
// CONCATENATED MODULE: ./src/templates/headline_list.js


const tpl_headline_box = o => lit_html_html`
    <div class="list-item controlbox-padded d-flex flex-row"
        data-headline-jid="${o.headlinebox.get('jid')}">
    <a class="list-item-link open-headline available-room w-100"
        data-headline-jid="${o.headlinebox.get('jid')}"
        title="${o.open_title}" href="#">${o.headlinebox.get('jid')}</a>
    </div>
`;

/* harmony default export */ var headline_list = (o => lit_html_html`
    <div class="list-container list-container--headline ${o.headlineboxes.length ? '' : 'hidden'}">
        <div class="items-list rooms-list headline-list">
            ${o.headlineboxes.map(headlinebox => tpl_headline_box(Object.assign({
  headlinebox
}, o)))}
        </div>
    </div>
`);
// CONCATENATED MODULE: ./src/templates/headline_panel.js


/* harmony default export */ var headline_panel = (o => lit_html_html`
    <div class="d-flex controlbox-padded ${o.headlineboxes.length ? '' : 'hidden'}">
        <span class="w-100 controlbox-heading controlbox-heading--headline">${o.heading_headline}</span>
    </div>
    ${headline_list(o)}
`);
// CONCATENATED MODULE: ./src/converse-headlines-view.js
/**
 * @module converse-headlines-view
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */








const converse_headlines_view_u = converse.env.utils;
const HeadlinesBoxView = ChatBoxView.extend({
  className: 'chatbox headlines hidden',
  events: {
    'click .close-chatbox-button': 'close',
    'click .toggle-chatbox-button': 'minimize',
    'keypress textarea.chat-textarea': 'onKeyDown'
  },

  async initialize() {
    this.initDebounced();
    this.model.disable_mam = true; // Don't do MAM queries for this box

    this.listenTo(this.model, 'change:hidden', m => m.get('hidden') ? this.hide() : this.show());
    this.listenTo(this.model, 'destroy', this.remove);
    this.listenTo(this.model, 'show', this.show);
    this.render(); // Need to be registered after render has been called.

    this.listenTo(this.model.messages, 'add', this.onMessageAdded);
    this.listenTo(this.model.messages, 'remove', this.renderChatHistory);
    this.listenTo(this.model.messages, 'rendered', this.maybeScrollDown);
    this.listenTo(this.model.messages, 'reset', this.renderChatHistory);
    await this.model.messages.fetched;
    this.insertIntoDOM();
    this.model.maybeShow();
    this.scrollDown();
    /**
     * Triggered once the {@link _converse.HeadlinesBoxView} has been initialized
     * @event _converse#headlinesBoxViewInitialized
     * @type { _converse.HeadlinesBoxView }
     * @example _converse.api.listen.on('headlinesBoxViewInitialized', view => { ... });
     */

    converse_core_api.trigger('headlinesBoxViewInitialized', this);
  },

  render() {
    this.el.setAttribute('id', this.model.get('box_id'));
    const result = templates_chatbox(Object.assign(this.model.toJSON(), {
      info_close: '',
      label_personal_message: '',
      show_send_button: false,
      show_toolbar: false,
      unread_msgs: ''
    }));
    render_render(result, this.el);
    this.content = this.el.querySelector('.chat-content');
    this.msgs_container = this.el.querySelector('.chat-content__messages');
    this.renderChatContent();
    this.renderHeading();
    return this;
  },

  getNotifications() {
    // Override method in ChatBox. We don't show notifications for
    // headlines boxes.
    return [];
  },

  /**
   * Returns a list of objects which represent buttons for the headlines header.
   * @async
   * @emits _converse#getHeadingButtons
   * @private
   * @method _converse.HeadlinesBoxView#getHeadingButtons
   */
  getHeadingButtons() {
    const buttons = [];

    if (!converse_core_api.settings.get("singleton")) {
      buttons.push({
        'a_class': 'close-chatbox-button',
        'handler': ev => this.close(ev),
        'i18n_text': i18n_('Close'),
        'i18n_title': i18n_('Close these announcements'),
        'icon_class': 'fa-times',
        'name': 'close',
        'standalone': converse_core_api.settings.get("view_mode") === 'overlayed'
      });
    }

    return converse_core_converse.api.hook('getHeadingButtons', this, buttons);
  },

  // Override to avoid the methods in converse-chatview.js
  'renderMessageForm': function renderMessageForm() {},
  'afterShown': function afterShown() {}
});
/**
 * View which renders headlines section of the control box.
 * @class
 * @namespace _converse.HeadlinesPanel
 * @memberOf _converse
 */

const HeadlinesPanel = View.extend({
  tagName: 'div',
  className: 'controlbox-section',
  id: 'headline',
  events: {
    'click .open-headline': 'openHeadline'
  },

  initialize() {
    this.listenTo(this.model, 'add', this.renderIfHeadline);
    this.listenTo(this.model, 'remove', this.renderIfHeadline);
    this.listenTo(this.model, 'destroy', this.renderIfHeadline);
    this.render();
    this.insertIntoDOM();
  },

  toHTML() {
    return headline_panel({
      'heading_headline': i18n_('Announcements'),
      'headlineboxes': this.model.filter(m => m.get('type') === converse_core_converse.HEADLINES_TYPE),
      'open_title': i18n_('Click to open this server message')
    });
  },

  renderIfHeadline(model) {
    return model && model.get('type') === converse_core_converse.HEADLINES_TYPE && this.render();
  },

  openHeadline(ev) {
    ev.preventDefault();
    const jid = ev.target.getAttribute('data-headline-jid');

    const chat = converse_core_converse.chatboxes.get(jid);

    chat.maybeShow(true);
  },

  insertIntoDOM() {
    const view = converse_core_converse.chatboxviews.get('controlbox');

    view && view.el.querySelector('.controlbox-pane').insertAdjacentElement('beforeEnd', this.el);
  }

});
converse.plugins.add('converse-headlines-view', {
  /* Plugin dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin.
   *
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found. By default it's
   * false, which means these plugins are only loaded opportunistically.
   *
   * NB: These plugins need to have already been loaded via require.js.
   */
  dependencies: ["converse-headlines", "converse-chatview"],
  overrides: {
    // Overrides mentioned here will be picked up by converse.js's
    // plugin architecture they will replace existing methods on the
    // relevant objects or classes.
    //
    // New functions which don't exist yet can also be added.
    ControlBoxView: {
      renderControlBoxPane() {
        this.__super__.renderControlBoxPane.apply(this, arguments);

        this.renderHeadlinesPanel();
      }

    }
  },

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    const viewWithHeadlinesPanel = {
      renderHeadlinesPanel() {
        if (this.headlinepanel && converse_headlines_view_u.isInDOM(this.headlinepanel.el)) {
          return this.headlinepanel;
        }

        this.headlinepanel = new converse_core_converse.HeadlinesPanel({
          'model': converse_core_converse.chatboxes
        });
        /**
         * Triggered once the section of the { @link _converse.ControlBoxView }
         * which shows announcements has been rendered.
         * @event _converse#headlinesPanelRendered
         * @example _converse.api.listen.on('headlinesPanelRendered', () => { ... });
         */

        converse_core_api.trigger('headlinesPanelRendered');
        return this.headlinepanel;
      }

    };

    if (converse_core_converse.ControlBoxView) {
      Object.assign(converse_core_converse.ControlBoxView.prototype, viewWithHeadlinesPanel);
    }

    converse_core_converse.HeadlinesBoxView = HeadlinesBoxView;
    converse_core_converse.HeadlinesPanel = HeadlinesPanel;
    /************************ BEGIN Event Handlers ************************/

    converse_core_api.listen.on('chatBoxViewsInitialized', () => {
      const views = converse_core_converse.chatboxviews;

      converse_core_converse.chatboxes.on('add', item => {
        if (!views.get(item.get('id')) && item.get('type') === converse_core_converse.HEADLINES_TYPE) {
          views.add(item.get('id'), new converse_core_converse.HeadlinesBoxView({
            model: item
          }));
        }
      });
    });
  }

});
// EXTERNAL MODULE: ./node_modules/favico.js-slevomat/favico.js
var favico = __webpack_require__(175);
var favico_default = /*#__PURE__*/__webpack_require__.n(favico);

// CONCATENATED MODULE: ./src/converse-notification.js
/**
 * @module converse-notification
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */




const {
  Strophe: converse_notification_Strophe
} = converse.env;
const converse_notification_u = converse.env.utils;
const supports_html5_notification = ("Notification" in window);
converse.env.Favico = favico_default.a;
let favicon;

function updateUnreadFavicon() {
  if (converse_core_api.settings.get('update_title')) {
    var _favicon;

    favicon = (_favicon = favicon) !== null && _favicon !== void 0 ? _favicon : new converse.env.Favico({
      type: 'circle',
      animation: 'pop'
    });
    const chats = converse_core_converse.chatboxes.models;
    const num_unread = chats.reduce((acc, chat) => acc + (chat.get('num_unread') || 0), 0);
    favicon.badge(num_unread);
  }
}

converse.plugins.add('converse-notification', {
  dependencies: ["converse-chatboxes"],

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    converse_core_api.settings.extend({
      update_title: true,
      notify_all_room_messages: false,
      show_desktop_notifications: true,
      show_chat_state_notifications: false,
      chatstate_notification_blacklist: [],
      // ^ a list of JIDs to ignore concerning chat state notifications
      play_sounds: true,
      sounds_path: converse_core_api.settings.get("assets_path") + '/sounds/',
      notification_icon: 'logo/conversejs-filled.svg',
      notification_delay: 5000,
      notify_nicknames_without_references: false
    });
    /**
     * Is this a group message for which we should notify the user?
     * @private
     * @method _converse#shouldNotifyOfGroupMessage
     * @param { MUCMessageAttributes } attrs
     */

    converse_core_converse.shouldNotifyOfGroupMessage = function (attrs) {
      if (!(attrs !== null && attrs !== void 0 && attrs.body)) {
        return false;
      }

      const jid = attrs.from;
      const room_jid = attrs.from_muc;
      const notify_all = converse_core_api.settings.get('notify_all_room_messages');

      const room = converse_core_converse.chatboxes.get(room_jid);

      const resource = converse_notification_Strophe.getResourceFromJid(jid);
      const sender = resource && converse_notification_Strophe.unescapeNode(resource) || '';
      let is_mentioned = false;
      const nick = room.get('nick');

      if (converse_core_api.settings.get('notify_nicknames_without_references')) {
        is_mentioned = new RegExp(`\\b${nick}\\b`).test(attrs.body);
      }

      const is_referenced = attrs.references.map(r => r.value).includes(nick);
      const is_not_mine = sender !== nick;
      const should_notify_user = notify_all === true || Array.isArray(notify_all) && notify_all.includes(room_jid) || is_referenced || is_mentioned;
      return is_not_mine && !!should_notify_user;
    };
    /**
     * Given parsed attributes for a message stanza, get the related
     * chatbox and check whether it's hidden.
     * @private
     * @method _converse#isMessageToHiddenChat
     * @param { MUCMessageAttributes } attrs
     */


    converse_core_converse.isMessageToHiddenChat = function (attrs) {
      var _converse$chatboxes$g, _converse$chatboxes$g2;

      return (_converse$chatboxes$g = (_converse$chatboxes$g2 = converse_core_converse.chatboxes.get(attrs.from)) === null || _converse$chatboxes$g2 === void 0 ? void 0 : _converse$chatboxes$g2.isHidden()) !== null && _converse$chatboxes$g !== void 0 ? _converse$chatboxes$g : false;
    };
    /**
     * @private
     * @method _converse#shouldNotifyOfMessage
     * @param { MessageData|MUCMessageData } data
     */


    converse_core_converse.shouldNotifyOfMessage = function (data) {
      const {
        attrs,
        stanza
      } = data;

      if (!attrs || stanza.querySelector('forwarded') !== null) {
        return false;
      }

      if (attrs['type'] === 'groupchat') {
        return converse_core_converse.shouldNotifyOfGroupMessage(attrs);
      } else if (attrs.is_headline) {
        // We want to show notifications for headline messages.
        return converse_core_converse.isMessageToHiddenChat(attrs);
      }

      const is_me = converse_notification_Strophe.getBareJidFromJid(attrs.from) === converse_core_converse.bare_jid;

      return !converse_notification_u.isOnlyChatStateNotification(stanza) && !converse_notification_u.isOnlyMessageDeliveryReceipt(stanza) && !is_me && (converse_core_api.settings.get('show_desktop_notifications') === 'all' || converse_core_converse.isMessageToHiddenChat(attrs));
    };
    /**
     * Plays a notification sound
     * @private
     * @method _converse#playSoundNotification
     */


    converse_core_converse.playSoundNotification = function () {
      if (converse_core_api.settings.get('play_sounds') && window.Audio !== undefined) {
        const audioOgg = new Audio(converse_core_api.settings.get('sounds_path') + "msg_received.ogg");
        const canPlayOgg = audioOgg.canPlayType('audio/ogg');

        if (canPlayOgg === 'probably') {
          return audioOgg.play();
        }

        const audioMp3 = new Audio(converse_core_api.settings.get('sounds_path') + "msg_received.mp3");
        const canPlayMp3 = audioMp3.canPlayType('audio/mp3');

        if (canPlayMp3 === 'probably') {
          audioMp3.play();
        } else if (canPlayOgg === 'maybe') {
          audioOgg.play();
        } else if (canPlayMp3 === 'maybe') {
          audioMp3.play();
        }
      }
    };

    converse_core_converse.areDesktopNotificationsEnabled = function () {
      return supports_html5_notification && converse_core_api.settings.get('show_desktop_notifications') && Notification.permission === "granted";
    };
    /**
     * Shows an HTML5 Notification with the passed in message
     * @private
     * @method _converse#showMessageNotification
     * @param { MessageData|MUCMessageData } data
     */


    converse_core_converse.showMessageNotification = function (data) {
      const {
        attrs
      } = data;

      if (attrs.is_error) {
        return;
      }

      if (!converse_core_converse.areDesktopNotificationsEnabled()) {
        return;
      }

      let title, roster_item;
      const full_from_jid = attrs.from,
            from_jid = converse_notification_Strophe.getBareJidFromJid(full_from_jid);

      if (attrs.type === 'headline') {
        if (!from_jid.includes('@') || converse_core_api.settings.get("allow_non_roster_messaging")) {
          title = i18n_("Notification from %1$s", from_jid);
        } else {
          return;
        }
      } else if (!from_jid.includes('@')) {
        // workaround for Prosody which doesn't give type "headline"
        title = i18n_("Notification from %1$s", from_jid);
      } else if (attrs.type === 'groupchat') {
        title = i18n_("%1$s says", converse_notification_Strophe.getResourceFromJid(full_from_jid));
      } else {
        if (converse_core_converse.roster === undefined) {
          headless_log.error("Could not send notification, because roster is undefined");
          return;
        }

        roster_item = converse_core_converse.roster.get(from_jid);

        if (roster_item !== undefined) {
          title = i18n_("%1$s says", roster_item.getDisplayName());
        } else {
          if (converse_core_api.settings.get("allow_non_roster_messaging")) {
            title = i18n_("%1$s says", from_jid);
          } else {
            return;
          }
        }
      }

      const body = attrs.is_encrypted ? i18n_('Encrypted message received') : attrs.body;

      if (!body) {
        return;
      }

      const n = new Notification(title, {
        'body': body,
        'lang': converse_core_converse.locale,
        'icon': converse_core_api.settings.get('notification_icon'),
        'requireInteraction': !converse_core_converse.notification_delay
      });

      if (converse_core_api.settings.get('notification_delay')) {
        setTimeout(n.close.bind(n), converse_core_api.settings.get('notification_delay'));
      }

      n.onclick = function (event) {
        event.preventDefault();
        window.focus();

        const chat = converse_core_converse.chatboxes.get(from_jid);

        chat.maybeShow(true);
      };

      n.onclick.bind(converse_core_converse);
    };

    converse_core_converse.showChatStateNotification = function (contact) {
      /* Creates an HTML5 Notification to inform of a change in a
       * contact's chat state.
       */
      if (converse_core_converse.chatstate_notification_blacklist.includes(contact.jid)) {
        // Don't notify if the user is being ignored.
        return;
      }

      const chat_state = contact.chat_status;
      let message = null;

      if (chat_state === 'offline') {
        message = i18n_('has gone offline');
      } else if (chat_state === 'away') {
        message = i18n_('has gone away');
      } else if (chat_state === 'dnd') {
        message = i18n_('is busy');
      } else if (chat_state === 'online') {
        message = i18n_('has come online');
      }

      if (message === null) {
        return;
      }

      const n = new Notification(contact.getDisplayName(), {
        body: message,
        lang: converse_core_converse.locale,
        icon: converse_core_converse.notification_icon
      });
      setTimeout(n.close.bind(n), 5000);
    };

    converse_core_converse.showContactRequestNotification = function (contact) {
      const n = new Notification(contact.getDisplayName(), {
        body: i18n_('wants to be your contact'),
        lang: converse_core_converse.locale,
        icon: converse_core_converse.notification_icon
      });
      setTimeout(n.close.bind(n), 5000);
    };

    converse_core_converse.showFeedbackNotification = function (data) {
      if (data.klass === 'error' || data.klass === 'warn') {
        const n = new Notification(data.subject, {
          body: data.message,
          lang: converse_core_converse.locale,
          icon: converse_core_converse.notification_icon
        });
        setTimeout(n.close.bind(n), 5000);
      }
    };

    converse_core_converse.handleChatStateNotification = function (contact) {
      /* Event handler for on('contactPresenceChanged').
       * Will show an HTML5 notification to indicate that the chat
       * status has changed.
       */
      if (converse_core_converse.areDesktopNotificationsEnabled() && converse_core_api.settings.get('show_chat_state_notifications')) {
        converse_core_converse.showChatStateNotification(contact);
      }
    };

    converse_core_converse.handleMessageNotification = function (data) {
      /* Event handler for the on('message') event. Will call methods
       * to play sounds and show HTML5 notifications.
       */
      if (!converse_core_converse.shouldNotifyOfMessage(data)) {
        return false;
      }
      /**
       * Triggered when a notification (sound or HTML5 notification) for a new
       * message has will be made.
       * @event _converse#messageNotification
       * @type { MessageData|MUCMessageData}
       * @example _converse.api.listen.on('messageNotification', stanza => { ... });
       */


      converse_core_api.trigger('messageNotification', data);

      converse_core_converse.playSoundNotification();

      converse_core_converse.showMessageNotification(data);
    };

    converse_core_converse.handleContactRequestNotification = function (contact) {
      if (converse_core_converse.areDesktopNotificationsEnabled(true)) {
        converse_core_converse.showContactRequestNotification(contact);
      }
    };

    converse_core_converse.handleFeedback = function (data) {
      if (converse_core_converse.areDesktopNotificationsEnabled(true)) {
        converse_core_converse.showFeedbackNotification(data);
      }
    };

    converse_core_converse.requestPermission = function () {
      if (supports_html5_notification && !['denied', 'granted'].includes(Notification.permission)) {
        // Ask user to enable HTML5 notifications
        Notification.requestPermission();
      }
    };
    /************************ BEGIN Event Handlers ************************/


    converse_core_api.listen.on('clearSession', () => favicon = null); // Needed for tests

    converse_core_api.waitUntil('chatBoxesInitialized').then(() => converse_core_converse.chatboxes.on('change:num_unread', updateUnreadFavicon));
    converse_core_api.listen.on('pluginsInitialized', function () {
      // We only register event handlers after all plugins are
      // registered, because other plugins might override some of our
      // handlers.
      converse_core_api.listen.on('contactRequest', converse_core_converse.handleContactRequestNotification);
      converse_core_api.listen.on('contactPresenceChanged', converse_core_converse.handleChatStateNotification);
      converse_core_api.listen.on('message', converse_core_converse.handleMessageNotification);
      converse_core_api.listen.on('feedback', converse_core_converse.handleFeedback);
      converse_core_api.listen.on('connected', converse_core_converse.requestPermission);
    });
  }

});
// CONCATENATED MODULE: ./src/components/adhoc-commands.js







const {
  Strophe: adhoc_commands_Strophe,
  $iq: adhoc_commands_$iq,
  sizzle: adhoc_commands_sizzle
} = converse.env;
const adhoc_commands_u = converse.env.utils;

const tpl_command_form = (o, command) => {
  const i18n_hide = i18n_('Hide');

  const i18n_run = i18n_('Execute');

  return lit_html_html`
        <form @submit=${o.runCommand}>
            ${command.alert ? lit_html_html`<div class="alert alert-${command.alert_type}" role="alert">${command.alert}</div>` : ''}
            <fieldset class="form-group">
                <input type="hidden" name="command_node" value="${command.node}"/>
                <input type="hidden" name="command_jid" value="${command.jid}"/>

                <p class="form-help">${command.instructions}</p>
                <!-- Fields are generated internally, with xForm2webForm -->
                ${command.fields.map(field => unsafeHTML(field))}
            </fieldset>
            <fieldset>
                <input type="submit" class="btn btn-primary" value="${i18n_run}">
                <input type="button" class="btn btn-secondary button-cancel" value="${i18n_hide}" @click=${o.hideCommandForm}>
            </fieldset>
        </form>
    `;
};

const tpl_command = (o, command) => lit_html_html`
    <li class="room-item list-group-item">
        <div class="available-chatroom d-flex flex-row">
            <a class="open-room available-room w-100"
               @click=${o.toggleCommandForm}
               data-command-node="${command.node}"
               data-command-jid="${command.jid}"
               data-command-name="${command.name}"
               title="${command.name}"
               href="#">${command.name || command.jid}</a>
        </div>
        ${command.node === o.showform ? tpl_command_form(o, command) : ''}
    </li>
`;

async function getAutoCompleteList() {
  const models = [...(await converse_core_api.rooms.get()), ...(await converse_core_api.contacts.get())];
  const jids = [...new Set(models.map(o => adhoc_commands_Strophe.getDomainFromJid(o.get('jid'))))];
  return jids;
}

const tpl_adhoc = o => {
  const i18n_choose_service = i18n_('On which entity do you want to run commands?');

  const i18n_choose_service_instructions = i18n_('Certain XMPP services and entities allow privileged users to execute ad-hoc commands on them.');

  const i18n_commands_found = i18n_('Commands found');

  const i18n_fetch_commands = i18n_('List available commands');

  const i18n_jid_placeholder = i18n_('XMPP Address');

  const i18n_no_commands_found = i18n_('No commands found');

  return lit_html_html`
        ${o.alert ? lit_html_html`<div class="alert alert-${o.alert_type}" role="alert">${o.alert}</div>` : ''}
        <form class="converse-form" @submit=${o.fetchCommands}>
            <fieldset class="form-group">
                <label>
                    ${i18n_choose_service}
                    <p class="form-help">${i18n_choose_service_instructions}</p>
                    <converse-autocomplete
                        .getAutoCompleteList="${getAutoCompleteList}"
                        placeholder="${i18n_jid_placeholder}"
                        name="jid"/>
                </label>
            </fieldset>
            <fieldset class="form-group">
                <input type="submit" class="btn btn-primary" value="${i18n_fetch_commands}">
            </fieldset>
            ${o.view === 'list-commands' ? lit_html_html`
            <fieldset class="form-group">
                <ul class="list-group">
                    <li class="list-group-item active">${o.commands.length ? i18n_commands_found : i18n_no_commands_found}:</li>
                    ${o.commands.map(cmd => tpl_command(o, cmd))}
                </ul>
            </fieldset>` : ''}

        </form>
    `;
};

async function fetchCommandForm(command) {
  const node = command.node;
  const jid = command.jid;
  const stanza = adhoc_commands_$iq({
    'type': 'set',
    'to': jid
  }).c('command', {
    'xmlns': adhoc_commands_Strophe.NS.ADHOC,
    'node': node,
    'action': 'execute'
  });

  try {
    var _sizzle$pop;

    const iq = await converse_core_api.sendIQ(stanza);
    const cmd_el = adhoc_commands_sizzle(`command[xmlns="${adhoc_commands_Strophe.NS.ADHOC}"]`, iq).pop();
    command.sessionid = cmd_el.getAttribute('sessionid');
    command.instructions = (_sizzle$pop = adhoc_commands_sizzle('x[type="form"][xmlns="jabber:x:data"] instructions', cmd_el).pop()) === null || _sizzle$pop === void 0 ? void 0 : _sizzle$pop.textContent;
    command.fields = adhoc_commands_sizzle('x[type="form"][xmlns="jabber:x:data"] field', cmd_el).map(f => adhoc_commands_u.xForm2webForm(f, cmd_el));
  } catch (e) {
    if (e === null) {
      headless_log.error(`Error: timeout while trying to execute command for ${jid}`);
    } else {
      headless_log.error(`Error while trying to execute command for ${jid}`);
      headless_log.error(e);
    }

    command.fields = [];
  }
}

class adhoc_commands_AdHocCommands extends element_CustomElement {
  static get properties() {
    return {
      'alert': {
        type: String
      },
      'alert_type': {
        type: String
      },
      'nonce': {
        type: String
      },
      // Used to force re-rendering
      'showform': {
        type: String
      },
      'view': {
        type: String
      }
    };
  }

  constructor() {
    super();
    this.view = 'choose-service';
    this.showform = '';
    this.commands = [];
  }

  render() {
    return tpl_adhoc({
      'alert': this.alert,
      'alert_type': this.alert_type,
      'commands': this.commands,
      'fetchCommands': ev => this.fetchCommands(ev),
      'hideCommandForm': ev => this.hideCommandForm(ev),
      'runCommand': ev => this.runCommand(ev),
      'showform': this.showform,
      'toggleCommandForm': ev => this.toggleCommandForm(ev),
      'view': this.view
    });
  }

  async fetchCommands(ev) {
    ev.preventDefault();
    delete this.alert_type;
    delete this.alert;
    const form_data = new FormData(ev.target);
    const jid = form_data.get('jid').trim();
    let supported;

    try {
      supported = await converse_core_api.disco.supports(adhoc_commands_Strophe.NS.ADHOC, jid);
    } catch (e) {
      headless_log.error(e);
    }

    if (supported) {
      try {
        this.commands = await converse_core_api.adhoc.getCommands(jid);
        this.view = 'list-commands';
      } catch (e) {
        headless_log.error(e);
        this.alert_type = 'danger';
        this.alert = i18n_('Sorry, an error occurred while looking for commands on that entity.');
        this.commands = [];
        headless_log.error(e);
        return;
      }
    } else {
      this.alert_type = 'danger';
      this.alert = i18n_("The specified entity doesn't support ad-hoc commands");
    }
  }

  async toggleCommandForm(ev) {
    ev.preventDefault();
    const node = ev.target.getAttribute('data-command-node');
    const cmd = this.commands.filter(c => c.node === node)[0];
    this.showform !== node && (await fetchCommandForm(cmd));
    this.showform = node;
  }

  hideCommandForm(ev) {
    ev.preventDefault();
    this.showform = '';
  }

  async runCommand(ev) {
    ev.preventDefault();
    const form_data = new FormData(ev.target);
    const jid = form_data.get('command_jid').trim();
    const node = form_data.get('command_node').trim();
    const cmd = this.commands.filter(c => c.node === node)[0];
    const inputs = adhoc_commands_sizzle(':input:not([type=button]):not([type=submit])', ev.target);
    const config_array = inputs.filter(i => !['command_jid', 'command_node'].includes(i.getAttribute('name'))).map(adhoc_commands_u.webForm2xForm).filter(n => n);
    const iq = adhoc_commands_$iq({
      to: jid,
      type: "set"
    }).c("command", {
      'sessionid': cmd.sessionid,
      'node': cmd.node,
      'xmlns': adhoc_commands_Strophe.NS.ADHOC
    }).c("x", {
      xmlns: adhoc_commands_Strophe.NS.XFORM,
      type: "submit"
    });
    config_array.forEach(node => iq.cnode(node).up());
    let result;

    try {
      result = await converse_core_api.sendIQ(iq);
    } catch (e) {
      cmd.alert_type = 'danger';
      cmd.alert = i18n_('Sorry, an error occurred while trying to execute the command. See the developer console for details');
      headless_log.error('Error while trying to execute an ad-hoc command');
      headless_log.error(e);
    }

    if (result) {
      var _result$querySelector;

      cmd.alert = (_result$querySelector = result.querySelector('note')) === null || _result$querySelector === void 0 ? void 0 : _result$querySelector.textContent;
    } else {
      cmd.alert = 'Done';
    }

    cmd.alert_type = 'primary';
    this.nonce = adhoc_commands_u.getUniqueId();
  }

}
converse_core_api.elements.define('converse-adhoc-commands', adhoc_commands_AdHocCommands);
// CONCATENATED MODULE: ./src/templates/user_settings_modal.js








const user_settings_modal_tpl_navigation = o => {
  const i18n_about = i18n_('About');

  const i18n_commands = i18n_('Commands');

  return lit_html_html`
        <ul class="nav nav-pills justify-content-center">
            <li role="presentation" class="nav-item">
                <a class="nav-link active" id="about-tab" href="#about-tabpanel" aria-controls="about-tabpanel" role="tab" data-toggle="tab" @click=${o.switchTab}>${i18n_about}</a>
            </li>
            <li role="presentation" class="nav-item">
                <a class="nav-link" id="commands-tab" href="#commands-tabpanel" aria-controls="commands-tabpanel" role="tab" data-toggle="tab" @click=${o.switchTab}>${i18n_commands}</a>
            </li>
        </ul>
    `;
};

/* harmony default export */ var user_settings_modal = (o => {
  const i18n_modal_title = i18n_('Settings');

  const first_subtitle = i18n_('%1$s Open Source %2$s XMPP chat client brought to you by %3$s Opkode %2$s', '<a target="_blank" rel="nofollow" href="https://conversejs.org">', '</a>', '<a target="_blank" rel="nofollow" href="https://opkode.com">');

  const second_subtitle = i18n_('%1$s Translate %2$s it into your own language', '<a target="_blank" rel="nofollow" href="https://hosted.weblate.org/projects/conversejs/#languages">', '</a>');

  const show_client_info = converse_core_api.settings.get('show_client_info');
  const allow_adhoc_commands = converse_core_api.settings.get('allow_adhoc_commands');
  const show_both_tabs = show_client_info && allow_adhoc_commands;
  return lit_html_html`
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="converse-modtools-modal-label">${i18n_modal_title}</h5>
                ${modal_header_close_button}
            </div>
            <div class="modal-body">
                ${show_both_tabs ? user_settings_modal_tpl_navigation(o) : ''}

                <div class="tab-content">
                    <div class="tab-pane tab-pane--columns ${show_client_info ? 'active' : ''}"
                         id="about-tabpanel" role="tabpanel" aria-labelledby="about-tab">

                        <span class="modal-alert"></span>
                        <br/>
                        <div class="container">
                            <h6 class="brand-heading">Converse</h6>
                            <p class="brand-subtitle">${o.version_name}</p>
                            <p class="brand-subtitle">${unsafeHTML(xss_default.a.filterXSS(first_subtitle, {
    'whiteList': {
      'a': []
    }
  }))}</p>
                            <p class="brand-subtitle">${unsafeHTML(xss_default.a.filterXSS(second_subtitle, {
    'whiteList': {
      'a': []
    }
  }))}</p>
                        </div>
                    </div>

                    <div class="tab-pane tab-pane--columns ${!show_client_info && allow_adhoc_commands ? 'active' : ''}"
                         id="commands-tabpanel"
                         role="tabpanel"
                         aria-labelledby="commands-tab">
                        <converse-adhoc-commands/>
                    </div>
                </div>
            </div>
        </div>
    </div>
`;
});
// CONCATENATED MODULE: ./src/modals/user-settings.js



let user_settings_converse;

/* harmony default export */ var modals_user_settings = (BootstrapModal.extend({
  id: "converse-client-info-modal",

  initialize(settings) {
    user_settings_converse = settings._converse;
    BootstrapModal.prototype.initialize.apply(this, arguments);
  },

  toHTML() {
    return user_settings_modal(Object.assign(this.model.toJSON(), this.model.vcard.toJSON(), {
      'version_name': user_settings_converse.VERSION_NAME
    }));
  }

}));
// CONCATENATED MODULE: ./src/templates/chat_status_modal.js


/* harmony default export */ var chat_status_modal = (o => lit_html_html`
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="changeStatusModalLabel">${o.modal_title}</h5>
                ${modal_header_close_button}
            </div>
            <div class="modal-body">
                <span class="modal-alert"></span>
                <form class="converse-form set-xmpp-status" id="set-xmpp-status">
                    <div class="form-group">
                        <div class="custom-control custom-radio">
                            <input ?checked=${o.status === 'online'}
                                type="radio" id="radio-online" value="online" name="chat_status" class="custom-control-input"/>
                            <label class="custom-control-label" for="radio-online">
                                <span class="fa fa-circle chat-status chat-status--online"></span>${o.label_online}</label>
                        </div>
                        <div class="custom-control custom-radio">
                            <input ?checked=${o.status === 'busy'}
                                type="radio" id="radio-busy" value="dnd" name="chat_status" class="custom-control-input"/>
                            <label class="custom-control-label" for="radio-busy">
                                <span class="fa fa-minus-circle  chat-status chat-status--busy"></span>${o.label_busy}</label>
                        </div>
                        <div class="custom-control custom-radio">
                            <input ?checked=${o.status === 'away'}
                                type="radio" id="radio-away" value="away" name="chat_status" class="custom-control-input"/>
                            <label class="custom-control-label" for="radio-away">
                                <span class="fa fa-circle chat-status chat-status--away"></span>${o.label_away}</label>
                        </div>
                        <div class="custom-control custom-radio">
                            <input ?checked=${o.status === 'xa'}
                                type="radio" id="radio-xa" value="xa" name="chat_status" class="custom-control-input"/>
                            <label class="custom-control-label" for="radio-xa">
                                <span class="far fa-circle chat-status chat-status--xa"></span>${o.label_xa}</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="btn-group w-100">
                            <input name="status_message" type="text" class="form-control"
                                value="${o.status_message || ''}" placeholder="${o.placeholder_status_message}"/>
                            <span class="clear-input fa fa-times ${o.status_message ? '' : 'hidden'}"></span>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">${o.label_save}</button>
                </form>
            </div>
        </div>
    </div>
`);
// CONCATENATED MODULE: ./src/templates/profile.js



/* harmony default export */ var profile = (o => {
  const i18n_logout = i18n_('Log out');

  const i18n_change_status = i18n_('Click to change your chat status');

  const i18n_details = i18n_('Show details about this chat client');

  const show_settings_button = converse_core_api.settings.get('show_client_info') || converse_core_api.settings.get('allow_adhoc_commands');
  return lit_html_html`
    <div class="userinfo controlbox-padded">
        <div class="controlbox-section profile d-flex">
            <a class="show-profile" href="#">
                <canvas class="avatar align-self-center" height="40" width="40"></canvas>
            </a>
            <span class="username w-100 align-self-center">${o.fullname}</span>
            ${show_settings_button ? lit_html_html`<a class="controlbox-heading__btn show-client-info fa fa-cog align-self-center" title="${i18n_details}" @click=${o.showUserSettingsModal}></a>` : ''}
            ${converse_core_api.settings.get('allow_logout') ? lit_html_html`<a class="controlbox-heading__btn logout fa fa-sign-out-alt align-self-center" title="${i18n_logout}"></a>` : ''}
        </div>
        <div class="d-flex xmpp-status">
            <a class="change-status" title="${i18n_change_status}" data-toggle="modal" data-target="#changeStatusModal">
                <span class="${o.chat_status} w-100 align-self-center" data-value="${o.chat_status}">
                    <span class="
                        ${o.chat_status === 'online' && 'fa fa-circle chat-status chat-status--online'}
                        ${o.chat_status === 'dnd' && 'fa fa-minus-circle chat-status chat-status--busy'}
                        ${o.chat_status === 'away' && 'fa fa-circle chat-status chat-status--away'}
                        ${o.chat_status === 'xa' && 'far fa-circle chat-status chat-status--xa '}
                        ${o.chat_status === 'offline' && 'fa fa-circle chat-status chat-status--offline'}"></span> ${o.status_message}</span>
            </a>
        </div>
    </div>
`;
});
// CONCATENATED MODULE: ./src/components/image_picker.js






const i18n_alt_avatar = i18n_('Your avatar image');

class image_picker_ImagePicker extends element_CustomElement {
  static get properties() {
    return {
      'height': {
        type: Number
      },
      'image': {
        type: String
      },
      'width': {
        type: Number
      }
    };
  }

  render() {
    const avatar_data = {
      'height': this.height,
      'image': this.image,
      'width': this.width
    };
    return lit_html_html`
            <a class="change-avatar" @click=${this.openFileSelection} title="${i18n_alt_avatar}">
                ${renderAvatar(avatar_data)}
            </a>
            <input @change=${this.updateFilePreview} class="hidden" name="image" type="file"/>
        `;
  }

  openFileSelection(ev) {
    ev.preventDefault();
    this.querySelector('input[type="file"]').click();
  }

  updateFilePreview(ev) {
    const file = ev.target.files[0];
    const reader = new FileReader();

    reader.onloadend = () => this.image = reader.result;

    reader.readAsDataURL(file);
  }

}
converse_core_api.elements.define('converse-image-picker', image_picker_ImagePicker);
// CONCATENATED MODULE: ./src/templates/profile_modal.js






const profile_modal_u = converse.env.utils;

const fingerprint = o => lit_html_html`
    <span class="fingerprint">${profile_modal_u.formatFingerprint(o.view.current_device.get('bundle').fingerprint)}</span>`;

const device_with_fingerprint = o => {
  const i18n_fingerprint_checkbox_label = i18n_('Checkbox for selecting the following fingerprint');

  return lit_html_html`
        <li class="fingerprint-removal-item list-group-item nopadding">
            <label>
            <input type="checkbox" value="${o.device.get('id')}"
                aria-label="${i18n_fingerprint_checkbox_label}"/>
            <span class="fingerprint">${profile_modal_u.formatFingerprint(o.device.get('bundle').fingerprint)}</span>
            </label>
        </li>
    `;
};

const device_without_fingerprint = o => {
  const i18n_device_without_fingerprint = i18n_('Device without a fingerprint');

  const i18n_fingerprint_checkbox_label = i18n_('Checkbox for selecting the following device');

  return lit_html_html`
        <li class="fingerprint-removal-item list-group-item nopadding">
            <label>
            <input type="checkbox" value="${o.device.get('id')}"
                aria-label="${i18n_fingerprint_checkbox_label}"/>
            <span>${i18n_device_without_fingerprint}</span>
            </label>
        </li>
    `;
};

const device_item = o => lit_html_html`
    ${o.device.get('bundle') && o.device.get('bundle').fingerprint ? device_with_fingerprint(o) : device_without_fingerprint(o)}
`;

const device_list = o => {
  const i18n_other_devices = i18n_('Other OMEMO-enabled devices');

  const i18n_other_devices_label = i18n_('Checkbox to select fingerprints of all other OMEMO devices');

  const i18n_remove_devices = i18n_('Remove checked devices and close');

  const i18n_select_all = i18n_('Select all');

  return lit_html_html`
        <ul class="list-group fingerprints">
            <li class="list-group-item nopadding active">
                <label>
                    <input type="checkbox" class="select-all" title="${i18n_select_all}" aria-label="${i18n_other_devices_label}"/>
                    ${i18n_other_devices}
                </label>
            </li>
            ${o.view.other_devices.map(device => device_item(Object.assign({
    device
  }, o)))}
        </ul>
        <div class="form-group"><button type="submit" class="save-form btn btn-primary">${i18n_remove_devices}</button></div>
    `;
}; // TODO: this needs to go as a component into the OMEMO plugin folder


const omemo_page = o => {
  const i18n_fingerprint = i18n_("This device's OMEMO fingerprint");

  const i18n_generate = i18n_('Generate new keys and fingerprint');

  return lit_html_html`
        <div class="tab-pane" id="omemo-tabpanel" role="tabpanel" aria-labelledby="omemo-tab">
            <form class="converse-form fingerprint-removal">
                <ul class="list-group fingerprints">
                    <li class="list-group-item active">${i18n_fingerprint}</li>
                    <li class="list-group-item">
                        ${o.view.current_device && o.view.current_device.get('bundle') && o.view.current_device.get('bundle').fingerprint ? fingerprint(o) : spinner()}
                    </li>
                </ul>
                <div class="form-group">
                    <button type="button" class="generate-bundle btn btn-danger">${i18n_generate}</button>
                </div>
                ${o.view.other_devices.length ? device_list(o) : ''}
            </form>
        </div>`;
};

/* harmony default export */ var profile_modal = (o => {
  const heading_profile = i18n_('Your Profile');

  const i18n_email = i18n_('Email');

  const i18n_fullname = i18n_('Full Name');

  const i18n_jid = i18n_('XMPP Address (JID)');

  const i18n_nickname = i18n_('Nickname');

  const i18n_role = i18n_('Role');

  const i18n_save = i18n_('Save and close');

  const i18n_role_help = i18n_('Use commas to separate multiple roles. Your roles are shown next to your name on your chat messages.');

  const i18n_url = i18n_('URL');

  const i18n_omemo = i18n_('OMEMO');

  const i18n_profile = i18n_('Profile');

  const navigation = lit_html_html`
        <ul class="nav nav-pills justify-content-center">
            <li role="presentation" class="nav-item">
                <a class="nav-link active" id="profile-tab" href="#profile-tabpanel" aria-controls="profile-tabpanel" role="tab" data-toggle="tab">${i18n_profile}</a>
            </li>
            <li role="presentation" class="nav-item">
                <a class="nav-link" id="omemo-tab" href="#omemo-tabpanel" aria-controls="omemo-tabpanel" role="tab" data-toggle="tab">${i18n_omemo}</a>
            </li>
        </ul>`;
  return lit_html_html`
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="user-profile-modal-label">${heading_profile}</h5>
                    ${modal_header_close_button}
                </div>
                <div class="modal-body">
                    <span class="modal-alert"></span>
                    ${converse_core_converse.pluggable.plugins['converse-omemo'].enabled(converse_core_converse) && navigation || ''}
                    <div class="tab-content">
                        <div class="tab-pane active" id="profile-tabpanel" role="tabpanel" aria-labelledby="profile-tab">
                            <form class="converse-form converse-form--modal profile-form" action="#">
                                <div class="row">
                                    <div class="col-auto">
                                        <converse-image-picker image="${o.image}" width="${o.width}" height="${o.height}"></converse-image-picker>
                                    </div>
                                    <div class="col">
                                        <div class="form-group">
                                            <label class="col-form-label">${i18n_jid}:</label>
                                            <div>${o.jid}</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="vcard-fullname" class="col-form-label">${i18n_fullname}:</label>
                                    <input id="vcard-fullname" type="text" class="form-control" name="fn" value="${o.fullname || ''}"/>
                                </div>
                                <div class="form-group">
                                    <label for="vcard-nickname" class="col-form-label">${i18n_nickname}:</label>
                                    <input id="vcard-nickname" type="text" class="form-control" name="nickname" value="${o.nickname || ''}"/>
                                </div>
                                <div class="form-group">
                                    <label for="vcard-url" class="col-form-label">${i18n_url}:</label>
                                    <input id="vcard-url" type="url" class="form-control" name="url" value="${o.url || ''}"/>
                                </div>
                                <div class="form-group">
                                    <label for="vcard-email" class="col-form-label">${i18n_email}:</label>
                                    <input id="vcard-email" type="email" class="form-control" name="email" value="${o.email || ''}"/>
                                </div>
                                <div class="form-group">
                                    <label for="vcard-role" class="col-form-label">${i18n_role}:</label>
                                    <input id="vcard-role" type="text" class="form-control" name="role" value="${o.role || ''}" aria-describedby="vcard-role-help"/>
                                    <small id="vcard-role-help" class="form-text text-muted">${i18n_role_help}</small>
                                </div>
                                <hr/>
                                <div class="form-group">
                                    <button type="submit" class="save-form btn btn-primary">${i18n_save}</button>
                                </div>
                            </form>
                        </div>
                        ${converse_core_converse.pluggable.plugins['converse-omemo'].enabled(converse_core_converse) && omemo_page(o) || ''}
                    </div>
                </div>
            </div>
        </div>
    `;
});
// CONCATENATED MODULE: ./src/converse-profile.js
/**
 * @module converse-profile
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */












const {
  sizzle: converse_profile_sizzle,
  u: converse_profile_u
} = converse.env;
converse.plugins.add('converse-profile', {
  dependencies: ["converse-status", "converse-modal", "converse-vcard", "converse-chatboxviews"],

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    converse_core_api.settings.extend({
      'allow_adhoc_commands': true,
      'show_client_info': true
    });
    converse_core_converse.ProfileModal = BootstrapModal.extend({
      id: "user-profile-modal",
      events: {
        'submit .profile-form': 'onFormSubmitted'
      },

      initialize() {
        this.listenTo(this.model, 'change', this.render);
        BootstrapModal.prototype.initialize.apply(this, arguments);
        /**
         * Triggered when the _converse.ProfileModal has been created and initialized.
         * @event _converse#profileModalInitialized
         * @type { _converse.XMPPStatus }
         * @example _converse.api.listen.on('profileModalInitialized', status => { ... });
         */

        converse_core_api.trigger('profileModalInitialized', this.model);
      },

      toHTML() {
        return profile_modal(Object.assign(this.model.toJSON(), this.model.vcard.toJSON(), this.getAvatarData(), {
          'view': this
        }));
      },

      getAvatarData() {
        const image_type = this.model.vcard.get('image_type');
        const image_data = this.model.vcard.get('image');
        const image = "data:" + image_type + ";base64," + image_data;
        return {
          'height': 128,
          'width': 128,
          image
        };
      },

      afterRender() {
        this.tabs = converse_profile_sizzle('.nav-item .nav-link', this.el).map(e => new bootstrap_native_default.a.Tab(e));
      },

      async setVCard(data) {
        try {
          await converse_core_api.vcard.set(converse_core_converse.bare_jid, data);
        } catch (err) {
          headless_log.fatal(err);
          this.alert([i18n_("Sorry, an error happened while trying to save your profile data."), i18n_("You can check your browser's developer console for any error output.")].join(" "));
          return;
        }

        this.modal.hide();
      },

      onFormSubmitted(ev) {
        ev.preventDefault();
        const reader = new FileReader();
        const form_data = new FormData(ev.target);
        const image_file = form_data.get('image');
        const data = {
          'fn': form_data.get('fn'),
          'nickname': form_data.get('nickname'),
          'role': form_data.get('role'),
          'email': form_data.get('email'),
          'url': form_data.get('url')
        };

        if (!image_file.size) {
          Object.assign(data, {
            'image': this.model.vcard.get('image'),
            'image_type': this.model.vcard.get('image_type')
          });
          this.setVCard(data);
        } else {
          reader.onloadend = () => {
            Object.assign(data, {
              'image': btoa(reader.result),
              'image_type': image_file.type
            });
            this.setVCard(data);
          };

          reader.readAsBinaryString(image_file);
        }
      }

    });
    converse_core_converse.ChatStatusModal = BootstrapModal.extend({
      id: "modal-status-change",
      events: {
        "submit form#set-xmpp-status": "onFormSubmitted",
        "click .clear-input": "clearStatusMessage"
      },

      toHTML() {
        return chat_status_modal(Object.assign(this.model.toJSON(), this.model.vcard.toJSON(), {
          'label_away': i18n_('Away'),
          'label_busy': i18n_('Busy'),
          'label_cancel': i18n_('Cancel'),
          'label_close': i18n_('Close'),
          'label_custom_status': i18n_('Custom status'),
          'label_offline': i18n_('Offline'),
          'label_online': i18n_('Online'),
          'label_save': i18n_('Save'),
          'label_xa': i18n_('Away for long'),
          'modal_title': i18n_('Change chat status'),
          'placeholder_status_message': i18n_('Personal status message')
        }));
      },

      afterRender() {
        this.el.addEventListener('shown.bs.modal', () => {
          this.el.querySelector('input[name="status_message"]').focus();
        }, false);
      },

      clearStatusMessage(ev) {
        if (ev && ev.preventDefault) {
          ev.preventDefault();
          converse_profile_u.hideElement(this.el.querySelector('.clear-input'));
        }

        const roster_filter = this.el.querySelector('input[name="status_message"]');
        roster_filter.value = '';
      },

      onFormSubmitted(ev) {
        ev.preventDefault();
        const data = new FormData(ev.target);
        this.model.save({
          'status_message': data.get('status_message'),
          'status': data.get('chat_status')
        });
        this.modal.hide();
      }

    });
    converse_core_converse.XMPPStatusView = converse_core_converse.ViewWithAvatar.extend({
      tagName: "div",
      events: {
        "click a.show-profile": "showProfileModal",
        "click a.change-status": "showStatusChangeModal",
        "click .logout": "logOut"
      },

      initialize() {
        this.listenTo(this.model, "change", this.render);
        this.listenTo(this.model.vcard, "change", this.render);
      },

      toHTML() {
        const chat_status = this.model.get('status') || 'offline';
        return profile(Object.assign(this.model.toJSON(), this.model.vcard.toJSON(), {
          chat_status,
          'fullname': this.model.vcard.get('fullname') || converse_core_converse.bare_jid,
          "showUserSettingsModal": ev => this.showUserSettingsModal(ev),
          'status_message': this.model.get('status_message') || i18n_("I am %1$s", this.getPrettyStatus(chat_status))
        }));
      },

      afterRender() {
        this.renderAvatar();
      },

      showProfileModal(ev) {
        ev.preventDefault();

        if (this.profile_modal === undefined) {
          this.profile_modal = new converse_core_converse.ProfileModal({
            model: this.model
          });
        }

        this.profile_modal.show(ev);
      },

      showStatusChangeModal(ev) {
        ev.preventDefault();

        if (this.status_modal === undefined) {
          this.status_modal = new converse_core_converse.ChatStatusModal({
            model: this.model
          });
        }

        this.status_modal.show(ev);
      },

      showUserSettingsModal(ev) {
        ev.preventDefault();

        if (this.user_settings_modal === undefined) {
          this.user_settings_modal = new modals_user_settings({
            model: this.model,
            _converse: converse_core_converse
          });
        }

        this.user_settings_modal.show(ev);
      },

      logOut(ev) {
        ev.preventDefault();
        const result = confirm(i18n_("Are you sure you want to log out?"));

        if (result === true) {
          converse_core_api.user.logout();
        }
      },

      getPrettyStatus(stat) {
        if (stat === 'chat') {
          return i18n_('online');
        } else if (stat === 'dnd') {
          return i18n_('busy');
        } else if (stat === 'xa') {
          return i18n_('away for long');
        } else if (stat === 'away') {
          return i18n_('away');
        } else if (stat === 'offline') {
          return i18n_('offline');
        } else {
          return i18n_(stat) || i18n_('online');
        }
      }

    });
    /******************** Event Handlers ********************/

    converse_core_api.listen.on('controlBoxPaneInitialized', async view => {
      await converse_core_api.waitUntil('VCardsInitialized');
      converse_core_converse.xmppstatusview = new converse_core_converse.XMPPStatusView({
        'model': converse_core_converse.xmppstatus
      });
      view.el.insertAdjacentElement('afterBegin', converse_core_converse.xmppstatusview.render().el);
    });
  }

});
// CONCATENATED MODULE: ./node_modules/lodash-es/concat.js




/**
 * Creates a new array concatenating `array` with any additional arrays
 * and/or values.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Array
 * @param {Array} array The array to concatenate.
 * @param {...*} [values] The values to concatenate.
 * @returns {Array} Returns the new concatenated array.
 * @example
 *
 * var array = [1];
 * var other = _.concat(array, 2, [3], [[4]]);
 *
 * console.log(other);
 * // => [1, 2, 3, [4]]
 *
 * console.log(array);
 * // => [1]
 */

function concat() {
  var length = arguments.length;

  if (!length) {
    return [];
  }

  var args = Array(length - 1),
      array = arguments[0],
      index = length;

  while (index--) {
    args[index - 1] = arguments[index];
  }

  return _arrayPush(lodash_es_isArray(array) ? _copyArray(array) : [array], _baseFlatten(args, 1));
}

/* harmony default export */ var lodash_es_concat = (concat);
// CONCATENATED MODULE: ./node_modules/lodash-es/_baseRange.js
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
    _baseRange_nativeMax = Math.max;
/**
 * The base implementation of `_.range` and `_.rangeRight` which doesn't
 * coerce arguments.
 *
 * @private
 * @param {number} start The start of the range.
 * @param {number} end The end of the range.
 * @param {number} step The value to increment or decrement by.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Array} Returns the range of numbers.
 */

function baseRange(start, end, step, fromRight) {
  var index = -1,
      length = _baseRange_nativeMax(nativeCeil((end - start) / (step || 1)), 0),
      result = Array(length);

  while (length--) {
    result[fromRight ? length : ++index] = start;
    start += step;
  }

  return result;
}

/* harmony default export */ var _baseRange = (baseRange);
// CONCATENATED MODULE: ./node_modules/lodash-es/_createRange.js



/**
 * Creates a `_.range` or `_.rangeRight` function.
 *
 * @private
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new range function.
 */

function createRange(fromRight) {
  return function (start, end, step) {
    if (step && typeof step != 'number' && _isIterateeCall(start, end, step)) {
      end = step = undefined;
    } // Ensure the sign of `-0` is preserved.


    start = lodash_es_toFinite(start);

    if (end === undefined) {
      end = start;
      start = 0;
    } else {
      end = lodash_es_toFinite(end);
    }

    step = step === undefined ? start < end ? 1 : -1 : lodash_es_toFinite(step);
    return _baseRange(start, end, step, fromRight);
  };
}

/* harmony default export */ var _createRange = (createRange);
// CONCATENATED MODULE: ./node_modules/lodash-es/range.js

/**
 * Creates an array of numbers (positive and/or negative) progressing from
 * `start` up to, but not including, `end`. A step of `-1` is used if a negative
 * `start` is specified without an `end` or `step`. If `end` is not specified,
 * it's set to `start` with `start` then set to `0`.
 *
 * **Note:** JavaScript follows the IEEE-754 standard for resolving
 * floating-point values which can produce unexpected results.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {number} [start=0] The start of the range.
 * @param {number} end The end of the range.
 * @param {number} [step=1] The value to increment or decrement by.
 * @returns {Array} Returns the range of numbers.
 * @see _.inRange, _.rangeRight
 * @example
 *
 * _.range(4);
 * // => [0, 1, 2, 3]
 *
 * _.range(-4);
 * // => [0, -1, -2, -3]
 *
 * _.range(1, 5);
 * // => [1, 2, 3, 4]
 *
 * _.range(0, 20, 5);
 * // => [0, 5, 10, 15]
 *
 * _.range(0, -4, -1);
 * // => [0, -1, -2, -3]
 *
 * _.range(1, 4, 0);
 * // => [1, 1, 1]
 *
 * _.range(0);
 * // => []
 */

var range = _createRange();
/* harmony default export */ var lodash_es_range = (range);
// CONCATENATED MODULE: ./src/converse-omemo.js
/**
 * @module converse-omemo
 * @copyright The Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */

/* global libsignal */








const {
  Strophe: converse_omemo_Strophe,
  sizzle: converse_omemo_sizzle,
  $build: converse_omemo_$build,
  $iq: converse_omemo_$iq,
  $msg: converse_omemo_$msg
} = converse.env;
const converse_omemo_u = converse.env.utils;
converse_omemo_Strophe.addNamespace('OMEMO_DEVICELIST', converse_omemo_Strophe.NS.OMEMO + ".devicelist");
converse_omemo_Strophe.addNamespace('OMEMO_VERIFICATION', converse_omemo_Strophe.NS.OMEMO + ".verification");
converse_omemo_Strophe.addNamespace('OMEMO_WHITELISTED', converse_omemo_Strophe.NS.OMEMO + ".whitelisted");
converse_omemo_Strophe.addNamespace('OMEMO_BUNDLES', converse_omemo_Strophe.NS.OMEMO + ".bundles");
const UNDECIDED = 0;
const TRUSTED = 1; // eslint-disable-line no-unused-vars

const UNTRUSTED = -1;
const TAG_LENGTH = 128;
const KEY_ALGO = {
  'name': "AES-GCM",
  'length': 128
};

class IQError extends Error {
  constructor(message, iq) {
    super(message, iq);
    this.name = 'IQError';
    this.iq = iq;
  }

}

function parseEncryptedMessage(stanza, attrs) {
  if (attrs.is_encrypted && attrs.encrypted.key) {
    // https://xmpp.org/extensions/xep-0384.html#usecases-receiving
    if (attrs.encrypted.prekey === true) {
      return decryptPrekeyWhisperMessage(attrs);
    } else {
      return decryptWhisperMessage(attrs);
    }
  } else {
    return attrs;
  }
}

function onChatBoxesInitialized() {
  converse_core_converse.chatboxes.on('add', chatbox => {
    checkOMEMOSupported(chatbox);

    if (chatbox.get('type') === converse_core_converse.CHATROOMS_TYPE) {
      chatbox.occupants.on('add', o => onOccupantAdded(chatbox, o));
      chatbox.features.on('change', () => checkOMEMOSupported(chatbox));
    }
  });
}

function onChatInitialized(view) {
  view.listenTo(view.model.messages, 'add', message => {
    if (message.get('is_encrypted') && !message.get('is_error')) {
      view.model.save('omemo_supported', true);
    }
  });
  view.listenTo(view.model, 'change:omemo_supported', () => {
    if (!view.model.get('omemo_supported') && view.model.get('omemo_active')) {
      view.model.set('omemo_active', false);
    } else {
      var _view$el$querySelecto;

      // Manually trigger an update, setting omemo_active to
      // false above will automatically trigger one.
      (_view$el$querySelecto = view.el.querySelector('converse-chat-toolbar')) === null || _view$el$querySelecto === void 0 ? void 0 : _view$el$querySelecto.requestUpdate();
    }
  });
  view.listenTo(view.model, 'change:omemo_active', () => {
    view.el.querySelector('converse-chat-toolbar').requestUpdate();
  });
}

const omemo = converse.env.omemo = {
  async encryptMessage(plaintext) {
    // The client MUST use fresh, randomly generated key/IV pairs
    // with AES-128 in Galois/Counter Mode (GCM).
    // For GCM a 12 byte IV is strongly suggested as other IV lengths
    // will require additional calculations. In principle any IV size
    // can be used as long as the IV doesn't ever repeat. NIST however
    // suggests that only an IV size of 12 bytes needs to be supported
    // by implementations.
    //
    // https://crypto.stackexchange.com/questions/26783/ciphertext-and-tag-size-and-iv-transmission-with-aes-in-gcm-mode
    const iv = crypto.getRandomValues(new window.Uint8Array(12)),
          key = await crypto.subtle.generateKey(KEY_ALGO, true, ["encrypt", "decrypt"]),
          algo = {
      'name': 'AES-GCM',
      'iv': iv,
      'tagLength': TAG_LENGTH
    },
          encrypted = await crypto.subtle.encrypt(algo, key, converse_omemo_u.stringToArrayBuffer(plaintext)),
          length = encrypted.byteLength - (128 + 7 >> 3),
          ciphertext = encrypted.slice(0, length),
          tag = encrypted.slice(length),
          exported_key = await crypto.subtle.exportKey("raw", key);
    return {
      'key': exported_key,
      'tag': tag,
      'key_and_tag': converse_omemo_u.appendArrayBuffer(exported_key, tag),
      'payload': converse_omemo_u.arrayBufferToBase64(ciphertext),
      'iv': converse_omemo_u.arrayBufferToBase64(iv)
    };
  },

  async decryptMessage(obj) {
    const key_obj = await crypto.subtle.importKey('raw', obj.key, KEY_ALGO, true, ['encrypt', 'decrypt']);
    const cipher = converse_omemo_u.appendArrayBuffer(converse_omemo_u.base64ToArrayBuffer(obj.payload), obj.tag);
    const algo = {
      'name': "AES-GCM",
      'iv': converse_omemo_u.base64ToArrayBuffer(obj.iv),
      'tagLength': TAG_LENGTH
    };
    return converse_omemo_u.arrayBufferToString(await crypto.subtle.decrypt(algo, key_obj, cipher));
  }

};

function getSessionCipher(jid, id) {
  const address = new libsignal.SignalProtocolAddress(jid, id);
  return new window.libsignal.SessionCipher(converse_core_converse.omemo_store, address);
}

async function handleDecryptedWhisperMessage(attrs, key_and_tag) {
  const encrypted = attrs.encrypted;

  const devicelist = converse_core_converse.devicelists.getDeviceList(attrs.from);

  await devicelist._devices_promise;
  let device = devicelist.get(encrypted.device_id);

  if (!device) {
    device = await devicelist.devices.create({
      'id': encrypted.device_id,
      'jid': attrs.from
    }, {
      'promise': true
    });
  }

  if (encrypted.payload) {
    const key = key_and_tag.slice(0, 16);
    const tag = key_and_tag.slice(16);
    const result = await omemo.decryptMessage(Object.assign(encrypted, {
      'key': key,
      'tag': tag
    }));
    device.save('active', true);
    return result;
  }
}

function getDecryptionErrorAttributes(e) {
  if (converse_core_api.settings.get("loglevel") === 'debug') {
    return {
      'error_text': i18n_("Sorry, could not decrypt a received OMEMO message due to an error.") + ` ${e.name} ${e.message}`,
      'error_type': 'Decryption',
      'is_ephemeral': true,
      'is_error': true,
      'type': 'error'
    };
  } else {
    return {};
  }
}

async function decryptPrekeyWhisperMessage(attrs) {
  const session_cipher = getSessionCipher(attrs.from, parseInt(attrs.encrypted.device_id, 10));
  const key = converse_omemo_u.base64ToArrayBuffer(attrs.encrypted.key);
  let key_and_tag;

  try {
    key_and_tag = await session_cipher.decryptPreKeyWhisperMessage(key, 'binary');
  } catch (e) {
    // TODO from the XEP:
    // There are various reasons why decryption of an
    // OMEMOKeyExchange or an OMEMOAuthenticatedMessage
    // could fail. One reason is if the message was
    // received twice and already decrypted once, in this
    // case the client MUST ignore the decryption failure
    // and not show any warnings/errors. In all other cases
    // of decryption failure, clients SHOULD respond by
    // forcibly doing a new key exchange and sending a new
    // OMEMOKeyExchange with a potentially empty SCE
    // payload. By building a new session with the original
    // sender this way, the invalid session of the original
    // sender will get overwritten with this newly created,
    // valid session.
    headless_log.error(`${e.name} ${e.message}`);
    return Object.assign(attrs, getDecryptionErrorAttributes(e));
  } // TODO from the XEP:
  // When a client receives the first message for a given
  // ratchet key with a counter of 53 or higher, it MUST send
  // a heartbeat message. Heartbeat messages are normal OMEMO
  // encrypted messages where the SCE payload does not include
  // any elements. These heartbeat messages cause the ratchet
  // to forward, thus consequent messages will have the
  // counter restarted from 0.


  try {
    const plaintext = await handleDecryptedWhisperMessage(attrs, key_and_tag);
    await converse_core_converse.omemo_store.generateMissingPreKeys();
    await converse_core_converse.omemo_store.publishBundle();

    if (plaintext) {
      return Object.assign(attrs, {
        'plaintext': plaintext
      });
    } else {
      return Object.assign(attrs, {
        'is_only_key': true
      });
    }
  } catch (e) {
    headless_log.error(`${e.name} ${e.message}`);
    return Object.assign(attrs, getDecryptionErrorAttributes(e));
  }
}

async function decryptWhisperMessage(attrs) {
  const from_jid = attrs.from_muc ? attrs.from_real_jid : attrs.from;

  if (!from_jid) {
    Object.assign(attrs, {
      'error_text': i18n_("Sorry, could not decrypt a received OMEMO because we don't have the JID for that user."),
      'error_type': 'Decryption',
      'is_ephemeral': false,
      'is_error': true,
      'type': 'error'
    });
  }

  const session_cipher = getSessionCipher(from_jid, parseInt(attrs.encrypted.device_id, 10));
  const key = converse_omemo_u.base64ToArrayBuffer(attrs.encrypted.key);

  try {
    const key_and_tag = await session_cipher.decryptWhisperMessage(key, 'binary');
    const plaintext = await handleDecryptedWhisperMessage(attrs, key_and_tag);
    return Object.assign(attrs, {
      'plaintext': plaintext
    });
  } catch (e) {
    headless_log.error(`${e.name} ${e.message}`);
    return Object.assign(attrs, getDecryptionErrorAttributes(e));
  }
}

function addKeysToMessageStanza(stanza, dicts, iv) {
  for (const i in dicts) {
    if (Object.prototype.hasOwnProperty.call(dicts, i)) {
      const payload = dicts[i].payload;
      const device = dicts[i].device;
      const prekey = 3 == parseInt(payload.type, 10);
      stanza.c('key', {
        'rid': device.get('id')
      }).t(btoa(payload.body));

      if (prekey) {
        stanza.attrs({
          'prekey': prekey
        });
      }

      stanza.up();

      if (i == dicts.length - 1) {
        stanza.c('iv').t(iv).up().up();
      }
    }
  }

  return Promise.resolve(stanza);
}

function parseBundle(bundle_el) {
  /* Given an XML element representing a user's OMEMO bundle, parse it
   * and return a map.
   */
  const signed_prekey_public_el = bundle_el.querySelector('signedPreKeyPublic');
  const signed_prekey_signature_el = bundle_el.querySelector('signedPreKeySignature');
  const prekeys = converse_omemo_sizzle(`prekeys > preKeyPublic`, bundle_el).map(el => ({
    'id': parseInt(el.getAttribute('preKeyId'), 10),
    'key': el.textContent
  }));
  return {
    'identity_key': bundle_el.querySelector('identityKey').textContent.trim(),
    'signed_prekey': {
      'id': parseInt(signed_prekey_public_el.getAttribute('signedPreKeyId'), 10),
      'public_key': signed_prekey_public_el.textContent,
      'signature': signed_prekey_signature_el.textContent
    },
    'prekeys': prekeys
  };
}

async function generateFingerprint(device) {
  var _device$get;

  if ((_device$get = device.get('bundle')) !== null && _device$get !== void 0 && _device$get.fingerprint) {
    return;
  }

  const bundle = await device.getBundle();
  bundle['fingerprint'] = converse_omemo_u.arrayBufferToHex(converse_omemo_u.base64ToArrayBuffer(bundle['identity_key']));
  device.save('bundle', bundle);
  device.trigger('change:bundle'); // Doesn't get triggered automatically due to pass-by-reference
}

async function getDevicesForContact(jid) {
  await converse_core_api.waitUntil('OMEMOInitialized');

  const devicelist = converse_core_converse.devicelists.get(jid) || converse_core_converse.devicelists.create({
    'jid': jid
  });

  await devicelist.fetchDevices();
  return devicelist.devices;
}

function generateDeviceID() {
  /* Generates a device ID, making sure that it's unique */
  const existing_ids = converse_core_converse.devicelists.get(converse_core_converse.bare_jid).devices.pluck('id');

  let device_id = libsignal.KeyHelper.generateRegistrationId(); // Before publishing a freshly generated device id for the first time,
  // a device MUST check whether that device id already exists, and if so, generate a new one.

  let i = 0;

  while (existing_ids.includes(device_id)) {
    device_id = libsignal.KeyHelper.generateRegistrationId();
    i++;

    if (i === 10) {
      throw new Error("Unable to generate a unique device ID");
    }
  }

  return device_id.toString();
}

async function buildSession(device) {
  // TODO: check device-get('jid') versus the 'from' attribute which is used
  // to build a session when receiving an encrypted message in a MUC.
  // https://github.com/conversejs/converse.js/issues/1481#issuecomment-509183431
  const address = new libsignal.SignalProtocolAddress(device.get('jid'), device.get('id'));
  const sessionBuilder = new libsignal.SessionBuilder(converse_core_converse.omemo_store, address);
  const prekey = device.getRandomPreKey();
  const bundle = await device.getBundle();
  return sessionBuilder.processPreKey({
    'registrationId': parseInt(device.get('id'), 10),
    'identityKey': converse_omemo_u.base64ToArrayBuffer(bundle.identity_key),
    'signedPreKey': {
      'keyId': bundle.signed_prekey.id,
      // <Number>
      'publicKey': converse_omemo_u.base64ToArrayBuffer(bundle.signed_prekey.public_key),
      'signature': converse_omemo_u.base64ToArrayBuffer(bundle.signed_prekey.signature)
    },
    'preKey': {
      'keyId': prekey.id,
      // <Number>
      'publicKey': converse_omemo_u.base64ToArrayBuffer(prekey.key)
    }
  });
}

async function getSession(device) {
  if (!device.get('bundle')) {
    headless_log.error(`Could not build an OMEMO session for device ${device.get('id')} because we don't have its bundle`);
    return null;
  }

  const address = new libsignal.SignalProtocolAddress(device.get('jid'), device.get('id'));
  const session = await converse_core_converse.omemo_store.loadSession(address.toString());

  if (session) {
    return session;
  } else {
    try {
      const session = await buildSession(device);
      return session;
    } catch (e) {
      headless_log.error(`Could not build an OMEMO session for device ${device.get('id')}`);
      headless_log.error(e);
      return null;
    }
  }
}

function updateBundleFromStanza(stanza) {
  const items_el = converse_omemo_sizzle(`items`, stanza).pop();

  if (!items_el || !items_el.getAttribute('node').startsWith(converse_omemo_Strophe.NS.OMEMO_BUNDLES)) {
    return;
  }

  const device_id = items_el.getAttribute('node').split(':')[1];
  const jid = stanza.getAttribute('from');
  const bundle_el = converse_omemo_sizzle(`item > bundle`, items_el).pop();

  const devicelist = converse_core_converse.devicelists.getDeviceList(jid);

  const device = devicelist.devices.get(device_id) || devicelist.devices.create({
    'id': device_id,
    'jid': jid
  });
  device.save({
    'bundle': parseBundle(bundle_el)
  });
}

function updateDevicesFromStanza(stanza) {
  const items_el = converse_omemo_sizzle(`items[node="${converse_omemo_Strophe.NS.OMEMO_DEVICELIST}"]`, stanza).pop();

  if (!items_el) {
    return;
  }

  const device_selector = `item list[xmlns="${converse_omemo_Strophe.NS.OMEMO}"] device`;
  const device_ids = converse_omemo_sizzle(device_selector, items_el).map(d => d.getAttribute('id'));
  const jid = stanza.getAttribute('from');

  const devicelist = converse_core_converse.devicelists.getDeviceList(jid);

  const devices = devicelist.devices;
  const removed_ids = lodash_es_difference(devices.pluck('id'), device_ids);
  removed_ids.forEach(id => {
    if (jid === converse_core_converse.bare_jid && id === converse_core_converse.omemo_store.get('device_id')) {
      return; // We don't set the current device as inactive
    }

    devices.get(id).save('active', false);
  });
  device_ids.forEach(device_id => {
    const device = devices.get(device_id);

    if (device) {
      device.save('active', true);
    } else {
      devices.create({
        'id': device_id,
        'jid': jid
      });
    }
  });

  if (converse_omemo_u.isSameBareJID(jid, converse_core_converse.bare_jid)) {
    // Make sure our own device is on the list
    // (i.e. if it was removed, add it again).
    devicelist.publishCurrentDevice(device_ids);
  }
}

function registerPEPPushHandler() {
  // Add a handler for devices pushed from other connected clients
  converse_core_converse.connection.addHandler(message => {
    try {
      if (converse_omemo_sizzle(`event[xmlns="${converse_omemo_Strophe.NS.PUBSUB}#event"]`, message).length) {
        updateDevicesFromStanza(message);
        updateBundleFromStanza(message);
      }
    } catch (e) {
      headless_log.error(e.message);
    }

    return true;
  }, null, 'message', 'headline');
}

function restoreOMEMOSession() {
  if (converse_core_converse.omemo_store === undefined) {
    const id = `converse.omemosession-${converse_core_converse.bare_jid}`;
    converse_core_converse.omemo_store = new converse_core_converse.OMEMOStore({
      'id': id
    });
    converse_core_converse.omemo_store.browserStorage = converse_core_converse.createStore(id);
  }

  return converse_core_converse.omemo_store.fetchSession();
}

function fetchDeviceLists() {
  return new Promise((success, error) => converse_core_converse.devicelists.fetch({
    success,
    'error': (m, e) => error(e)
  }));
}

async function fetchOwnDevices() {
  await fetchDeviceLists();

  let own_devicelist = converse_core_converse.devicelists.get(converse_core_converse.bare_jid);

  if (own_devicelist) {
    own_devicelist.fetchDevices();
  } else {
    own_devicelist = await converse_core_converse.devicelists.create({
      'jid': converse_core_converse.bare_jid
    }, {
      'promise': true
    });
  }

  return own_devicelist._devices_promise;
}

async function initOMEMO() {
  if (!converse_core_converse.config.get('trusted') || converse_core_api.settings.get('clear_cache_on_logout')) {
    headless_log.warn("Not initializing OMEMO, since this browser is not trusted or clear_cache_on_logout is set to true");
    return;
  }

  converse_core_converse.devicelists = new converse_core_converse.DeviceLists();
  const id = `converse.devicelists-${converse_core_converse.bare_jid}`;
  converse_core_converse.devicelists.browserStorage = converse_core_converse.createStore(id);

  try {
    await fetchOwnDevices();
    await restoreOMEMOSession();
    await converse_core_converse.omemo_store.publishBundle();
  } catch (e) {
    headless_log.error("Could not initialize OMEMO support");
    headless_log.error(e);
    return;
  }
  /**
   * Triggered once OMEMO support has been initialized
   * @event _converse#OMEMOInitialized
   * @example _converse.api.listen.on('OMEMOInitialized', () => { ... }); */


  converse_core_api.trigger('OMEMOInitialized');
}

async function onOccupantAdded(chatroom, occupant) {
  if (occupant.isSelf() || !chatroom.features.get('nonanonymous') || !chatroom.features.get('membersonly')) {
    return;
  }

  if (chatroom.get('omemo_active')) {
    const supported = await converse_core_converse.contactHasOMEMOSupport(occupant.get('jid'));

    if (!supported) {
      chatroom.createMessage({
        'message': i18n_("%1$s doesn't appear to have a client that supports OMEMO. " + "Encrypted chat will no longer be possible in this grouchat.", occupant.get('nick')),
        'type': 'error'
      });
      chatroom.save({
        'omemo_active': false,
        'omemo_supported': false
      });
    }
  }
}

async function checkOMEMOSupported(chatbox) {
  let supported;

  if (chatbox.get('type') === converse_core_converse.CHATROOMS_TYPE) {
    await converse_core_api.waitUntil('OMEMOInitialized');
    supported = chatbox.features.get('nonanonymous') && chatbox.features.get('membersonly');
  } else if (chatbox.get('type') === converse_core_converse.PRIVATE_CHAT_TYPE) {
    supported = await converse_core_converse.contactHasOMEMOSupport(chatbox.get('jid'));
  }

  chatbox.set('omemo_supported', supported);

  if (supported && converse_core_api.settings.get('omemo_default')) {
    chatbox.set('omemo_active', true);
  }
}

function toggleOMEMO(ev) {
  ev.stopPropagation();
  ev.preventDefault();
  const toolbar_el = converse_omemo_u.ancestor(ev.target, 'converse-chat-toolbar');

  if (!toolbar_el.model.get('omemo_supported')) {
    let messages;

    if (toolbar_el.model.get('type') === converse_core_converse.CHATROOMS_TYPE) {
      messages = [i18n_('Cannot use end-to-end encryption in this groupchat, ' + 'either the groupchat has some anonymity or not all participants support OMEMO.')];
    } else {
      messages = [i18n_("Cannot use end-to-end encryption because %1$s uses a client that doesn't support OMEMO.", toolbar_el.model.contact.getDisplayName())];
    }

    return converse_core_api.alert('error', i18n_('Error'), messages);
  }

  toolbar_el.model.save({
    'omemo_active': !toolbar_el.model.get('omemo_active')
  });
}

function getOMEMOToolbarButton(toolbar_el, buttons) {
  const model = toolbar_el.model;

  const is_muc = model.get('type') === converse_core_converse.CHATROOMS_TYPE;

  let title;

  if (is_muc && model.get('omemo_supported')) {
    const i18n_plaintext = i18n_('Messages are being sent in plaintext');

    const i18n_encrypted = i18n_('Messages are sent encrypted');

    title = model.get('omemo_active') ? i18n_encrypted : i18n_plaintext;
  } else {
    title = i18n_('This groupchat needs to be members-only and non-anonymous in ' + 'order to support OMEMO encrypted messages');
  }

  buttons.push(lit_html_html`
        <button class="toggle-omemo"
                title="${title}"
                ?disabled=${!model.get('omemo_supported')}
                @click=${toggleOMEMO}>
        <converse-icon class="fa ${model.get('omemo_active') ? `fa-lock` : `fa-unlock`}"
                    path-prefix="${converse_core_api.settings.get('assets_path')}" size="1em"
                    color="${model.get('omemo_active') ? `var(--info-color)` : `var(--error-color)`}"
        ></converse-icon>
        </button>`);
  return buttons;
}
/**
 * Mixin object that contains OMEMO-related methods for
 * {@link _converse.ChatBox} or {@link _converse.ChatRoom} objects.
 *
 * @typedef {Object} OMEMOEnabledChatBox
 */


const OMEMOEnabledChatBox = {
  encryptKey(plaintext, device) {
    return getSessionCipher(device.get('jid'), device.get('id')).encrypt(plaintext).then(payload => ({
      'payload': payload,
      'device': device
    }));
  },

  handleMessageSendError(e) {
    if (e.name === 'IQError') {
      this.save('omemo_supported', false);
      const err_msgs = [];

      if (converse_omemo_sizzle(`presence-subscription-required[xmlns="${converse_omemo_Strophe.NS.PUBSUB_ERROR}"]`, e.iq).length) {
        err_msgs.push(i18n_("Sorry, we're unable to send an encrypted message because %1$s " + "requires you to be subscribed to their presence in order to see their OMEMO information", e.iq.getAttribute('from')));
      } else if (converse_omemo_sizzle(`remote-server-not-found[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]`, e.iq).length) {
        err_msgs.push(i18n_("Sorry, we're unable to send an encrypted message because the remote server for %1$s could not be found", e.iq.getAttribute('from')));
      } else {
        err_msgs.push(i18n_("Unable to send an encrypted message due to an unexpected error."));
        err_msgs.push(e.iq.outerHTML);
      }

      converse_core_api.alert('error', i18n_('Error'), err_msgs);
      headless_log.error(e);
    } else if (e.user_facing) {
      converse_core_api.alert('error', i18n_('Error'), [e.message]);
      headless_log.error(e);
    } else {
      throw e;
    }
  }

};
converse.plugins.add('converse-omemo', {
  enabled(_converse) {
    return window.libsignal && _converse.config.get('trusted') && !converse_core_api.settings.get('clear_cache_on_logout') && !_converse.api.settings.get("blacklisted_plugins").includes('converse-omemo');
  },

  dependencies: ["converse-chatview", "converse-pubsub", "converse-profile"],
  overrides: {
    ProfileModal: {
      events: {
        'change input.select-all': 'selectAll',
        'click .generate-bundle': 'generateOMEMODeviceBundle',
        'submit .fingerprint-removal': 'removeSelectedFingerprints'
      },

      initialize() {
        this.debouncedRender = lodash_es_debounce(this.render, 50);
        this.devicelist = converse_core_converse.devicelists.get(converse_core_converse.bare_jid);
        this.listenTo(this.devicelist.devices, 'change:bundle', this.debouncedRender);
        this.listenTo(this.devicelist.devices, 'reset', this.debouncedRender);
        this.listenTo(this.devicelist.devices, 'reset', this.debouncedRender);
        this.listenTo(this.devicelist.devices, 'remove', this.debouncedRender);
        this.listenTo(this.devicelist.devices, 'add', this.debouncedRender);
        return this.__super__.initialize.apply(this, arguments);
      },

      beforeRender() {
        const device_id = converse_core_converse.omemo_store.get('device_id');

        if (device_id) {
          this.current_device = this.devicelist.devices.get(device_id);
        }

        this.other_devices = this.devicelist.devices.filter(d => d.get('id') !== device_id);

        if (this.__super__.beforeRender) {
          return this.__super__.beforeRender.apply(this, arguments);
        }
      },

      selectAll(ev) {
        let sibling = converse_omemo_u.ancestor(ev.target, 'li');

        while (sibling) {
          sibling.querySelector('input[type="checkbox"]').checked = ev.target.checked;
          sibling = sibling.nextElementSibling;
        }
      },

      removeSelectedFingerprints(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        ev.target.querySelector('.select-all').checked = false;
        const device_ids = converse_omemo_sizzle('.fingerprint-removal-item input[type="checkbox"]:checked', ev.target).map(c => c.value);
        this.devicelist.removeOwnDevices(device_ids).then(this.modal.hide).catch(err => {
          headless_log.error(err);

          converse_core_converse.api.alert(converse_omemo_Strophe.LogLevel.ERROR, i18n_('Error'), [i18n_('Sorry, an error occurred while trying to remove the devices.')]);
        });
      },

      generateOMEMODeviceBundle(ev) {
        ev.preventDefault();

        if (confirm(i18n_("Are you sure you want to generate new OMEMO keys? " + "This will remove your old keys and all previously encrypted messages will no longer be decryptable on this device."))) {
          converse_core_api.omemo.bundle.generate();
        }
      }

    },
    UserDetailsModal: {
      events: {
        'click .fingerprint-trust .btn input': 'toggleDeviceTrust'
      },

      initialize() {
        const jid = this.model.get('jid');
        this.devicelist = converse_core_converse.devicelists.getDeviceList(jid);
        this.listenTo(this.devicelist.devices, 'change:bundle', this.render);
        this.listenTo(this.devicelist.devices, 'change:trusted', this.render);
        this.listenTo(this.devicelist.devices, 'remove', this.render);
        this.listenTo(this.devicelist.devices, 'add', this.render);
        this.listenTo(this.devicelist.devices, 'reset', this.render);
        return this.__super__.initialize.apply(this, arguments);
      },

      toggleDeviceTrust(ev) {
        const radio = ev.target;
        const device = this.devicelist.devices.get(radio.getAttribute('name'));
        device.save('trusted', parseInt(radio.value, 10));
      }

    },
    ChatBox: {
      async sendMessage(text, spoiler_hint) {
        if (this.get('omemo_active') && text) {
          const attrs = this.getOutgoingMessageAttributes(text, spoiler_hint);
          attrs['is_encrypted'] = true;
          attrs['plaintext'] = attrs.message;
          let message, stanza;

          try {
            const devices = await converse_core_converse.getBundlesAndBuildSessions(this);
            message = await this.createMessage(attrs);
            stanza = await converse_core_converse.createOMEMOMessageStanza(this, message, devices);
          } catch (e) {
            this.handleMessageSendError(e);
            return null;
          }

          converse_core_converse.api.send(stanza);

          return message;
        } else {
          return this.__super__.sendMessage.apply(this, arguments);
        }
      }

    }
  },

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by Converse.js's plugin machinery.
     */
    converse_core_api.settings.extend({
      'omemo_default': false
    });
    converse_core_api.promises.add(['OMEMOInitialized']);
    converse_core_converse.NUM_PREKEYS = 100; // Set here so that tests can override

    Object.assign(converse_core_converse.ChatBox.prototype, OMEMOEnabledChatBox);

    converse_core_converse.generateFingerprints = async function (jid) {
      const devices = await getDevicesForContact(jid);
      return Promise.all(devices.map(d => generateFingerprint(d)));
    };

    converse_core_converse.getDeviceForContact = function (jid, device_id) {
      return getDevicesForContact(jid).then(devices => devices.get(device_id));
    };

    converse_core_converse.contactHasOMEMOSupport = async function (jid) {
      /* Checks whether the contact advertises any OMEMO-compatible devices. */
      const devices = await getDevicesForContact(jid);
      return devices.length > 0;
    };

    converse_core_converse.getBundlesAndBuildSessions = async function (chatbox) {
      const no_devices_err = i18n_("Sorry, no devices found to which we can send an OMEMO encrypted message.");

      let devices;

      if (chatbox.get('type') === converse_core_converse.CHATROOMS_TYPE) {
        const collections = await Promise.all(chatbox.occupants.map(o => getDevicesForContact(o.get('jid'))));
        devices = collections.reduce((a, b) => lodash_es_concat(a, b.models), []);
      } else if (chatbox.get('type') === converse_core_converse.PRIVATE_CHAT_TYPE) {
        const their_devices = await getDevicesForContact(chatbox.get('jid'));

        if (their_devices.length === 0) {
          const err = new Error(no_devices_err);
          err.user_facing = true;
          throw err;
        }

        const own_devices = converse_core_converse.devicelists.get(converse_core_converse.bare_jid).devices;

        devices = [...own_devices.models, ...their_devices.models];
      } // Filter out our own device


      const id = converse_core_converse.omemo_store.get('device_id');

      devices = devices.filter(d => d.get('id') !== id); // Fetch bundles if necessary

      await Promise.all(devices.map(d => d.getBundle()));
      const sessions = devices.filter(d => d).map(d => getSession(d));
      await Promise.all(sessions);

      if (sessions.includes(null)) {
        // We couldn't build a session for certain devices.
        devices = devices.filter(d => sessions[devices.indexOf(d)]);

        if (devices.length === 0) {
          const err = new Error(no_devices_err);
          err.user_facing = true;
          throw err;
        }
      }

      return devices;
    };

    converse_core_converse.createOMEMOMessageStanza = function (chatbox, message, devices) {
      const body = i18n_("This is an OMEMO encrypted message which your client doesn’t seem to support. " + "Find more information on https://conversations.im/omemo");

      if (!message.get('message')) {
        throw new Error("No message body to encrypt!");
      }

      const stanza = converse_omemo_$msg({
        'from': converse_core_converse.connection.jid,
        'to': chatbox.get('jid'),
        'type': chatbox.get('message_type'),
        'id': message.get('msgid')
      }).c('body').t(body).up();

      if (message.get('type') === 'chat') {
        stanza.c('request', {
          'xmlns': converse_omemo_Strophe.NS.RECEIPTS
        }).up();
      } // An encrypted header is added to the message for
      // each device that is supposed to receive it.
      // These headers simply contain the key that the
      // payload message is encrypted with,
      // and they are separately encrypted using the
      // session corresponding to the counterpart device.


      stanza.c('encrypted', {
        'xmlns': converse_omemo_Strophe.NS.OMEMO
      }).c('header', {
        'sid': converse_core_converse.omemo_store.get('device_id')
      });
      return omemo.encryptMessage(message.get('message')).then(obj => {
        // The 16 bytes key and the GCM authentication tag (The tag
        // SHOULD have at least 128 bit) are concatenated and for each
        // intended recipient device, i.e. both own devices as well as
        // devices associated with the contact, the result of this
        // concatenation is encrypted using the corresponding
        // long-standing SignalProtocol session.
        const promises = devices.filter(device => device.get('trusted') != UNTRUSTED && device.get('active')).map(device => chatbox.encryptKey(obj.key_and_tag, device));
        return Promise.all(promises).then(dicts => addKeysToMessageStanza(stanza, dicts, obj.iv)).then(stanza => {
          stanza.c('payload').t(obj.payload).up().up();
          stanza.c('store', {
            'xmlns': converse_omemo_Strophe.NS.HINTS
          });
          return stanza;
        });
      });
    };

    converse_core_converse.OMEMOStore = model_Model.extend({
      Direction: {
        SENDING: 1,
        RECEIVING: 2
      },

      getIdentityKeyPair() {
        const keypair = this.get('identity_keypair');
        return Promise.resolve({
          'privKey': converse_omemo_u.base64ToArrayBuffer(keypair.privKey),
          'pubKey': converse_omemo_u.base64ToArrayBuffer(keypair.pubKey)
        });
      },

      getLocalRegistrationId() {
        return Promise.resolve(parseInt(this.get('device_id'), 10));
      },

      isTrustedIdentity(identifier, identity_key, direction) {
        // eslint-disable-line no-unused-vars
        if (identifier === null || identifier === undefined) {
          throw new Error("Can't check identity key for invalid key");
        }

        if (!(identity_key instanceof ArrayBuffer)) {
          throw new Error("Expected identity_key to be an ArrayBuffer");
        }

        const trusted = this.get('identity_key' + identifier);

        if (trusted === undefined) {
          return Promise.resolve(true);
        }

        return Promise.resolve(converse_omemo_u.arrayBufferToBase64(identity_key) === trusted);
      },

      loadIdentityKey(identifier) {
        if (identifier === null || identifier === undefined) {
          throw new Error("Can't load identity_key for invalid identifier");
        }

        return Promise.resolve(converse_omemo_u.base64ToArrayBuffer(this.get('identity_key' + identifier)));
      },

      saveIdentity(identifier, identity_key) {
        if (identifier === null || identifier === undefined) {
          throw new Error("Can't save identity_key for invalid identifier");
        }

        const address = new libsignal.SignalProtocolAddress.fromString(identifier);
        const existing = this.get('identity_key' + address.getName());
        const b64_idkey = converse_omemo_u.arrayBufferToBase64(identity_key);
        this.save('identity_key' + address.getName(), b64_idkey);

        if (existing && b64_idkey !== existing) {
          return Promise.resolve(true);
        } else {
          return Promise.resolve(false);
        }
      },

      getPreKeys() {
        return this.get('prekeys') || {};
      },

      loadPreKey(key_id) {
        const res = this.getPreKeys()[key_id];

        if (res) {
          return Promise.resolve({
            'privKey': converse_omemo_u.base64ToArrayBuffer(res.privKey),
            'pubKey': converse_omemo_u.base64ToArrayBuffer(res.pubKey)
          });
        }

        return Promise.resolve();
      },

      storePreKey(key_id, key_pair) {
        const prekey = {};
        prekey[key_id] = {
          'pubKey': converse_omemo_u.arrayBufferToBase64(key_pair.pubKey),
          'privKey': converse_omemo_u.arrayBufferToBase64(key_pair.privKey)
        };
        this.save('prekeys', Object.assign(this.getPreKeys(), prekey));
        return Promise.resolve();
      },

      removePreKey(key_id) {
        this.save('prekeys', lodash_es_omit(this.getPreKeys(), key_id));
        return Promise.resolve();
      },

      loadSignedPreKey(keyId) {
        // eslint-disable-line no-unused-vars
        const res = this.get('signed_prekey');

        if (res) {
          return Promise.resolve({
            'privKey': converse_omemo_u.base64ToArrayBuffer(res.privKey),
            'pubKey': converse_omemo_u.base64ToArrayBuffer(res.pubKey)
          });
        }

        return Promise.resolve();
      },

      storeSignedPreKey(spk) {
        if (typeof spk !== "object") {
          // XXX: We've changed the signature of this method from the
          // example given in InMemorySignalProtocolStore.
          // Should be fine because the libsignal code doesn't
          // actually call this method.
          throw new Error("storeSignedPreKey: expected an object");
        }

        this.save('signed_prekey', {
          'id': spk.keyId,
          'privKey': converse_omemo_u.arrayBufferToBase64(spk.keyPair.privKey),
          'pubKey': converse_omemo_u.arrayBufferToBase64(spk.keyPair.pubKey),
          // XXX: The InMemorySignalProtocolStore does not pass
          // in or store the signature, but we need it when we
          // publish out bundle and this method isn't called from
          // within libsignal code, so we modify it to also store
          // the signature.
          'signature': converse_omemo_u.arrayBufferToBase64(spk.signature)
        });
        return Promise.resolve();
      },

      removeSignedPreKey(key_id) {
        if (this.get('signed_prekey')['id'] === key_id) {
          this.unset('signed_prekey');
          this.save();
        }

        return Promise.resolve();
      },

      loadSession(identifier) {
        return Promise.resolve(this.get('session' + identifier));
      },

      storeSession(identifier, record) {
        return Promise.resolve(this.save('session' + identifier, record));
      },

      removeSession(identifier) {
        return Promise.resolve(this.unset('session' + identifier));
      },

      removeAllSessions(identifier) {
        const keys = Object.keys(this.attributes).filter(key => key.startsWith('session' + identifier) ? key : false);
        const attrs = {};
        keys.forEach(key => {
          attrs[key] = undefined;
        });
        this.save(attrs);
        return Promise.resolve();
      },

      publishBundle() {
        const signed_prekey = this.get('signed_prekey');
        const node = `${converse_omemo_Strophe.NS.OMEMO_BUNDLES}:${this.get('device_id')}`;
        const item = converse_omemo_$build('item').c('bundle', {
          'xmlns': converse_omemo_Strophe.NS.OMEMO
        }).c('signedPreKeyPublic', {
          'signedPreKeyId': signed_prekey.id
        }).t(signed_prekey.pubKey).up().c('signedPreKeySignature').t(signed_prekey.signature).up().c('identityKey').t(this.get('identity_keypair').pubKey).up().c('prekeys');
        Object.values(this.get('prekeys')).forEach((prekey, id) => item.c('preKeyPublic', {
          'preKeyId': id
        }).t(prekey.pubKey).up());
        const options = {
          'pubsub#access_model': 'open'
        };
        return converse_core_api.pubsub.publish(null, node, item, options, false);
      },

      async generateMissingPreKeys() {
        const missing_keys = lodash_es_difference(lodash_es_invokeMap(lodash_es_range(0, converse_core_converse.NUM_PREKEYS), Number.prototype.toString), Object.keys(this.getPreKeys()));

        if (missing_keys.length < 1) {
          headless_log.warn("No missing prekeys to generate for our own device");
          return Promise.resolve();
        }

        const keys = await Promise.all(missing_keys.map(id => libsignal.KeyHelper.generatePreKey(parseInt(id, 10))));
        keys.forEach(k => this.storePreKey(k.keyId, k.keyPair));
        const marshalled_keys = Object.keys(this.getPreKeys()).map(k => ({
          'id': k.keyId,
          'key': converse_omemo_u.arrayBufferToBase64(k.pubKey)
        }));

        const devicelist = converse_core_converse.devicelists.get(converse_core_converse.bare_jid);

        const device = devicelist.devices.get(this.get('device_id'));
        const bundle = await device.getBundle();
        device.save('bundle', Object.assign(bundle, {
          'prekeys': marshalled_keys
        }));
      },

      /**
       * Generate a the data used by the X3DH key agreement protocol
       * that can be used to build a session with a device.
       */
      async generateBundle() {
        // The first thing that needs to happen if a client wants to
        // start using OMEMO is they need to generate an IdentityKey
        // and a Device ID. The IdentityKey is a Curve25519 [6]
        // public/private Key pair. The Device ID is a randomly
        // generated integer between 1 and 2^31 - 1.
        const identity_keypair = await libsignal.KeyHelper.generateIdentityKeyPair();
        const bundle = {};
        const identity_key = converse_omemo_u.arrayBufferToBase64(identity_keypair.pubKey);
        const device_id = generateDeviceID();
        bundle['identity_key'] = identity_key;
        bundle['device_id'] = device_id;
        this.save({
          'device_id': device_id,
          'identity_keypair': {
            'privKey': converse_omemo_u.arrayBufferToBase64(identity_keypair.privKey),
            'pubKey': identity_key
          },
          'identity_key': identity_key
        });
        const signed_prekey = await libsignal.KeyHelper.generateSignedPreKey(identity_keypair, 0);

        converse_core_converse.omemo_store.storeSignedPreKey(signed_prekey);

        bundle['signed_prekey'] = {
          'id': signed_prekey.keyId,
          'public_key': converse_omemo_u.arrayBufferToBase64(signed_prekey.keyPair.pubKey),
          'signature': converse_omemo_u.arrayBufferToBase64(signed_prekey.signature)
        };
        const keys = await Promise.all(lodash_es_range(0, converse_core_converse.NUM_PREKEYS).map(id => libsignal.KeyHelper.generatePreKey(id)));
        keys.forEach(k => converse_core_converse.omemo_store.storePreKey(k.keyId, k.keyPair));

        const devicelist = converse_core_converse.devicelists.get(converse_core_converse.bare_jid);

        const device = await devicelist.devices.create({
          'id': bundle.device_id,
          'jid': converse_core_converse.bare_jid
        }, {
          'promise': true
        });
        const marshalled_keys = keys.map(k => ({
          'id': k.keyId,
          'key': converse_omemo_u.arrayBufferToBase64(k.keyPair.pubKey)
        }));
        bundle['prekeys'] = marshalled_keys;
        device.save('bundle', bundle);
      },

      fetchSession() {
        if (this._setup_promise === undefined) {
          this._setup_promise = new Promise((resolve, reject) => {
            this.fetch({
              'success': () => {
                if (!converse_core_converse.omemo_store.get('device_id')) {
                  this.generateBundle().then(resolve).catch(reject);
                } else {
                  resolve();
                }
              },
              'error': (model, resp) => {
                headless_log.warn("Could not fetch OMEMO session from cache, we'll generate a new one.");
                headless_log.warn(resp);
                this.generateBundle().then(resolve).catch(reject);
              }
            });
          });
        }

        return this._setup_promise;
      }

    });
    /**
     * @class
     * @namespace _converse.Device
     * @memberOf _converse
     */

    converse_core_converse.Device = model_Model.extend({
      defaults: {
        'trusted': UNDECIDED,
        'active': true
      },

      getRandomPreKey() {
        // XXX: assumes that the bundle has already been fetched
        const bundle = this.get('bundle');
        return bundle.prekeys[converse_omemo_u.getRandomInt(bundle.prekeys.length)];
      },

      async fetchBundleFromServer() {
        const stanza = converse_omemo_$iq({
          'type': 'get',
          'from': converse_core_converse.bare_jid,
          'to': this.get('jid')
        }).c('pubsub', {
          'xmlns': converse_omemo_Strophe.NS.PUBSUB
        }).c('items', {
          'node': `${converse_omemo_Strophe.NS.OMEMO_BUNDLES}:${this.get('id')}`
        });
        let iq;

        try {
          iq = await converse_core_api.sendIQ(stanza);
        } catch (iq) {
          headless_log.error(`Could not fetch bundle for device ${this.get('id')} from ${this.get('jid')}`);
          headless_log.error(iq);
          return null;
        }

        if (iq.querySelector('error')) {
          throw new IQError("Could not fetch bundle", iq);
        }

        const publish_el = converse_omemo_sizzle(`items[node="${converse_omemo_Strophe.NS.OMEMO_BUNDLES}:${this.get('id')}"]`, iq).pop();
        const bundle_el = converse_omemo_sizzle(`bundle[xmlns="${converse_omemo_Strophe.NS.OMEMO}"]`, publish_el).pop();
        const bundle = parseBundle(bundle_el);
        this.save('bundle', bundle);
        return bundle;
      },

      /**
       * Fetch and save the bundle information associated with
       * this device, if the information is not cached already.
       * @method _converse.Device#getBundle
       */
      getBundle() {
        if (this.get('bundle')) {
          return Promise.resolve(this.get('bundle'), this);
        } else {
          return this.fetchBundleFromServer();
        }
      }

    });
    converse_core_converse.Devices = Collection.extend({
      model: converse_core_converse.Device
    });
    /**
     * @class
     * @namespace _converse.DeviceList
     * @memberOf _converse
     */

    converse_core_converse.DeviceList = model_Model.extend({
      idAttribute: 'jid',

      initialize() {
        this.devices = new converse_core_converse.Devices();
        const id = `converse.devicelist-${converse_core_converse.bare_jid}-${this.get('jid')}`;
        this.devices.browserStorage = converse_core_converse.createStore(id);
        this.fetchDevices();
      },

      async onDevicesFound(collection) {
        if (collection.length === 0) {
          let ids;

          try {
            ids = await this.fetchDevicesFromServer();
          } catch (e) {
            if (e === null) {
              headless_log.error(`Timeout error while fetching devices for ${this.get('jid')}`);
            } else {
              headless_log.error(`Could not fetch devices for ${this.get('jid')}`);
              headless_log.error(e);
            }

            this.destroy();
          }

          if (this.get('jid') === converse_core_converse.bare_jid) {
            await this.publishCurrentDevice(ids);
          }
        }
      },

      fetchDevices() {
        if (this._devices_promise === undefined) {
          this._devices_promise = new Promise(resolve => {
            this.devices.fetch({
              'success': c => resolve(this.onDevicesFound(c)),
              'error': (m, e) => {
                headless_log.error(e);
                resolve();
              }
            });
          });
        }

        return this._devices_promise;
      },

      async getOwnDeviceId() {
        let device_id = converse_core_converse.omemo_store.get('device_id');

        if (!this.devices.findWhere({
          'id': device_id
        })) {
          // Generate a new bundle if we cannot find our device
          await converse_core_converse.omemo_store.generateBundle();
          device_id = converse_core_converse.omemo_store.get('device_id');
        }

        return device_id;
      },

      async publishCurrentDevice(device_ids) {
        if (this.get('jid') !== converse_core_converse.bare_jid) {
          return; // We only publish for ourselves.
        }

        await restoreOMEMOSession();

        if (!converse_core_converse.omemo_store) {
          // Happens during tests. The connection gets torn down
          // before publishCurrentDevice has time to finish.
          headless_log.warn('publishCurrentDevice: omemo_store is not defined, likely a timing issue');
          return;
        }

        if (!device_ids.includes(await this.getOwnDeviceId())) {
          return this.publishDevices();
        }
      },

      async fetchDevicesFromServer() {
        const stanza = converse_omemo_$iq({
          'type': 'get',
          'from': converse_core_converse.bare_jid,
          'to': this.get('jid')
        }).c('pubsub', {
          'xmlns': converse_omemo_Strophe.NS.PUBSUB
        }).c('items', {
          'node': converse_omemo_Strophe.NS.OMEMO_DEVICELIST
        });
        let iq;

        try {
          iq = await converse_core_api.sendIQ(stanza);
        } catch (e) {
          headless_log.error(e);
          return [];
        }

        const selector = `list[xmlns="${converse_omemo_Strophe.NS.OMEMO}"] device`;
        const device_ids = converse_omemo_sizzle(selector, iq).map(d => d.getAttribute('id'));
        await Promise.all(device_ids.map(id => this.devices.create({
          id,
          'jid': this.get('jid')
        }, {
          'promise': true
        })));
        return device_ids;
      },

      /**
       * Send an IQ stanza to the current user's "devices" PEP node to
       * ensure that all devices are published for potential chat partners to see.
       * See: https://xmpp.org/extensions/xep-0384.html#usecases-announcing
       */
      publishDevices() {
        const item = converse_omemo_$build('item', {
          'id': 'current'
        }).c('list', {
          'xmlns': converse_omemo_Strophe.NS.OMEMO
        });
        this.devices.filter(d => d.get('active')).forEach(d => item.c('device', {
          'id': d.get('id')
        }).up());
        const options = {
          'pubsub#access_model': 'open'
        };
        return converse_core_api.pubsub.publish(null, converse_omemo_Strophe.NS.OMEMO_DEVICELIST, item, options, false);
      },

      removeOwnDevices(device_ids) {
        if (this.get('jid') !== converse_core_converse.bare_jid) {
          throw new Error("Cannot remove devices from someone else's device list");
        }

        device_ids.forEach(device_id => this.devices.get(device_id).destroy());
        return this.publishDevices();
      }

    });
    /**
     * @class
     * @namespace _converse.DeviceLists
     * @memberOf _converse
     */

    converse_core_converse.DeviceLists = Collection.extend({
      model: converse_core_converse.DeviceList,

      /**
       * Returns the {@link _converse.DeviceList} for a particular JID.
       * The device list will be created if it doesn't exist already.
       * @private
       * @method _converse.DeviceLists#getDeviceList
       * @param { String } jid - The Jabber ID for which the device list will be returned.
       */
      getDeviceList(jid) {
        return this.get(jid) || this.create({
          'jid': jid
        });
      }

    });
    /******************** Event Handlers ********************/

    converse_core_api.waitUntil('chatBoxesInitialized').then(onChatBoxesInitialized);
    converse_core_api.listen.on('parseMessage', parseEncryptedMessage);
    converse_core_api.listen.on('parseMUCMessage', parseEncryptedMessage);
    converse_core_api.listen.on('chatBoxViewInitialized', onChatInitialized);
    converse_core_api.listen.on('chatRoomViewInitialized', onChatInitialized);
    converse_core_api.listen.on('connected', registerPEPPushHandler);
    converse_core_api.listen.on('getToolbarButtons', getOMEMOToolbarButton);
    converse_core_api.listen.on('statusInitialized', initOMEMO);
    converse_core_api.listen.on('addClientFeatures', () => converse_core_api.disco.own.features.add(`${converse_omemo_Strophe.NS.OMEMO_DEVICELIST}+notify`));
    converse_core_api.listen.on('userDetailsModalInitialized', contact => {
      const jid = contact.get('jid');

      converse_core_converse.generateFingerprints(jid).catch(e => headless_log.error(e));
    });
    converse_core_api.listen.on('profileModalInitialized', () => {
      converse_core_converse.generateFingerprints(converse_core_converse.bare_jid).catch(e => headless_log.error(e));
    });
    converse_core_api.listen.on('afterTearDown', () => delete converse_core_converse.omemo_store);
    converse_core_api.listen.on('clearSession', () => {
      if (converse_core_converse.shouldClearCache() && converse_core_converse.devicelists) {
        converse_core_converse.devicelists.clearStore();

        delete converse_core_converse.devicelists;
      }
    });
    /************************ API ************************/

    Object.assign(converse_core_converse.api, {
      /**
       * The "omemo" namespace groups methods relevant to OMEMO
       * encryption.
       *
       * @namespace _converse.api.omemo
       * @memberOf _converse.api
       */
      'omemo': {
        /**
         * The "bundle" namespace groups methods relevant to the user's
         * OMEMO bundle.
         *
         * @namespace _converse.api.omemo.bundle
         * @memberOf _converse.api.omemo
         */
        'bundle': {
          /**
           * Lets you generate a new OMEMO device bundle
           *
           * @method _converse.api.omemo.bundle.generate
           * @returns {promise} Promise which resolves once we have a result from the server.
           */
          'generate': async () => {
            // Remove current device
            const devicelist = converse_core_converse.devicelists.get(converse_core_converse.bare_jid);

            const device_id = converse_core_converse.omemo_store.get('device_id');

            if (device_id) {
              const device = devicelist.devices.get(device_id);

              converse_core_converse.omemo_store.unset(device_id);

              if (device) {
                await new Promise(done => device.destroy({
                  'success': done,
                  'error': done
                }));
              }

              devicelist.devices.trigger('remove');
            } // Generate new device bundle and publish
            // https://xmpp.org/extensions/attic/xep-0384-0.3.0.html#usecases-announcing


            await converse_core_converse.omemo_store.generateBundle();
            await devicelist.publishDevices();
            const device = devicelist.devices.get(converse_core_converse.omemo_store.get('device_id'));
            const fp = generateFingerprint(device);
            await converse_core_converse.omemo_store.publishBundle();
            return fp;
          }
        }
      }
    });
  }

});
// CONCATENATED MODULE: ./src/converse-push.js
/**
 * @module converse-push
 * @description
 * Converse.js plugin which add support for registering
 * an "App Server" as defined in  XEP-0357
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */


const {
  Strophe: converse_push_Strophe,
  $iq: converse_push_$iq
} = converse.env;
converse_push_Strophe.addNamespace('PUSH', 'urn:xmpp:push:0');
converse.plugins.add('converse-push', {
  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    converse_core_api.settings.extend({
      'push_app_servers': [],
      'enable_muc_push': false
    });

    async function disablePushAppServer(domain, push_app_server) {
      if (!push_app_server.jid) {
        return;
      }

      if (!(await converse_core_api.disco.supports(converse_push_Strophe.NS.PUSH, domain || converse_core_converse.bare_jid))) {
        headless_log.warn(`Not disabling push app server "${push_app_server.jid}", no disco support from your server.`);
        return;
      }

      const stanza = converse_push_$iq({
        'type': 'set'
      });

      if (domain !== converse_core_converse.bare_jid) {
        stanza.attrs({
          'to': domain
        });
      }

      stanza.c('disable', {
        'xmlns': converse_push_Strophe.NS.PUSH,
        'jid': push_app_server.jid
      });

      if (push_app_server.node) {
        stanza.attrs({
          'node': push_app_server.node
        });
      }

      converse_core_api.sendIQ(stanza).catch(e => {
        headless_log.error(`Could not disable push app server for ${push_app_server.jid}`);
        headless_log.error(e);
      });
    }

    async function enablePushAppServer(domain, push_app_server) {
      if (!push_app_server.jid || !push_app_server.node) {
        return;
      }

      const identity = await converse_core_api.disco.getIdentity('pubsub', 'push', push_app_server.jid);

      if (!identity) {
        return headless_log.warn(`Not enabling push the service "${push_app_server.jid}", it doesn't have the right disco identtiy.`);
      }

      const result = await Promise.all([converse_core_api.disco.supports(converse_push_Strophe.NS.PUSH, push_app_server.jid), converse_core_api.disco.supports(converse_push_Strophe.NS.PUSH, domain)]);

      if (!result[0] && !result[1]) {
        headless_log.warn(`Not enabling push app server "${push_app_server.jid}", no disco support from your server.`);
        return;
      }

      const stanza = converse_push_$iq({
        'type': 'set'
      });

      if (domain !== converse_core_converse.bare_jid) {
        stanza.attrs({
          'to': domain
        });
      }

      stanza.c('enable', {
        'xmlns': converse_push_Strophe.NS.PUSH,
        'jid': push_app_server.jid,
        'node': push_app_server.node
      });

      if (push_app_server.secret) {
        stanza.c('x', {
          'xmlns': converse_push_Strophe.NS.XFORM,
          'type': 'submit'
        }).c('field', {
          'var': 'FORM_TYPE'
        }).c('value').t(`${converse_push_Strophe.NS.PUBSUB}#publish-options`).up().up().c('field', {
          'var': 'secret'
        }).c('value').t(push_app_server.secret);
      }

      return converse_core_api.sendIQ(stanza);
    }

    async function enablePush(domain) {
      domain = domain || converse_core_converse.bare_jid;
      const push_enabled = converse_core_converse.session.get('push_enabled') || [];

      if (push_enabled.includes(domain)) {
        return;
      }

      const enabled_services = converse_core_api.settings.get('push_app_servers').filter(s => !s.disable);
      const disabled_services = converse_core_api.settings.get('push_app_servers').filter(s => s.disable);
      const enabled = enabled_services.map(s => enablePushAppServer(domain, s));
      const disabled = disabled_services.map(s => disablePushAppServer(domain, s));

      try {
        await Promise.all(enabled.concat(disabled));
      } catch (e) {
        headless_log.error('Could not enable or disable push App Server');
        if (e) headless_log.error(e);
      } finally {
        push_enabled.push(domain);
      }

      converse_core_converse.session.save('push_enabled', push_enabled);
    }

    converse_core_api.listen.on('statusInitialized', () => enablePush());

    function onChatBoxAdded(model) {
      if (model.get('type') == converse_core_converse.CHATROOMS_TYPE) {
        enablePush(converse_push_Strophe.getDomainFromJid(model.get('jid')));
      }
    }

    if (converse_core_api.settings.get('enable_muc_push')) {
      converse_core_api.listen.on('chatBoxesInitialized', () => converse_core_converse.chatboxes.on('add', onChatBoxAdded));
    }
  }

});
// EXTERNAL MODULE: ./src/templates/register_panel.html
var register_panel = __webpack_require__(176);
var register_panel_default = /*#__PURE__*/__webpack_require__.n(register_panel);

// EXTERNAL MODULE: ./src/templates/registration_form.html
var registration_form = __webpack_require__(177);
var registration_form_default = /*#__PURE__*/__webpack_require__.n(registration_form);

// EXTERNAL MODULE: ./src/templates/registration_request.html
var registration_request = __webpack_require__(178);
var registration_request_default = /*#__PURE__*/__webpack_require__.n(registration_request);

// CONCATENATED MODULE: ./src/converse-register.js
/**
 * @module converse-register
 * @description
 * This is a Converse.js plugin which add support for in-band registration
 * as specified in XEP-0077.
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */













 // Strophe methods for building stanzas

const {
  Strophe: converse_register_Strophe,
  sizzle: converse_register_sizzle,
  $iq: converse_register_$iq
} = converse.env;
const converse_register_u = converse.env.utils; // Add Strophe Namespaces

converse_register_Strophe.addNamespace('REGISTER', 'jabber:iq:register'); // Add Strophe Statuses

const converse_register_i = Object.keys(converse_register_Strophe.Status).reduce((max, k) => Math.max(max, converse_register_Strophe.Status[k]), 0);
converse_register_Strophe.Status.REGIFAIL = converse_register_i + 1;
converse_register_Strophe.Status.REGISTERED = converse_register_i + 2;
converse_register_Strophe.Status.CONFLICT = converse_register_i + 3;
converse_register_Strophe.Status.NOTACCEPTABLE = converse_register_i + 5;
converse.plugins.add('converse-register', {
  enabled() {
    return true;
  },

  overrides: {
    // Overrides mentioned here will be picked up by converse.js's
    // plugin architecture they will replace existing methods on the
    // relevant objects or classes.
    //
    // New functions which don't exist yet can also be added.
    ControlBoxView: {
      renderLoginPanel() {
        /* Also render a registration panel, when rendering the
         * login panel.
         */
        this.__super__.renderLoginPanel.apply(this, arguments);

        this.renderRegistrationPanel();
        return this;
      }

    }
  },

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    converse_core_converse.CONNECTION_STATUS[converse_register_Strophe.Status.REGIFAIL] = 'REGIFAIL';
    converse_core_converse.CONNECTION_STATUS[converse_register_Strophe.Status.REGISTERED] = 'REGISTERED';
    converse_core_converse.CONNECTION_STATUS[converse_register_Strophe.Status.CONFLICT] = 'CONFLICT';
    converse_core_converse.CONNECTION_STATUS[converse_register_Strophe.Status.NOTACCEPTABLE] = 'NOTACCEPTABLE';
    converse_core_api.settings.extend({
      'allow_registration': true,
      'domain_placeholder': i18n_(" e.g. conversejs.org"),
      // Placeholder text shown in the domain input on the registration form
      'providers_link': 'https://compliance.conversations.im/',
      // Link to XMPP providers shown on registration page
      'registration_domain': ''
    });
    Object.assign(converse_core_converse.ControlBoxView.prototype, {
      showLoginOrRegisterForm() {
        if (!this.registerpanel) {
          return;
        }

        if (this.model.get('active-form') == "register") {
          this.loginpanel.el.classList.add('hidden');
          this.registerpanel.el.classList.remove('hidden');
        } else {
          this.loginpanel.el.classList.remove('hidden');
          this.registerpanel.el.classList.add('hidden');
        }
      },

      renderRegistrationPanel() {
        if (converse_core_api.settings.get('allow_registration')) {
          this.registerpanel = new converse_core_converse.RegisterPanel({
            'model': this.model
          });
          this.registerpanel.render();
          this.registerpanel.el.classList.add('hidden');
          const login_panel = this.el.querySelector('#converse-login-panel');

          if (login_panel) {
            login_panel.insertAdjacentElement('afterend', this.registerpanel.el);
          }

          this.showLoginOrRegisterForm();
        }

        return this;
      }

    });

    function setActiveForm(value) {
      converse_core_api.waitUntil('controlBoxInitialized').then(() => {
        const controlbox = converse_core_converse.chatboxes.get('controlbox');

        controlbox.set({
          'active-form': value
        });
      }).catch(e => headless_log.fatal(e));
    }

    converse_core_converse.router.route('converse/login', () => setActiveForm('login'));

    converse_core_converse.router.route('converse/register', () => setActiveForm('register'));
    /**
     * @class
     * @namespace _converse.RegisterPanel
     * @memberOf _converse
     */


    converse_core_converse.RegisterPanel = View.extend({
      tagName: 'div',
      id: "converse-register-panel",
      className: 'controlbox-pane fade-in',
      events: {
        'submit form#converse-register': 'onFormSubmission',
        'click .button-cancel': 'renderProviderChoiceForm'
      },

      initialize() {
        this.reset();
        converse_core_api.listen.on('connectionInitialized', () => this.registerHooks());
      },

      render() {
        this.model.set('registration_form_rendered', false);
        this.el.innerHTML = register_panel_default()({
          '__': i18n_,
          'default_domain': converse_core_api.settings.get('registration_domain'),
          'label_register': i18n_('Fetch registration form'),
          'help_providers': i18n_('Tip: A list of public XMPP providers is available'),
          'help_providers_link': i18n_('here'),
          'href_providers': converse_core_api.settings.get('providers_link'),
          'domain_placeholder': converse_core_api.settings.get('domain_placeholder')
        });

        if (converse_core_api.settings.get('registration_domain')) {
          this.fetchRegistrationForm(converse_core_api.settings.get('registration_domain'));
        }

        return this;
      },

      registerHooks() {
        /* Hook into Strophe's _connect_cb, so that we can send an IQ
         * requesting the registration fields.
         */
        const conn = converse_core_converse.connection;

        const connect_cb = conn._connect_cb.bind(conn);

        conn._connect_cb = (req, callback, raw) => {
          if (!this._registering) {
            connect_cb(req, callback, raw);
          } else {
            if (this.getRegistrationFields(req, callback)) {
              this._registering = false;
            }
          }
        };
      },

      /**
       * Send an IQ stanza to the XMPP server asking for the registration fields.
       * @private
       * @method _converse.RegisterPanel#getRegistrationFields
       * @param { Strophe.Request } req - The current request
       * @param { Function } callback - The callback function
       */
      getRegistrationFields(req, _callback) {
        const conn = converse_core_converse.connection;
        conn.connected = true;

        const body = conn._proto._reqToData(req);

        if (!body) {
          return;
        }

        if (conn._proto._connect_cb(body) === converse_register_Strophe.Status.CONNFAIL) {
          this.showValidationError(i18n_("Sorry, we're unable to connect to your chosen provider."));
          return false;
        }

        const register = body.getElementsByTagName("register");
        const mechanisms = body.getElementsByTagName("mechanism");

        if (register.length === 0 && mechanisms.length === 0) {
          conn._proto._no_auth_received(_callback);

          return false;
        }

        if (register.length === 0) {
          conn._changeConnectStatus(converse_register_Strophe.Status.REGIFAIL);

          this.showValidationError(i18n_("Sorry, the given provider does not support in " + "band account registration. Please try with a " + "different provider."));
          return true;
        } // Send an IQ stanza to get all required data fields


        conn._addSysHandler(this.onRegistrationFields.bind(this), null, "iq", null, null);

        const stanza = converse_register_$iq({
          type: "get"
        }).c("query", {
          xmlns: converse_register_Strophe.NS.REGISTER
        }).tree();
        stanza.setAttribute("id", conn.getUniqueId("sendIQ"));
        conn.send(stanza);
        conn.connected = false;
        return true;
      },

      /**
       * Handler for {@link _converse.RegisterPanel#getRegistrationFields}
       * @private
       * @method _converse.RegisterPanel#onRegistrationFields
       * @param { XMLElement } stanza - The query stanza.
       */
      onRegistrationFields(stanza) {
        if (stanza.getAttribute("type") === "error") {
          converse_core_converse.connection._changeConnectStatus(converse_register_Strophe.Status.REGIFAIL, i18n_('Something went wrong while establishing a connection with "%1$s". ' + 'Are you sure it exists?', this.domain));

          return false;
        }

        if (stanza.getElementsByTagName("query").length !== 1) {
          converse_core_converse.connection._changeConnectStatus(converse_register_Strophe.Status.REGIFAIL, "unknown");

          return false;
        }

        this.setFields(stanza);

        if (!this.model.get('registration_form_rendered')) {
          this.renderRegistrationForm(stanza);
        }

        return false;
      },

      reset(settings) {
        const defaults = {
          fields: {},
          urls: [],
          title: "",
          instructions: "",
          registered: false,
          _registering: false,
          domain: null,
          form_type: null
        };
        Object.assign(this, defaults);

        if (settings) {
          Object.assign(this, lodash_es_pick(settings, Object.keys(defaults)));
        }
      },

      onFormSubmission(ev) {
        /* Event handler when the #converse-register form is
         * submitted.
         *
         * Depending on the available input fields, we delegate to
         * other methods.
         */
        if (ev && ev.preventDefault) {
          ev.preventDefault();
        }

        if (ev.target.querySelector('input[name=domain]') === null) {
          this.submitRegistrationForm(ev.target);
        } else {
          this.onProviderChosen(ev.target);
        }
      },

      /**
       * Callback method that gets called when the user has chosen an XMPP provider
       * @private
       * @method _converse.RegisterPanel#onProviderChosen
       * @param { HTMLElement } form - The form that was submitted
       */
      onProviderChosen(form) {
        const domain_input = form.querySelector('input[name=domain]'),
              domain = domain_input === null || domain_input === void 0 ? void 0 : domain_input.value;

        if (!domain) {
          // TODO: add validation message
          domain_input.classList.add('error');
          return;
        }

        form.querySelector('input[type=submit]').classList.add('hidden');
        this.fetchRegistrationForm(domain.trim());
      },

      /**
       * Fetch a registration form from the requested domain
       * @private
       * @method _converse.RegisterPanel#fetchRegistrationForm
       * @param { String } domain_name - XMPP server domain
       */
      async fetchRegistrationForm(domain_name) {
        var _converse$connection;

        if (!this.model.get('registration_form_rendered')) {
          this.renderRegistrationRequest();
        }

        this.reset({
          'domain': converse_register_Strophe.getDomainFromJid(domain_name),
          '_registering': true
        });
        await converse_core_converse.initConnection(this.domain); // When testing, the test tears down before the async function
        // above finishes. So we use optional chaining here

        (_converse$connection = converse_core_converse.connection) === null || _converse$connection === void 0 ? void 0 : _converse$connection.connect(this.domain, "", status => this.onConnectStatusChanged(status));
        return false;
      },

      renderRegistrationRequest() {
        /* Clear the form and inform the user that the registration
         * form is being fetched.
         */
        this.clearRegistrationForm().insertAdjacentHTML('beforeend', registration_request_default()({
          '__': converse_core_converse.__,
          'cancel': converse_core_api.settings.get('registration_domain')
        }));
      },

      giveFeedback(message, klass) {
        let feedback = this.el.querySelector('.reg-feedback');

        if (feedback !== null) {
          feedback.parentNode.removeChild(feedback);
        }

        const form = this.el.querySelector('form');
        form.insertAdjacentHTML('afterbegin', '<span class="reg-feedback"></span>');
        feedback = form.querySelector('.reg-feedback');
        feedback.textContent = message;

        if (klass) {
          feedback.classList.add(klass);
        }
      },

      clearRegistrationForm() {
        const form = this.el.querySelector('form');
        form.innerHTML = '';
        this.model.set('registration_form_rendered', false);
        return form;
      },

      showSpinner() {
        const form = this.el.querySelector('form');
        render_render(spinner(), form);
        this.model.set('registration_form_rendered', false);
        return this;
      },

      /**
       * Callback function called by Strophe whenever the connection status changes.
       * Passed to Strophe specifically during a registration attempt.
       * @private
       * @method _converse.RegisterPanel#onConnectStatusChanged
       * @param { integer } status_code - The Strophe.Status status code
       */
      onConnectStatusChanged(status_code) {
        headless_log.debug('converse-register: onConnectStatusChanged');

        if ([converse_register_Strophe.Status.DISCONNECTED, converse_register_Strophe.Status.CONNFAIL, converse_register_Strophe.Status.REGIFAIL, converse_register_Strophe.Status.NOTACCEPTABLE, converse_register_Strophe.Status.CONFLICT].includes(status_code)) {
          headless_log.error(`Problem during registration: Strophe.Status is ${converse_core_converse.CONNECTION_STATUS[status_code]}`);
          this.abortRegistration();
        } else if (status_code === converse_register_Strophe.Status.REGISTERED) {
          headless_log.debug("Registered successfully.");

          converse_core_converse.connection.reset();

          this.showSpinner();

          if (["converse/login", "converse/register"].includes(converse_core_converse.router.history.getFragment())) {
            converse_core_converse.router.navigate('', {
              'replace': true
            });
          }

          if (this.fields.password && this.fields.username) {
            // automatically log the user in
            converse_core_converse.connection.connect(this.fields.username.toLowerCase() + '@' + this.domain.toLowerCase(), this.fields.password, converse_core_converse.onConnectStatusChanged);

            this.giveFeedback(i18n_('Now logging you in'), 'info');
          } else {
            converse_core_converse.chatboxviews.get('controlbox').renderLoginPanel();

            converse_core_converse.giveFeedback(i18n_('Registered successfully'));
          }

          this.reset();
        }
      },

      renderLegacyRegistrationForm(form) {
        Object.keys(this.fields).forEach(key => {
          if (key === "username") {
            form.insertAdjacentHTML('beforeend', form_username_default()({
              'domain': ` @${this.domain}`,
              'name': key,
              'type': "text",
              'label': key,
              'value': '',
              'required': true
            }));
          } else {
            form.insertAdjacentHTML('beforeend', form_input_default()({
              'label': key,
              'name': key,
              'placeholder': key,
              'required': true,
              'type': key === 'password' || key === 'email' ? key : "text",
              'value': ''
            }));
          }
        }); // Show urls

        this.urls.forEach(u => form.insertAdjacentHTML('afterend', '<a target="blank" rel="noopener" href="' + u + '">' + u + '</a>'));
      },

      /**
       * Renders the registration form based on the XForm fields
       * received from the XMPP server.
       * @private
       * @method _converse.RegisterPanel#renderRegistrationForm
       * @param { XMLElement } stanza - The IQ stanza received from the XMPP server.
       */
      renderRegistrationForm(stanza) {
        const form = this.el.querySelector('form');
        form.innerHTML = registration_form_default()({
          '__': i18n_,
          'domain': this.domain,
          'title': this.title,
          'instructions': this.instructions,
          'registration_domain': converse_core_api.settings.get('registration_domain')
        });
        const buttons = form.querySelector('fieldset.buttons');

        if (this.form_type === 'xform') {
          stanza.querySelectorAll('field').forEach(field => {
            buttons.insertAdjacentHTML('beforebegin', utils_form.xForm2webForm(field, stanza, {
              'domain': this.domain
            }));
          });
        } else {
          this.renderLegacyRegistrationForm(form);
        }

        if (!this.fields) {
          form.querySelector('.button-primary').classList.add('hidden');
        }

        form.classList.remove('hidden');
        this.model.set('registration_form_rendered', true);
      },

      showValidationError(message) {
        const form = this.el.querySelector('form');
        let flash = form.querySelector('.form-errors');

        if (flash === null) {
          flash = '<div class="form-errors hidden"></div>';
          const instructions = form.querySelector('p.instructions');

          if (instructions === null) {
            form.insertAdjacentHTML('afterbegin', flash);
          } else {
            instructions.insertAdjacentHTML('afterend', flash);
          }

          flash = form.querySelector('.form-errors');
        } else {
          flash.innerHTML = '';
        }

        flash.insertAdjacentHTML('beforeend', '<p class="form-help error">' + message + '</p>');
        flash.classList.remove('hidden');
      },

      /**
       * Report back to the user any error messages received from the
       * XMPP server after attempted registration.
       * @private
       * @method _converse.RegisterPanel#reportErrors
       * @param { XMLElement } stanza - The IQ stanza received from the XMPP server
       */
      reportErrors(stanza) {
        const errors = stanza.querySelectorAll('error');
        errors.forEach(e => this.showValidationError(e.textContent));

        if (!errors.length) {
          const message = i18n_('The provider rejected your registration attempt. ' + 'Please check the values you entered for correctness.');

          this.showValidationError(message);
        }
      },

      renderProviderChoiceForm(ev) {
        if (ev && ev.preventDefault) {
          ev.preventDefault();
        }

        converse_core_converse.connection._proto._abortAllRequests();

        converse_core_converse.connection.reset();

        this.render();
      },

      abortRegistration() {
        converse_core_converse.connection._proto._abortAllRequests();

        converse_core_converse.connection.reset();

        if (this.model.get('registration_form_rendered')) {
          if (converse_core_api.settings.get('registration_domain') && this.model.get('registration_form_rendered')) {
            this.fetchRegistrationForm(converse_core_api.settings.get('registration_domain'));
          }
        } else {
          this.render();
        }
      },

      /**
       * Handler, when the user submits the registration form.
       * Provides form error feedback or starts the registration process.
       * @private
       * @method _converse.RegisterPanel#submitRegistrationForm
       * @param { HTMLElement } form - The HTML form that was submitted
       */
      submitRegistrationForm(form) {
        const has_empty_inputs = Array.from(this.el.querySelectorAll('input.required')).reduce((result, input) => {
          if (input.value === '') {
            input.classList.add('error');
            return result + 1;
          }

          return result;
        }, 0);

        if (has_empty_inputs) {
          return;
        }

        const inputs = converse_register_sizzle(':input:not([type=button]):not([type=submit])', form);
        const iq = converse_register_$iq({
          'type': 'set',
          'id': converse_register_u.getUniqueId()
        }).c("query", {
          xmlns: converse_register_Strophe.NS.REGISTER
        });

        if (this.form_type === 'xform') {
          iq.c("x", {
            xmlns: converse_register_Strophe.NS.XFORM,
            type: 'submit'
          });
          const xml_nodes = inputs.map(i => utils_form.webForm2xForm(i)).filter(n => n);
          xml_nodes.forEach(n => iq.cnode(n).up());
        } else {
          inputs.forEach(input => iq.c(input.getAttribute('name'), {}, input.value));
        }

        converse_core_converse.connection._addSysHandler(this._onRegisterIQ.bind(this), null, "iq", null, null);

        converse_core_converse.connection.send(iq);

        this.setFields(iq.tree());
      },

      /* Stores the values that will be sent to the XMPP server during attempted registration.
       * @private
       * @method _converse.RegisterPanel#setFields
       * @param { XMLElement } stanza - the IQ stanza that will be sent to the XMPP server.
       */
      setFields(stanza) {
        const query = stanza.querySelector('query');
        const xform = converse_register_sizzle(`x[xmlns="${converse_register_Strophe.NS.XFORM}"]`, query);

        if (xform.length > 0) {
          this._setFieldsFromXForm(xform.pop());
        } else {
          this._setFieldsFromLegacy(query);
        }
      },

      _setFieldsFromLegacy(query) {
        [].forEach.call(query.children, field => {
          if (field.tagName.toLowerCase() === 'instructions') {
            this.instructions = converse_register_Strophe.getText(field);
            return;
          } else if (field.tagName.toLowerCase() === 'x') {
            if (field.getAttribute('xmlns') === 'jabber:x:oob') {
              this.urls.concat(converse_register_sizzle('url', field).map(u => u.textContent));
            }

            return;
          }

          this.fields[field.tagName.toLowerCase()] = converse_register_Strophe.getText(field);
        });
        this.form_type = 'legacy';
      },

      _setFieldsFromXForm(xform) {
        var _xform$querySelector, _xform$querySelector2;

        this.title = (_xform$querySelector = xform.querySelector('title')) === null || _xform$querySelector === void 0 ? void 0 : _xform$querySelector.textContent;
        this.instructions = (_xform$querySelector2 = xform.querySelector('instructions')) === null || _xform$querySelector2 === void 0 ? void 0 : _xform$querySelector2.textContent;
        xform.querySelectorAll('field').forEach(field => {
          const _var = field.getAttribute('var');

          if (_var) {
            var _field$querySelector$, _field$querySelector;

            this.fields[_var.toLowerCase()] = (_field$querySelector$ = (_field$querySelector = field.querySelector('value')) === null || _field$querySelector === void 0 ? void 0 : _field$querySelector.textContent) !== null && _field$querySelector$ !== void 0 ? _field$querySelector$ : '';
          } else {
            // TODO: other option seems to be type="fixed"
            headless_log.warn("Found field we couldn't parse");
          }
        });
        this.form_type = 'xform';
      },

      /**
       * Callback method that gets called when a return IQ stanza
       * is received from the XMPP server, after attempting to
       * register a new user.
       * @private
       * @method _converse.RegisterPanel#reportErrors
       * @param { XMLElement } stanza - The IQ stanza.
       */
      _onRegisterIQ(stanza) {
        if (stanza.getAttribute("type") === "error") {
          headless_log.error("Registration failed.");
          this.reportErrors(stanza);
          let error = stanza.getElementsByTagName("error");

          if (error.length !== 1) {
            converse_core_converse.connection._changeConnectStatus(converse_register_Strophe.Status.REGIFAIL, "unknown");

            return false;
          }

          error = error[0].firstElementChild.tagName.toLowerCase();

          if (error === 'conflict') {
            converse_core_converse.connection._changeConnectStatus(converse_register_Strophe.Status.CONFLICT, error);
          } else if (error === 'not-acceptable') {
            converse_core_converse.connection._changeConnectStatus(converse_register_Strophe.Status.NOTACCEPTABLE, error);
          } else {
            converse_core_converse.connection._changeConnectStatus(converse_register_Strophe.Status.REGIFAIL, error);
          }
        } else {
          converse_core_converse.connection._changeConnectStatus(converse_register_Strophe.Status.REGISTERED, null);
        }

        return false;
      }

    });
    /************************ BEGIN Event Handlers ************************/

    converse_core_api.listen.on('controlBoxInitialized', view => {
      view.model.on('change:active-form', view.showLoginOrRegisterForm, view);
    });
    /************************ END Event Handlers ************************/
  }

});
// CONCATENATED MODULE: ./src/templates/rooms_list.js



const rooms_list_bookmark = o => {
  const i18n_add_bookmark = i18n_('Bookmark this groupchat');

  const i18n_remove_bookmark = i18n_('Unbookmark this groupchat');

  if (o.bookmarked) {
    return lit_html_html`
            <a class="list-item-action fa fa-bookmark remove-bookmark button-on"
               data-room-jid="${o.room.get('jid')}"
               data-bookmark-name="${o.room.getDisplayName()}"
               @click=${o.removeBookmark}
               title="${o.bookmarked ? i18n_remove_bookmark : i18n_add_bookmark}"></a>`;
  } else {
    return lit_html_html`
            <a class="list-item-action fa fa-bookmark add-bookmark"
               data-room-jid="${o.room.get('jid')}"
               data-bookmark-name="${o.room.getDisplayName()}"
               @click=${o.addBookmark}
               title="${o.bookmarked ? i18n_remove_bookmark : i18n_add_bookmark}"></a>`;
  }
};

const room_item = o => {
  const i18n_leave_room = i18n_('Leave this groupchat');

  const unread_indicator = o => lit_html_html`<span class="list-item-badge badge badge--muc msgs-indicator">${o.room.get('num_unread')}</span>`;

  return lit_html_html`
        <div class="list-item controlbox-padded available-chatroom d-flex flex-row ${o.currently_open(o.room) ? 'open' : ''} ${o.room.get('num_unread_general') ? 'unread-msgs' : ''}"
            data-room-jid="${o.room.get('jid')}">

            ${o.room.get('num_unread') ? unread_indicator(o) : ''}
            <a class="list-item-link open-room available-room w-100"
            data-room-jid="${o.room.get('jid')}"
            title="${i18n_('Click to open this groupchat')}"
            @click=${o.openRoom}>${o.room.getDisplayName()}</a>

            ${o.allow_bookmarks ? rooms_list_bookmark(o) : ''}

            <a class="list-item-action room-info fa fa-info-circle"
            data-room-jid="${o.room.get('jid')}"
            title="${i18n_('Show more information on this groupchat')}"
            @click=${o.showRoomDetailsModal}></a>

            <a class="list-item-action fa fa-sign-out-alt close-room"
            data-room-jid="${o.room.get('jid')}"
            data-room-name="${o.room.getDisplayName()}"
            title="${i18n_leave_room}"
            @click=${o.closeRoom}></a>
        </div>`;
};

/* harmony default export */ var rooms_list = (o => {
  const i18n_desc_rooms = i18n_('Click to toggle the list of open groupchats');

  return lit_html_html`
        <div class="list-container list-container--openrooms ${o.rooms.length ? '' : 'hidden'}">
            <a class="list-toggle open-rooms-toggle controlbox-padded" title="${i18n_desc_rooms}" @click=${o.toggleRoomsList}>
            <span class="fa ${o.toggle_state === o._converse.OPENED ? 'fa-caret-down' : 'fa-caret-right'}"></span> ${i18n_('Open Groupchats')}</a>
            <div class="items-list rooms-list open-rooms-list ${o.collapsed && 'collapsed'}">
                ${o.rooms.map(room => room_item(Object.assign({
    room
  }, o)))}
            </div>
        </div>`;
});
// CONCATENATED MODULE: ./src/converse-roomslist.js
/**
 * @module converse-roomslist
 * @description
 *  Converse.js plugin which shows a list of currently open
 *  rooms in the "Rooms Panel" of the ControlBox.
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */







const {
  Strophe: converse_roomslist_Strophe
} = converse.env;
const converse_roomslist_u = converse.env.utils;
converse.plugins.add('converse-roomslist', {
  /* Optional dependencies are other plugins which might be
   * overridden or relied upon, and therefore need to be loaded before
   * this plugin. They are called "optional" because they might not be
   * available, in which case any overrides applicable to them will be
   * ignored.
   *
   * It's possible however to make optional dependencies non-optional.
   * If the setting "strict_plugin_dependencies" is set to true,
   * an error will be raised if the plugin is not found.
   *
   * NB: These plugins need to have already been loaded via require.js.
   */
  dependencies: ["converse-singleton", "converse-controlbox", "converse-muc", "converse-bookmarks"],

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    // Promises exposed by this plugin
    converse_core_api.promises.add('roomsListInitialized');
    converse_core_converse.RoomsList = model_Model.extend({
      defaults: {
        "toggle-state": converse_core_converse.OPENED
      }
    });
    converse_core_converse.RoomsListView = View.extend({
      tagName: 'span',

      initialize() {
        this.listenTo(this.model, 'add', this.renderIfChatRoom);
        this.listenTo(this.model, 'remove', this.renderIfChatRoom);
        this.listenTo(this.model, 'destroy', this.renderIfChatRoom);
        this.listenTo(this.model, 'change', this.renderIfRelevantChange);
        const id = `converse.roomslist${converse_core_converse.bare_jid}`;
        this.list_model = new converse_core_converse.RoomsList({
          id
        });
        this.list_model.browserStorage = converse_core_converse.createStore(id);
        this.list_model.fetch();
        this.render();
        this.insertIntoControlBox();
      },

      renderIfChatRoom(model) {
        converse_roomslist_u.isChatRoom(model) && this.render();
      },

      renderIfRelevantChange(model) {
        const attrs = ['bookmarked', 'hidden', 'name', 'num_unread', 'num_unread_general'];
        const changed = model.changed || {};

        if (converse_roomslist_u.isChatRoom(model) && Object.keys(changed).filter(m => attrs.includes(m)).length) {
          this.render();
        }
      },

      toHTML() {
        return rooms_list({
          '_converse': converse_core_converse,
          'addBookmark': ev => this.addBookmark(ev),
          'allow_bookmarks': converse_core_converse.allow_bookmarks && converse_core_converse.bookmarks,
          'closeRoom': ev => this.closeRoom(ev),
          'collapsed': this.list_model.get('toggle-state') !== converse_core_converse.OPENED,
          'currently_open': room => converse_core_converse.isUniView() && !room.get('hidden'),
          'openRoom': ev => this.openRoom(ev),
          'removeBookmark': ev => this.removeBookmark(ev),
          'rooms': this.model.filter(m => m.get('type') === converse_core_converse.CHATROOMS_TYPE),
          'showRoomDetailsModal': ev => this.showRoomDetailsModal(ev),
          'toggleRoomsList': ev => this.toggleRoomsList(ev),
          'toggle_state': this.list_model.get('toggle-state')
        });
      },

      insertIntoControlBox() {
        const controlboxview = converse_core_converse.chatboxviews.get('controlbox');

        if (controlboxview !== undefined && !converse_roomslist_u.rootContains(converse_core_converse.root, this.el)) {
          const el = controlboxview.el.querySelector('.list-container--openrooms');
          el && el.parentNode.replaceChild(this.el, el);
        }
      },

      showRoomDetailsModal(ev) {
        const jid = ev.target.getAttribute('data-room-jid');

        const room = converse_core_converse.chatboxes.get(jid);

        ev.preventDefault();

        if (room.room_details_modal === undefined) {
          room.room_details_modal = new muc_details({
            'model': room
          });
        }

        room.room_details_modal.show(ev);
      },

      async openRoom(ev) {
        ev.preventDefault();
        const name = ev.target.textContent;
        const jid = ev.target.getAttribute('data-room-jid');
        const data = {
          'name': name || converse_roomslist_Strophe.unescapeNode(converse_roomslist_Strophe.getNodeFromJid(jid)) || jid
        };
        await converse_core_api.rooms.open(jid, data, true);
        converse_core_api.chatviews.get(jid).maybeFocus();
      },

      closeRoom(ev) {
        ev.preventDefault();
        const name = ev.target.getAttribute('data-room-name');
        const jid = ev.target.getAttribute('data-room-jid');

        if (confirm(i18n_("Are you sure you want to leave the groupchat %1$s?", name))) {
          // TODO: replace with API call
          converse_core_converse.chatboxviews.get(jid).close();
        }
      },

      removeBookmark: converse_core_converse.removeBookmarkViaEvent,
      addBookmark: converse_core_converse.addBookmarkViaEvent,

      toggleRoomsList(ev) {
        if (ev && ev.preventDefault) {
          ev.preventDefault();
        }

        const icon_el = ev.target.matches('.fa') ? ev.target : ev.target.querySelector('.fa');

        if (icon_el.classList.contains("fa-caret-down")) {
          converse_roomslist_u.slideIn(this.el.querySelector('.open-rooms-list')).then(() => {
            this.list_model.save({
              'toggle-state': converse_core_converse.CLOSED
            });
            icon_el.classList.remove("fa-caret-down");
            icon_el.classList.add("fa-caret-right");
          });
        } else {
          converse_roomslist_u.slideOut(this.el.querySelector('.open-rooms-list')).then(() => {
            this.list_model.save({
              'toggle-state': converse_core_converse.OPENED
            });
            icon_el.classList.remove("fa-caret-right");
            icon_el.classList.add("fa-caret-down");
          });
        }
      }

    });

    const initRoomsListView = function () {
      converse_core_converse.rooms_list_view = new converse_core_converse.RoomsListView({
        'model': converse_core_converse.chatboxes
      });
      /**
       * Triggered once the _converse.RoomsListView has been created and initialized.
       * @event _converse#roomsListInitialized
       * @example _converse.api.listen.on('roomsListInitialized', status => { ... });
       */

      converse_core_api.trigger('roomsListInitialized');
    };

    converse_core_api.listen.on('connected', async () => {
      if (converse_core_converse.allow_bookmarks) {
        await converse_core_api.waitUntil('bookmarksInitialized');
      } else {
        await Promise.all([converse_core_api.waitUntil('chatBoxesFetched'), converse_core_api.waitUntil('roomsPanelRendered')]);
      }

      initRoomsListView();
    });
    converse_core_api.listen.on('reconnected', initRoomsListView);
  }

});
// CONCATENATED MODULE: ./src/templates/add_contact_modal.js



/* harmony default export */ var add_contact_modal = (o => {
  const i18n_contact_placeholder = i18n_('name@example.org');

  const i18n_add = i18n_('Add');

  const i18n_error_message = i18n_('Please enter a valid XMPP address');

  const i18n_new_contact = i18n_('Add a Contact');

  const i18n_xmpp_address = i18n_('XMPP Address');

  const i18n_nickname = i18n_('Nickname');

  return lit_html_html`
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addContactModalLabel">${i18n_new_contact}</h5>
                    ${modal_header_close_button}
                </div>
                <form class="converse-form add-xmpp-contact">
                    <div class="modal-body">
                        <span class="modal-alert"></span>
                        <div class="form-group add-xmpp-contact__jid">
                            <label class="clearfix" for="jid">${i18n_xmpp_address}:</label>
                            <div class="suggestion-box suggestion-box__jid">
                                <ul class="suggestion-box__results suggestion-box__results--above" hidden=""></ul>
                                <input type="text" name="jid" ?required=${!o._converse.xhr_user_search_url}
                                    value="${o.jid || ''}"
                                    class="form-control suggestion-box__input"
                                    placeholder="${i18n_contact_placeholder}"/>
                                <span class="suggestion-box__additions visually-hidden" role="status" aria-live="assertive" aria-relevant="additions"></span>
                            </div>
                        </div>
                        <div class="form-group add-xmpp-contact__name">
                            <label class="clearfix" for="name">${i18n_nickname}:</label>
                            <div class="suggestion-box suggestion-box__name">
                                <ul class="suggestion-box__results suggestion-box__results--above" hidden=""></ul>
                                <input type="text" name="name" value="${o.nickname || ''}"
                                    class="form-control suggestion-box__input"
                                    placeholder="${i18n_nickname}"/>
                                <span class="suggestion-box__additions visually-hidden" role="status" aria-live="assertive" aria-relevant="additions"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="invalid-feedback">${i18n_error_message}</div>
                        </div>
                        <button type="submit" class="btn btn-primary">${i18n_add}</button>
                    </div>
                </form>
            </div>
        </div>
    `;
});
// EXTERNAL MODULE: ./src/templates/group_header.html
var group_header = __webpack_require__(179);
var group_header_default = /*#__PURE__*/__webpack_require__.n(group_header);

// EXTERNAL MODULE: ./src/templates/pending_contact.html
var pending_contact = __webpack_require__(180);
var pending_contact_default = /*#__PURE__*/__webpack_require__.n(pending_contact);

// EXTERNAL MODULE: ./src/templates/requesting_contact.html
var requesting_contact = __webpack_require__(181);
var requesting_contact_default = /*#__PURE__*/__webpack_require__.n(requesting_contact);

// EXTERNAL MODULE: ./src/templates/roster.html
var roster = __webpack_require__(182);
var roster_default = /*#__PURE__*/__webpack_require__.n(roster);

// CONCATENATED MODULE: ./src/templates/roster_filter.js

/* harmony default export */ var roster_filter = (o => lit_html_html`
    <form class="controlbox-padded roster-filter-form input-button-group ${!o.visible ? 'hidden' : 'fade-in'}"
          @submit=${o.submitFilter}>
        <div class="form-inline flex-nowrap">
            <div class="filter-by d-flex flex-nowrap">
                <span @click=${o.changeTypeFilter} class="fa fa-user ${o.filter_type === 'contacts' ? 'selected' : ''}" data-type="contacts" title="${o.title_contact_filter}"></span>
                <span @click=${o.changeTypeFilter} class="fa fa-users ${o.filter_type === 'groups' ? 'selected' : ''}" data-type="groups" title="${o.title_group_filter}"></span>
                <span @click=${o.changeTypeFilter} class="fa fa-circle ${o.filter_type === 'state' ? 'selected' : ''}" data-type="state" title="${o.title_status_filter}"></span>
            </div>
            <div class="btn-group">
                <input .value="${o.filter_text || ''}"
                       @keydown=${o.liveFilter}
                       class="roster-filter form-control ${o.filter_type === 'state' ? 'hidden' : ''}"
                       placeholder="${o.placeholder}"/>
                <span class="clear-input fa fa-times ${!o.filter_text || o.filter_type === 'state' ? 'hidden' : ''}"
                      @click=${o.clearFilter}>
                </span>
            </div>
            <select class="form-control state-type ${o.filter_type !== 'state' ? 'hidden' : ''}"
                    @change=${o.changeChatStateFilter}>
                <option value="">${o.label_any}</option>
                <option ?selected=${o.chat_state === 'unread_messages'} value="unread_messages">${o.label_unread_messages}</option>
                <option ?selected=${o.chat_state === 'online'} value="online">${o.label_online}</option>
                <option ?selected=${o.chat_state === 'chat'} value="chat">${o.label_chatty}</option>
                <option ?selected=${o.chat_state === 'dnd'} value="dnd">${o.label_busy}</option>
                <option ?selected=${o.chat_state === 'away'} value="away">${o.label_away}</option>
                <option ?selected=${o.chat_state === 'xa'} value="xa">${o.label_xa}</option>
                <option ?selected=${o.chat_state === 'offline'} value="offline">${o.label_offline}</option>
            </select>
        </div>
    </form>
`);
// EXTERNAL MODULE: ./src/templates/roster_item.html
var templates_roster_item = __webpack_require__(183);
var roster_item_default = /*#__PURE__*/__webpack_require__.n(templates_roster_item);

// CONCATENATED MODULE: ./src/converse-rosterview.js
/**
 * @module converse-rosterview
 * @copyright 2020, the Converse.js contributors
 * @license Mozilla Public License (MPLv2)
 */


















const {
  Strophe: converse_rosterview_Strophe
} = converse.env;
const converse_rosterview_u = converse.env.utils;
converse.plugins.add('converse-rosterview', {
  dependencies: ["converse-roster", "converse-modal", "converse-chatboxviews"],

  initialize() {
    /* The initialize function gets called as soon as the plugin is
     * loaded by converse.js's plugin machinery.
     */
    converse_core_api.settings.extend({
      'autocomplete_add_contact': true,
      'allow_chat_pending_contacts': true,
      'allow_contact_removal': true,
      'hide_offline_users': false,
      'roster_groups': true,
      'xhr_user_search_url': null
    });
    converse_core_api.promises.add('rosterViewInitialized');
    const STATUSES = {
      'dnd': i18n_('This contact is busy'),
      'online': i18n_('This contact is online'),
      'offline': i18n_('This contact is offline'),
      'unavailable': i18n_('This contact is unavailable'),
      'xa': i18n_('This contact is away for an extended period'),
      'away': i18n_('This contact is away')
    };
    converse_core_converse.AddContactModal = BootstrapModal.extend({
      id: "add-contact-modal",
      events: {
        'submit form': 'addContactFromForm'
      },

      initialize() {
        BootstrapModal.prototype.initialize.apply(this, arguments);
        this.listenTo(this.model, 'change', this.render);
      },

      toHTML() {
        const label_nickname = converse_core_api.settings.get('xhr_user_search_url') ? i18n_('Contact name') : i18n_('Optional nickname');
        return add_contact_modal(Object.assign(this.model.toJSON(), {
          _converse: converse_core_converse,
          label_nickname
        }));
      },

      afterRender() {
        if (typeof converse_core_api.settings.get('xhr_user_search_url') === 'string') {
          this.initXHRAutoComplete();
        } else {
          this.initJIDAutoComplete();
        }

        const jid_input = this.el.querySelector('input[name="jid"]');
        this.el.addEventListener('shown.bs.modal', () => jid_input.focus(), false);
      },

      initJIDAutoComplete() {
        if (!converse_core_api.settings.get('autocomplete_add_contact')) {
          return;
        }

        const el = this.el.querySelector('.suggestion-box__jid').parentElement;
        this.jid_auto_complete = new converse_core_converse.AutoComplete(el, {
          'data': (text, input) => `${input.slice(0, input.indexOf("@"))}@${text}`,
          'filter': converse_core_converse.FILTER_STARTSWITH,
          'list': [...new Set(converse_core_converse.roster.map(item => converse_rosterview_Strophe.getDomainFromJid(item.get('jid'))))]
        });
      },

      initXHRAutoComplete() {
        if (!converse_core_api.settings.get('autocomplete_add_contact')) {
          return this.initXHRFetch();
        }

        const el = this.el.querySelector('.suggestion-box__name').parentElement;
        this.name_auto_complete = new converse_core_converse.AutoComplete(el, {
          'auto_evaluate': false,
          'filter': converse_core_converse.FILTER_STARTSWITH,
          'list': []
        });
        const xhr = new window.XMLHttpRequest(); // `open` must be called after `onload` for mock/testing purposes.

        xhr.onload = () => {
          if (xhr.responseText) {
            const r = xhr.responseText;
            this.name_auto_complete.list = JSON.parse(r).map(i => ({
              'label': i.fullname || i.jid,
              'value': i.jid
            }));
            this.name_auto_complete.auto_completing = true;
            this.name_auto_complete.evaluate();
          }
        };

        const input_el = this.el.querySelector('input[name="name"]');
        input_el.addEventListener('input', lodash_es_debounce(() => {
          xhr.open("GET", `${converse_core_api.settings.get('xhr_user_search_url')}q=${encodeURIComponent(input_el.value)}`, true);
          xhr.send();
        }, 300));
        this.name_auto_complete.on('suggestion-box-selectcomplete', ev => {
          this.el.querySelector('input[name="name"]').value = ev.text.label;
          this.el.querySelector('input[name="jid"]').value = ev.text.value;
        });
      },

      initXHRFetch() {
        this.xhr = new window.XMLHttpRequest();

        this.xhr.onload = () => {
          if (this.xhr.responseText) {
            const r = this.xhr.responseText;
            const list = JSON.parse(r).map(i => ({
              'label': i.fullname || i.jid,
              'value': i.jid
            }));

            if (list.length !== 1) {
              const el = this.el.querySelector('.invalid-feedback');
              el.textContent = i18n_('Sorry, could not find a contact with that name');
              converse_rosterview_u.addClass('d-block', el);
              return;
            }

            const jid = list[0].value;

            if (this.validateSubmission(jid)) {
              const form = this.el.querySelector('form');
              const name = list[0].label;
              this.afterSubmission(form, jid, name);
            }
          }
        };
      },

      validateSubmission(jid) {
        const el = this.el.querySelector('.invalid-feedback');

        if (!jid || lodash_es_compact(jid.split('@')).length < 2) {
          converse_rosterview_u.addClass('is-invalid', this.el.querySelector('input[name="jid"]'));
          converse_rosterview_u.addClass('d-block', el);
          return false;
        } else if (converse_core_converse.roster.get(converse_rosterview_Strophe.getBareJidFromJid(jid))) {
          el.textContent = i18n_('This contact has already been added');
          converse_rosterview_u.addClass('d-block', el);
          return false;
        }

        converse_rosterview_u.removeClass('d-block', el);
        return true;
      },

      afterSubmission(form, jid, name) {
        converse_core_converse.roster.addAndSubscribe(jid, name);

        this.model.clear();
        this.modal.hide();
      },

      addContactFromForm(ev) {
        ev.preventDefault();
        const data = new FormData(ev.target),
              jid = (data.get('jid') || '').trim();

        if (!jid && typeof converse_core_api.settings.get('xhr_user_search_url') === 'string') {
          const input_el = this.el.querySelector('input[name="name"]');
          this.xhr.open("GET", `${converse_core_api.settings.get('xhr_user_search_url')}q=${encodeURIComponent(input_el.value)}`, true);
          this.xhr.send();
          return;
        }

        if (this.validateSubmission(jid)) {
          this.afterSubmission(ev.target, jid, data.get('name'));
        }
      }

    });
    converse_core_converse.RosterFilter = model_Model.extend({
      initialize() {
        this.set({
          'filter_text': '',
          'filter_type': 'contacts',
          'chat_state': 'online'
        });
      }

    });
    converse_core_converse.RosterFilterView = View.extend({
      tagName: 'span',

      initialize() {
        this.listenTo(this.model, 'change:filter_type', this.render);
        this.listenTo(this.model, 'change:filter_text', this.render);
      },

      toHTML() {
        return roster_filter(Object.assign(this.model.toJSON(), {
          visible: this.shouldBeVisible(),
          placeholder: i18n_('Filter'),
          title_contact_filter: i18n_('Filter by contact name'),
          title_group_filter: i18n_('Filter by group name'),
          title_status_filter: i18n_('Filter by status'),
          label_any: i18n_('Any'),
          label_unread_messages: i18n_('Unread'),
          label_online: i18n_('Online'),
          label_chatty: i18n_('Chatty'),
          label_busy: i18n_('Busy'),
          label_away: i18n_('Away'),
          label_xa: i18n_('Extended Away'),
          label_offline: i18n_('Offline'),
          changeChatStateFilter: ev => this.changeChatStateFilter(ev),
          changeTypeFilter: ev => this.changeTypeFilter(ev),
          clearFilter: ev => this.clearFilter(ev),
          liveFilter: ev => this.liveFilter(ev),
          submitFilter: ev => this.submitFilter(ev)
        }));
      },

      changeChatStateFilter(ev) {
        ev && ev.preventDefault();
        this.model.save({
          'chat_state': this.el.querySelector('.state-type').value
        });
      },

      changeTypeFilter(ev) {
        ev && ev.preventDefault();
        const type = ev.target.dataset.type;

        if (type === 'state') {
          this.model.save({
            'filter_type': type,
            'chat_state': this.el.querySelector('.state-type').value
          });
        } else {
          this.model.save({
            'filter_type': type,
            'filter_text': this.el.querySelector('.roster-filter').value
          });
        }
      },

      liveFilter: lodash_es_debounce(function () {
        this.model.save({
          'filter_text': this.el.querySelector('.roster-filter').value
        });
      }, 250),

      submitFilter(ev) {
        ev && ev.preventDefault();
        this.liveFilter();
      },

      /**
       * Returns true if the filter is enabled (i.e. if the user
       * has added values to the filter).
       * @private
       * @method _converse.RosterFilterView#isActive
       */
      isActive() {
        return this.model.get('filter_type') === 'state' || this.model.get('filter_text');
      },

      shouldBeVisible() {
        return converse_core_converse.roster && converse_core_converse.roster.length >= 5 || this.isActive();
      },

      clearFilter(ev) {
        ev && ev.preventDefault();
        this.model.save({
          'filter_text': ''
        });
      }

    });
    converse_core_converse.RosterContactView = converse_core_converse.ViewWithAvatar.extend({
      tagName: 'li',
      className: 'list-item d-flex hidden controlbox-padded',
      events: {
        "click .accept-xmpp-request": "acceptRequest",
        "click .decline-xmpp-request": "declineRequest",
        "click .open-chat": "openChat",
        "click .remove-xmpp-contact": "removeContact"
      },

      async initialize() {
        await this.model.initialized;
        this.debouncedRender = lodash_es_debounce(this.render, 50);
        this.listenTo(this.model, "change", this.debouncedRender);
        this.listenTo(this.model, "destroy", this.remove);
        this.listenTo(this.model, "highlight", this.highlight);
        this.listenTo(this.model, "remove", this.remove);
        this.listenTo(this.model, 'vcard:change', this.debouncedRender);
        this.listenTo(this.model.presence, "change:show", this.debouncedRender);
        this.render();
      },

      render() {
        if (!this.mayBeShown()) {
          converse_rosterview_u.hideElement(this.el);
          return this;
        }

        const ask = this.model.get('ask'),
              show = this.model.presence.get('show'),
              requesting = this.model.get('requesting'),
              subscription = this.model.get('subscription'),
              jid = this.model.get('jid');
        const classes_to_remove = ['current-xmpp-contact', 'pending-xmpp-contact', 'requesting-xmpp-contact'].concat(Object.keys(STATUSES));
        classes_to_remove.forEach(c => converse_rosterview_u.removeClass(c, this.el));
        this.el.classList.add(show);
        this.el.setAttribute('data-status', show);
        this.highlight();

        if (converse_core_converse.isUniView()) {
          const chatbox = converse_core_converse.chatboxes.get(this.model.get('jid'));

          if (chatbox) {
            if (chatbox.get('hidden')) {
              this.el.classList.remove('open');
            } else {
              this.el.classList.add('open');
            }
          }
        }

        if (ask === 'subscribe' || subscription === 'from') {
          /* ask === 'subscribe'
           *      Means we have asked to subscribe to them.
           *
           * subscription === 'from'
           *      They are subscribed to use, but not vice versa.
           *      We assume that there is a pending subscription
           *      from us to them (otherwise we're in a state not
           *      supported by converse.js).
           *
           *  So in both cases the user is a "pending" contact.
           */
          const display_name = this.model.getDisplayName();
          this.el.classList.add('pending-xmpp-contact');
          this.el.innerHTML = pending_contact_default()(Object.assign(this.model.toJSON(), {
            display_name,
            'desc_remove': i18n_('Click to remove %1$s as a contact', display_name),
            'allow_chat_pending_contacts': converse_core_api.settings.get('allow_chat_pending_contacts')
          }));
        } else if (requesting === true) {
          const display_name = this.model.getDisplayName();
          this.el.classList.add('requesting-xmpp-contact');
          this.el.innerHTML = requesting_contact_default()(Object.assign(this.model.toJSON(), {
            display_name,
            'desc_accept': i18n_("Click to accept the contact request from %1$s", display_name),
            'desc_decline': i18n_("Click to decline the contact request from %1$s", display_name),
            'allow_chat_pending_contacts': converse_core_api.settings.get('allow_chat_pending_contacts')
          }));
        } else if (subscription === 'both' || subscription === 'to' || converse_core_converse.rosterview.isSelf(jid)) {
          this.el.classList.add('current-xmpp-contact');
          this.el.classList.remove(lodash_es_without(['both', 'to'], subscription)[0]);
          this.el.classList.add(subscription);
          this.renderRosterItem(this.model);
        }

        return this;
      },

      /**
       * If appropriate, highlight the contact (by adding the 'open' class).
       * @private
       * @method _converse.RosterContactView#highlight
       */
      highlight() {
        if (converse_core_converse.isUniView()) {
          const chatbox = converse_core_converse.chatboxes.get(this.model.get('jid'));

          if (chatbox && chatbox.get('hidden') || !chatbox) {
            this.el.classList.remove('open');
          } else {
            this.el.classList.add('open');
          }
        }
      },

      renderRosterItem(item) {
        const show = item.presence.get('show') || 'offline';
        let status_icon;

        if (show === 'online') {
          status_icon = 'fa fa-circle chat-status chat-status--online';
        } else if (show === 'away') {
          status_icon = 'fa fa-circle chat-status chat-status--away';
        } else if (show === 'xa') {
          status_icon = 'far fa-circle chat-status chat-status-xa';
        } else if (show === 'dnd') {
          status_icon = 'fa fa-minus-circle chat-status chat-status--busy';
        } else {
          status_icon = 'fa fa-times-circle chat-status chat-status--offline';
        }

        const display_name = item.getDisplayName();
        this.el.innerHTML = roster_item_default()(Object.assign(item.toJSON(), {
          show,
          display_name,
          status_icon,
          'desc_status': STATUSES[show],
          'desc_chat': i18n_('Click to chat with %1$s (XMPP address: %2$s)', display_name, item.get('jid')),
          'desc_remove': i18n_('Click to remove %1$s as a contact', display_name),
          'allow_contact_removal': converse_core_api.settings.get('allow_contact_removal'),
          'num_unread': item.get('num_unread') || 0,
          classes: ''
        }));
        this.renderAvatar();
        return this;
      },

      /**
       * Returns a boolean indicating whether this contact should
       * generally be visible in the roster.
       * It doesn't check for the more specific case of whether
       * the group it's in is collapsed.
       * @private
       * @method _converse.RosterContactView#mayBeShown
       */
      mayBeShown() {
        const chatStatus = this.model.presence.get('show');

        if (converse_core_api.settings.get('hide_offline_users') && chatStatus === 'offline') {
          // If pending or requesting, show
          if (this.model.get('ask') === 'subscribe' || this.model.get('subscription') === 'from' || this.model.get('requesting') === true) {
            return true;
          }

          return false;
        }

        return true;
      },

      openChat(ev) {
        if (ev && ev.preventDefault) {
          ev.preventDefault();
        }

        this.model.openChat();
      },

      async removeContact(ev) {
        if (ev && ev.preventDefault) {
          ev.preventDefault();
        }

        if (!converse_core_api.settings.get('allow_contact_removal')) {
          return;
        }

        if (!confirm(i18n_("Are you sure you want to remove this contact?"))) {
          return;
        }

        try {
          await this.model.removeFromRoster();
          this.remove();

          if (this.model.collection) {
            // The model might have already been removed as
            // result of a roster push.
            this.model.destroy();
          }
        } catch (e) {
          headless_log.error(e);
          converse_core_api.alert('error', i18n_('Error'), [i18n_('Sorry, there was an error while trying to remove %1$s as a contact.', this.model.getDisplayName())]);
        }
      },

      async acceptRequest(ev) {
        if (ev && ev.preventDefault) {
          ev.preventDefault();
        }

        await converse_core_converse.roster.sendContactAddIQ(this.model.get('jid'), this.model.getFullname(), []);
        this.model.authorize().subscribe();
      },

      declineRequest(ev) {
        if (ev && ev.preventDefault) {
          ev.preventDefault();
        }

        const result = confirm(i18n_("Are you sure you want to decline this contact request?"));

        if (result === true) {
          this.model.unauthorize().destroy();
        }

        return this;
      }

    });
    /**
     * @class
     * @namespace _converse.RosterGroupView
     * @memberOf _converse
     */

    converse_core_converse.RosterGroupView = OrderedListView.extend({
      tagName: 'div',
      className: 'roster-group hidden',
      events: {
        "click a.group-toggle": "toggle"
      },
      sortImmediatelyOnAdd: true,
      ItemView: converse_core_converse.RosterContactView,
      listItems: 'model.contacts',
      listSelector: '.roster-group-contacts',
      sortEvent: 'presenceChanged',

      initialize() {
        OrderedListView.prototype.initialize.apply(this, arguments);

        if (this.model.get('name') === converse_core_converse.HEADER_UNREAD) {
          this.listenTo(this.model.contacts, "change:num_unread", c => !this.model.get('unread_messages') && this.removeContact(c));
        }

        if (this.model.get('name') === converse_core_converse.HEADER_REQUESTING_CONTACTS) {
          this.listenTo(this.model.contacts, "change:requesting", c => !c.get('requesting') && this.removeContact(c));
        }

        if (this.model.get('name') === converse_core_converse.HEADER_PENDING_CONTACTS) {
          this.listenTo(this.model.contacts, "change:subscription", c => c.get('subscription') !== 'from' && this.removeContact(c));
        }

        this.listenTo(this.model.contacts, "remove", this.onRemove);
        this.listenTo(converse_core_converse.roster, 'change:groups', this.onContactGroupChange); // This event gets triggered once *all* contacts (i.e. not
        // just this group's) have been fetched from browser
        // storage or the XMPP server and once they've been
        // assigned to their various groups.

        converse_core_converse.rosterview.on('rosterContactsFetchedAndProcessed', () => this.sortAndPositionAllItems());
      },

      render() {
        this.el.setAttribute('data-group', this.model.get('name'));
        this.el.innerHTML = group_header_default()({
          'label_group': this.model.get('name'),
          'desc_group_toggle': this.model.get('description'),
          'toggle_state': this.model.get('state'),
          '_converse': converse_core_converse
        });
        this.contacts_el = this.el.querySelector('.roster-group-contacts');
        return this;
      },

      show() {
        converse_rosterview_u.showElement(this.el);

        if (this.model.get('state') === converse_core_converse.OPENED) {
          Object.values(this.getAll()).filter(v => v.mayBeShown()).forEach(v => converse_rosterview_u.showElement(v.el));
        }

        return this;
      },

      collapse() {
        return converse_rosterview_u.slideIn(this.contacts_el);
      },

      /* Given a list of contacts, make sure they're filtered out
       * (aka hidden) and that all other contacts are visible.
       * If all contacts are hidden, then also hide the group title.
       * @private
       * @method _converse.RosterGroupView#filterOutContacts
       * @param { Array } contacts
       */
      filterOutContacts(contacts = []) {
        let shown = 0;
        this.model.contacts.forEach(contact => {
          const contact_view = this.get(contact.get('id'));

          if (contacts.includes(contact)) {
            converse_rosterview_u.hideElement(contact_view.el);
          } else if (contact_view.mayBeShown()) {
            converse_rosterview_u.showElement(contact_view.el);
            shown += 1;
          }
        });

        if (shown) {
          converse_rosterview_u.showElement(this.el);
        } else {
          converse_rosterview_u.hideElement(this.el);
        }
      },

      /**
       * Given the filter query "q" and the filter type "type",
       * return a list of contacts that need to be filtered out.
       * @private
       * @method _converse.RosterGroupView#getFilterMatches
       * @param { String } q - The filter query
       * @param { String } type - The filter type
       */
      getFilterMatches(q, type) {
        if (q.length === 0) {
          return [];
        }

        q = q.toLowerCase();
        const contacts = this.model.contacts;

        if (type === 'state') {
          const sticky_groups = [converse_core_converse.HEADER_REQUESTING_CONTACTS, converse_core_converse.HEADER_UNREAD];

          if (sticky_groups.includes(this.model.get('name'))) {
            // When filtering by chat state, we still want to
            // show sticky groups, even though they don't
            // match the state in question.
            return [];
          } else if (q === 'unread_messages') {
            return contacts.filter({
              'num_unread': 0
            });
          } else if (q === 'online') {
            return contacts.filter(c => ["offline", "unavailable"].includes(c.presence.get('show')));
          } else {
            return contacts.filter(c => !c.presence.get('show').includes(q));
          }
        } else {
          return contacts.filter(c => !c.getFilterCriteria().includes(q));
        }
      },

      /**
       * Filter the group's contacts based on the query "q".
       *
       * If all contacts are filtered out (i.e. hidden), then the
       * group must be filtered out as well.
       * @private
       * @method _converse.RosterGroupView#filter
       * @param { string } q - The query to filter against
       * @param { string } type
       */
      filter(q, type) {
        if (q === null || q === undefined) {
          type = type || converse_core_converse.rosterview.filter_view.model.get('filter_type');

          if (type === 'state') {
            q = converse_core_converse.rosterview.filter_view.model.get('chat_state');
          } else {
            q = converse_core_converse.rosterview.filter_view.model.get('filter_text');
          }
        }

        this.filterOutContacts(this.getFilterMatches(q, type));
      },

      async toggle(ev) {
        if (ev && ev.preventDefault) {
          ev.preventDefault();
        }

        const icon_el = ev.target.matches('.fa') ? ev.target : ev.target.querySelector('.fa');

        if (converse_rosterview_u.hasClass("fa-caret-down", icon_el)) {
          this.model.save({
            state: converse_core_converse.CLOSED
          });
          await this.collapse();
          icon_el.classList.remove("fa-caret-down");
          icon_el.classList.add("fa-caret-right");
        } else {
          icon_el.classList.remove("fa-caret-right");
          icon_el.classList.add("fa-caret-down");
          this.model.save({
            state: converse_core_converse.OPENED
          });
          this.filter();
          converse_rosterview_u.showElement(this.el);
          converse_rosterview_u.slideOut(this.contacts_el);
        }
      },

      onContactGroupChange(contact) {
        const in_this_group = contact.get('groups').includes(this.model.get('name'));
        const cid = contact.get('id');
        const in_this_overview = !this.get(cid);

        if (in_this_group && !in_this_overview) {
          this.items.trigger('add', contact);
        } else if (!in_this_group) {
          this.removeContact(contact);
        }
      },

      removeContact(contact) {
        // We suppress events, otherwise the remove event will
        // also cause the contact's view to be removed from the
        // "Pending Contacts" group.
        this.model.contacts.remove(contact, {
          'silent': true
        });
        this.onRemove(contact);
      },

      onRemove(contact) {
        this.remove(contact.get('jid'));

        if (this.model.contacts.length === 0) {
          this.remove();
        }
      }

    });
    /**
     * @class
     * @namespace _converse.RosterView
     * @memberOf _converse
     */

    converse_core_converse.RosterView = OrderedListView.extend({
      tagName: 'div',
      id: 'converse-roster',
      className: 'controlbox-section',
      ItemView: converse_core_converse.RosterGroupView,
      listItems: 'model',
      listSelector: '.roster-contacts',
      sortEvent: null,
      // Groups are immutable, so they don't get re-sorted
      subviewIndex: 'name',
      sortImmediatelyOnAdd: true,
      events: {
        'click a.controlbox-heading__btn.add-contact': 'showAddContactModal',
        'click a.controlbox-heading__btn.sync-contacts': 'syncContacts'
      },

      initialize() {
        OrderedListView.prototype.initialize.apply(this, arguments);
        this.listenTo(converse_core_converse.roster, "add", this.onContactAdded);
        this.listenTo(converse_core_converse.roster, 'change:groups', this.onContactAdded);
        this.listenTo(converse_core_converse.roster, 'change', this.onContactChange);
        this.listenTo(converse_core_converse.roster, "destroy", this.update);
        this.listenTo(converse_core_converse.roster, "remove", this.update);

        converse_core_converse.presences.on('change:show', () => {
          this.update();
          this.updateFilter();
        });

        this.listenTo(this.model, "reset", this.reset); // This event gets triggered once *all* contacts (i.e. not
        // just this group's) have been fetched from browser
        // storage or the XMPP server and once they've been
        // assigned to their various groups.

        converse_core_api.listen.on('rosterGroupsFetched', this.sortAndPositionAllItems.bind(this));
        converse_core_api.listen.on('rosterContactsFetched', () => {
          converse_core_converse.roster.each(contact => this.addRosterContact(contact, {
            'silent': true
          }));

          this.update();
          this.updateFilter();
          this.trigger('rosterContactsFetchedAndProcessed');
        });
        this.createRosterFilter();
      },

      render() {
        this.el.innerHTML = roster_default()({
          'allow_contact_requests': converse_core_converse.allow_contact_requests,
          'heading_contacts': i18n_('Contacts'),
          'title_add_contact': i18n_('Add a contact'),
          'title_sync_contacts': i18n_('Re-sync your contacts')
        });
        const form = this.el.querySelector('.roster-filter-form');
        this.el.replaceChild(this.filter_view.render().el, form);
        this.roster_el = this.el.querySelector('.roster-contacts');
        return this;
      },

      showAddContactModal(ev) {
        if (this.add_contact_modal === undefined) {
          this.add_contact_modal = new converse_core_converse.AddContactModal({
            'model': new model_Model()
          });
        }

        this.add_contact_modal.show(ev);
      },

      createRosterFilter() {
        // Create a model on which we can store filter properties
        const model = new converse_core_converse.RosterFilter();
        model.id = `_converse.rosterfilter-${converse_core_converse.bare_jid}`;
        model.browserStorage = converse_core_converse.createStore(model.id);
        this.filter_view = new converse_core_converse.RosterFilterView({
          model
        });
        this.listenTo(this.filter_view.model, 'change', this.updateFilter);
        this.filter_view.model.fetch();
      },

      /**
       * Called whenever the filter settings have been changed or
       * when contacts have been added, removed or changed.
       *
       * Debounced for 100ms so that it doesn't get called for every
       * contact fetched from browser storage.
       */
      updateFilter: lodash_es_debounce(function () {
        const type = this.filter_view.model.get('filter_type');

        if (type === 'state') {
          this.filter(this.filter_view.model.get('chat_state'), type);
        } else {
          this.filter(this.filter_view.model.get('filter_text'), type);
        }
      }, 100),

      update() {
        if (!converse_rosterview_u.isVisible(this.roster_el)) {
          converse_rosterview_u.showElement(this.roster_el);
        }

        this.filter_view.render();
        return this;
      },

      filter(query, type) {
        const views = Object.values(this.getAll()); // First ensure the filter is restored to its original state

        views.forEach(v => v.model.contacts.length > 0 && v.show().filter('')); // Now we can filter

        query = query.toLowerCase();

        if (type === 'groups') {
          views.forEach(view => {
            if (!view.model.get('name').toLowerCase().includes(query)) {
              converse_rosterview_u.slideIn(view.el);
            } else if (view.model.contacts.length > 0) {
              converse_rosterview_u.slideOut(view.el);
            }
          });
        } else {
          views.forEach(v => v.filter(query, type));
        }
      },

      async syncContacts(ev) {
        ev.preventDefault();
        converse_rosterview_u.addClass('fa-spin', ev.target);

        converse_core_converse.roster.data.save('version', null);

        await converse_core_converse.roster.fetchFromServer();
        converse_core_api.user.presence.send();
        converse_rosterview_u.removeClass('fa-spin', ev.target);
      },

      reset() {
        this.removeAll();
        this.render().update();
        return this;
      },

      onContactAdded(contact) {
        this.addRosterContact(contact);
        this.update();
        this.updateFilter();
      },

      onContactChange(contact) {
        this.update();

        if (lodash_es_has(contact.changed, 'subscription')) {
          if (contact.changed.subscription === 'from') {
            this.addContactToGroup(contact, converse_core_converse.HEADER_PENDING_CONTACTS);
          } else if (['both', 'to'].includes(contact.get('subscription'))) {
            this.addExistingContact(contact);
          }
        }

        if (lodash_es_has(contact.changed, 'num_unread') && contact.get('num_unread')) {
          this.addContactToGroup(contact, converse_core_converse.HEADER_UNREAD);
        }

        if (lodash_es_has(contact.changed, 'ask') && contact.changed.ask === 'subscribe') {
          this.addContactToGroup(contact, converse_core_converse.HEADER_PENDING_CONTACTS);
        }

        if (lodash_es_has(contact.changed, 'subscription') && contact.changed.requesting === 'true') {
          this.addContactToGroup(contact, converse_core_converse.HEADER_REQUESTING_CONTACTS);
        }

        this.updateFilter();
      },

      /**
       * Returns the group as specified by name.
       * Creates the group if it doesn't exist.
       * @method _converse.RosterView#getGroup
       * @private
       * @param {string} name
       */
      getGroup(name) {
        const view = this.get(name);

        if (view) {
          return view.model;
        }

        return this.model.create({
          name
        });
      },

      addContactToGroup(contact, name, options) {
        this.getGroup(name).contacts.add(contact, options);
        this.sortAndPositionAllItems();
      },

      addExistingContact(contact, options) {
        let groups;

        if (converse_core_api.settings.get('roster_groups')) {
          groups = contact.get('groups');
          groups = groups.length === 0 ? [converse_core_converse.HEADER_UNGROUPED] : groups;
        } else {
          groups = [converse_core_converse.HEADER_CURRENT_CONTACTS];
        }

        if (contact.get('num_unread')) {
          groups.push(converse_core_converse.HEADER_UNREAD);
        }

        groups.forEach(g => this.addContactToGroup(contact, g, options));
      },

      isSelf(jid) {
        return converse_rosterview_u.isSameBareJID(jid, converse_core_converse.connection.jid);
      },

      addRosterContact(contact, options) {
        const jid = contact.get('jid');

        if (contact.get('subscription') === 'both' || contact.get('subscription') === 'to' || this.isSelf(jid)) {
          this.addExistingContact(contact, options);
        } else {
          if (!converse_core_converse.allow_contact_requests) {
            headless_log.debug(`Not adding requesting or pending contact ${jid} ` + `because allow_contact_requests is false`);
            return;
          }

          if (contact.get('ask') === 'subscribe' || contact.get('subscription') === 'from') {
            this.addContactToGroup(contact, converse_core_converse.HEADER_PENDING_CONTACTS, options);
          } else if (contact.get('requesting') === true) {
            this.addContactToGroup(contact, converse_core_converse.HEADER_REQUESTING_CONTACTS, options);
          }
        }

        return this;
      }

    });
    /* -------- Event Handlers ----------- */

    converse_core_api.listen.on('chatBoxesInitialized', () => {
      function highlightRosterItem(chatbox) {
        const contact = converse_core_converse.roster && converse_core_converse.roster.findWhere({
          'jid': chatbox.get('jid')
        });

        if (contact !== undefined) {
          contact.trigger('highlight');
        }
      }

      converse_core_converse.chatboxes.on('destroy', chatbox => highlightRosterItem(chatbox));

      converse_core_converse.chatboxes.on('change:hidden', chatbox => highlightRosterItem(chatbox));
    });
    converse_core_api.listen.on('controlBoxInitialized', view => {
      function insertRoster() {
        if (!view.model.get('connected') || converse_core_api.settings.get("authentication") === converse_core_converse.ANONYMOUS) {
          return;
        }
        /* Place the rosterview inside the "Contacts" panel. */


        converse_core_api.waitUntil('rosterViewInitialized').then(() => view.controlbox_pane.el.insertAdjacentElement('beforeEnd', converse_core_converse.rosterview.el)).catch(e => headless_log.fatal(e));
      }

      insertRoster();
      view.model.on('change:connected', insertRoster);
    });

    function initRosterView() {
      /* Create an instance of RosterView once the RosterGroups
       * collection has been created (in @converse/headless/converse-core.js)
       */
      if (converse_core_api.settings.get("authentication") === converse_core_converse.ANONYMOUS) {
        return;
      }

      converse_core_converse.rosterview = new converse_core_converse.RosterView({
        'model': converse_core_converse.rostergroups
      });

      converse_core_converse.rosterview.render();
      /**
       * Triggered once the _converse.RosterView instance has been created and initialized.
       * @event _converse#rosterViewInitialized
       * @example _converse.api.listen.on('rosterViewInitialized', () => { ... });
       */


      converse_core_api.trigger('rosterViewInitialized');
    }

    converse_core_api.listen.on('rosterInitialized', initRosterView);
    converse_core_api.listen.on('rosterReadyAfterReconnection', initRosterView);
    converse_core_api.listen.on('afterTearDown', () => {
      if (converse.rosterview) {
        converse.rosterview.model.off().reset();
        converse.rosterview.each(groupview => groupview.removeAll().remove());
        converse.rosterview.removeAll().remove();
        delete converse.rosterview;
      }
    });
  }

});
// EXTERNAL MODULE: ./sass/converse.scss
var sass_converse = __webpack_require__(496);

// CONCATENATED MODULE: ./src/converse.js
/**
 * @description Converse.js (A browser based XMPP chat client)
 * @copyright 2020, The Converse developers
 * @license Mozilla Public License (MPLv2)
 */

/* START: Removable components
 * --------------------
 * Any of the following components may be removed if they're not needed.
 */





 // Views for XEP-0048 Bookmarks

 // Renders standalone chat boxes for single user chat

 // The control box

 // Allows chat boxes to be resized by dragging them



 // Allows chat boxes to be minimized

 // Views related to MUC


 // HTML5 Notifications



 // XEP-0357 Push Notifications

 // XEP-0077 In-band registration

 // Show currently open chat rooms




/* END: Removable components */




converse_core_converse.CustomElement = element_CustomElement;
const WHITELISTED_PLUGINS = ['converse-autocomplete', 'converse-bookmark-views', 'converse-chatboxviews', 'converse-chatview', 'converse-controlbox', 'converse-dragresize', 'converse-fullscreen', 'converse-mam-views', 'converse-minimize', 'converse-modal', 'converse-muc-views', 'converse-headlines-view', 'converse-notification', 'converse-omemo', 'converse-profile', 'converse-push', 'converse-register', 'converse-roomslist', 'converse-rosterview', 'converse-singleton']; // Use Mustache style syntax for variable interpolation

/* Configuration of Lodash templates (this config is distinct to the
 * config of requirejs-tpl in main.js). This one is for normal inline templates.
 */

lodash_noconflict_default.a.templateSettings = {
  'escape': /\{\{\{([\s\S]+?)\}\}\}/g,
  'evaluate': /\{\[([\s\S]+?)\]\}/g,
  'interpolate': /\{\{([\s\S]+?)\}\}/g,
  'imports': {
    '_': lodash_noconflict_default.a
  }
};
converse.env._ = lodash_noconflict_default.a;
const initialize = converse.initialize;

converse.initialize = function (settings, callback) {
  if (Array.isArray(settings.whitelisted_plugins)) {
    settings.whitelisted_plugins = settings.whitelisted_plugins.concat(WHITELISTED_PLUGINS);
  } else {
    settings.whitelisted_plugins = WHITELISTED_PLUGINS;
  }

  return initialize(settings, callback);
};

/* harmony default export */ var src_converse = __webpack_exports__["default"] = (converse);

/***/ })
/******/ ]);
//# sourceMappingURL=converse.js.map