', {}, {\n CurrentPageURL: getRedactedUrl()\n })\n }, { expl: (0, _languageHandler._td)('Your User Agent'), value: navigator.userAgent }, { expl: (0, _languageHandler._td)('Your device resolution'), value: resolution }];\n\n var ErrorDialog = _index2.default.getComponent('dialogs.ErrorDialog');\n _Modal2.default.createTrackedDialog('Analytics Details', '', ErrorDialog, {\n title: (0, _languageHandler._t)('Analytics'),\n description: React.createElement(\n 'div',\n { className: 'mx_AnalyticsModal' },\n React.createElement(\n 'div',\n null,\n (0, _languageHandler._t)('The information being sent to us to help make Riot.im better includes:')\n ),\n React.createElement(\n 'table',\n null,\n rows.map(function (row) {\n return React.createElement(\n 'tr',\n { key: row[0] },\n React.createElement(\n 'td',\n null,\n (0, _languageHandler._t)(customVariables[row[0]].expl)\n ),\n row[1] !== undefined && React.createElement(\n 'td',\n null,\n React.createElement(\n 'code',\n null,\n row[1]\n )\n )\n );\n }),\n otherVariables.map(function (item, index) {\n return React.createElement(\n 'tr',\n { key: index },\n React.createElement(\n 'td',\n null,\n (0, _languageHandler._t)(item.expl)\n ),\n React.createElement(\n 'td',\n null,\n React.createElement(\n 'code',\n null,\n item.value\n )\n )\n );\n })\n ),\n React.createElement(\n 'div',\n null,\n (0, _languageHandler._t)('Where this page includes identifiable information, such as a room, ' + 'user or group ID, that data is removed before being sent to the server.')\n )\n )\n });\n }\n }]);\n return Analytics;\n}();\n\nif (!global.mxAnalytics) {\n global.mxAnalytics = new Analytics();\n}\nmodule.exports = global.mxAnalytics;\n//# sourceMappingURL=Analytics.js.map","module.exports = function (it) {\n if (typeof it != 'function') throw TypeError(it + ' is not a function!');\n return it;\n};\n","module.exports = { \"default\": require(\"core-js/library/fn/object/create\"), __esModule: true };","// optional / simple context binding\nvar aFunction = require('./_a-function');\nmodule.exports = function (fn, that, length) {\n aFunction(fn);\n if (that === undefined) return fn;\n switch (length) {\n case 1: return function (a) {\n return fn.call(that, a);\n };\n case 2: return function (a, b) {\n return fn.call(that, a, b);\n };\n case 3: return function (a, b, c) {\n return fn.call(that, a, b, c);\n };\n }\n return function (/* ...args */) {\n return fn.apply(that, arguments);\n };\n};\n","// most Object methods by ES6 should accept primitives\nvar $export = require('./_export');\nvar core = require('./_core');\nvar fails = require('./_fails');\nmodule.exports = function (KEY, exec) {\n var fn = (core.Object || {})[KEY] || Object[KEY];\n var exp = {};\n exp[KEY] = exec(fn);\n $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\n'use strict';\n\nvar canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n\n/**\n * Simple, lightweight module assisting with the detection and context of\n * Worker. Helps avoid circular dependencies and allows code to reason about\n * whether or not they are in a Worker, even if they never include the main\n * `ReactWorker` dependency.\n */\nvar ExecutionEnvironment = {\n\n canUseDOM: canUseDOM,\n\n canUseWorkers: typeof Worker !== 'undefined',\n\n canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),\n\n canUseViewport: canUseDOM && !!window.screen,\n\n isInWorker: !canUseDOM // For now, this is true - might change in the future.\n\n};\n\nmodule.exports = ExecutionEnvironment;","module.exports = { \"default\": require(\"core-js/library/fn/object/values\"), __esModule: true };","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar punycode = require('punycode');\nvar util = require('./util');\n\nexports.parse = urlParse;\nexports.resolve = urlResolve;\nexports.resolveObject = urlResolveObject;\nexports.format = urlFormat;\n\nexports.Url = Url;\n\nfunction Url() {\n this.protocol = null;\n this.slashes = null;\n this.auth = null;\n this.host = null;\n this.port = null;\n this.hostname = null;\n this.hash = null;\n this.search = null;\n this.query = null;\n this.pathname = null;\n this.path = null;\n this.href = null;\n}\n\n// Reference: RFC 3986, RFC 1808, RFC 2396\n\n// define these here so at least they only have to be\n// compiled once on the first module load.\nvar protocolPattern = /^([a-z0-9.+-]+:)/i,\n portPattern = /:[0-9]*$/,\n\n // Special case for a simple path URL\n simplePathPattern = /^(\\/\\/?(?!\\/)[^\\?\\s]*)(\\?[^\\s]*)?$/,\n\n // RFC 2396: characters reserved for delimiting URLs.\n // We actually just auto-escape these.\n delims = ['<', '>', '\"', '`', ' ', '\\r', '\\n', '\\t'],\n\n // RFC 2396: characters not allowed for various reasons.\n unwise = ['{', '}', '|', '\\\\', '^', '`'].concat(delims),\n\n // Allowed by RFCs, but cause of XSS attacks. Always escape these.\n autoEscape = ['\\''].concat(unwise),\n // Characters that are never ever allowed in a hostname.\n // Note that any invalid chars are also handled, but these\n // are the ones that are *expected* to be seen, so we fast-path\n // them.\n nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),\n hostEndingChars = ['/', '?', '#'],\n hostnameMaxLen = 255,\n hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,\n hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,\n // protocols that can allow \"unsafe\" and \"unwise\" chars.\n unsafeProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that never have a hostname.\n hostlessProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that always contain a // bit.\n slashedProtocol = {\n 'http': true,\n 'https': true,\n 'ftp': true,\n 'gopher': true,\n 'file': true,\n 'http:': true,\n 'https:': true,\n 'ftp:': true,\n 'gopher:': true,\n 'file:': true\n },\n querystring = require('querystring');\n\nfunction urlParse(url, parseQueryString, slashesDenoteHost) {\n if (url && util.isObject(url) && url instanceof Url) return url;\n\n var u = new Url;\n u.parse(url, parseQueryString, slashesDenoteHost);\n return u;\n}\n\nUrl.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {\n if (!util.isString(url)) {\n throw new TypeError(\"Parameter 'url' must be a string, not \" + typeof url);\n }\n\n // Copy chrome, IE, opera backslash-handling behavior.\n // Back slashes before the query string get converted to forward slashes\n // See: https://code.google.com/p/chromium/issues/detail?id=25916\n var queryIndex = url.indexOf('?'),\n splitter =\n (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',\n uSplit = url.split(splitter),\n slashRegex = /\\\\/g;\n uSplit[0] = uSplit[0].replace(slashRegex, '/');\n url = uSplit.join(splitter);\n\n var rest = url;\n\n // trim before proceeding.\n // This is to support parse stuff like \" http://foo.com \\n\"\n rest = rest.trim();\n\n if (!slashesDenoteHost && url.split('#').length === 1) {\n // Try fast path regexp\n var simplePath = simplePathPattern.exec(rest);\n if (simplePath) {\n this.path = rest;\n this.href = rest;\n this.pathname = simplePath[1];\n if (simplePath[2]) {\n this.search = simplePath[2];\n if (parseQueryString) {\n this.query = querystring.parse(this.search.substr(1));\n } else {\n this.query = this.search.substr(1);\n }\n } else if (parseQueryString) {\n this.search = '';\n this.query = {};\n }\n return this;\n }\n }\n\n var proto = protocolPattern.exec(rest);\n if (proto) {\n proto = proto[0];\n var lowerProto = proto.toLowerCase();\n this.protocol = lowerProto;\n rest = rest.substr(proto.length);\n }\n\n // figure out if it's got a host\n // user@server is *always* interpreted as a hostname, and url\n // resolution will treat //foo/bar as host=foo,path=bar because that's\n // how the browser resolves relative URLs.\n if (slashesDenoteHost || proto || rest.match(/^\\/\\/[^@\\/]+@[^@\\/]+/)) {\n var slashes = rest.substr(0, 2) === '//';\n if (slashes && !(proto && hostlessProtocol[proto])) {\n rest = rest.substr(2);\n this.slashes = true;\n }\n }\n\n if (!hostlessProtocol[proto] &&\n (slashes || (proto && !slashedProtocol[proto]))) {\n\n // there's a hostname.\n // the first instance of /, ?, ;, or # ends the host.\n //\n // If there is an @ in the hostname, then non-host chars *are* allowed\n // to the left of the last @ sign, unless some host-ending character\n // comes *before* the @-sign.\n // URLs are obnoxious.\n //\n // ex:\n // http://a@b@c/ => user:a@b host:c\n // http://a@b?@c => user:a host:c path:/?@c\n\n // v0.12 TODO(isaacs): This is not quite how Chrome does things.\n // Review our test case against browsers more comprehensively.\n\n // find the first instance of any hostEndingChars\n var hostEnd = -1;\n for (var i = 0; i < hostEndingChars.length; i++) {\n var hec = rest.indexOf(hostEndingChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))\n hostEnd = hec;\n }\n\n // at this point, either we have an explicit point where the\n // auth portion cannot go past, or the last @ char is the decider.\n var auth, atSign;\n if (hostEnd === -1) {\n // atSign can be anywhere.\n atSign = rest.lastIndexOf('@');\n } else {\n // atSign must be in auth portion.\n // http://a@b/c@d => host:b auth:a path:/c@d\n atSign = rest.lastIndexOf('@', hostEnd);\n }\n\n // Now we have a portion which is definitely the auth.\n // Pull that off.\n if (atSign !== -1) {\n auth = rest.slice(0, atSign);\n rest = rest.slice(atSign + 1);\n this.auth = decodeURIComponent(auth);\n }\n\n // the host is the remaining to the left of the first non-host char\n hostEnd = -1;\n for (var i = 0; i < nonHostChars.length; i++) {\n var hec = rest.indexOf(nonHostChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))\n hostEnd = hec;\n }\n // if we still have not hit it, then the entire thing is a host.\n if (hostEnd === -1)\n hostEnd = rest.length;\n\n this.host = rest.slice(0, hostEnd);\n rest = rest.slice(hostEnd);\n\n // pull out port.\n this.parseHost();\n\n // we've indicated that there is a hostname,\n // so even if it's empty, it has to be present.\n this.hostname = this.hostname || '';\n\n // if hostname begins with [ and ends with ]\n // assume that it's an IPv6 address.\n var ipv6Hostname = this.hostname[0] === '[' &&\n this.hostname[this.hostname.length - 1] === ']';\n\n // validate a little.\n if (!ipv6Hostname) {\n var hostparts = this.hostname.split(/\\./);\n for (var i = 0, l = hostparts.length; i < l; i++) {\n var part = hostparts[i];\n if (!part) continue;\n if (!part.match(hostnamePartPattern)) {\n var newpart = '';\n for (var j = 0, k = part.length; j < k; j++) {\n if (part.charCodeAt(j) > 127) {\n // we replace non-ASCII char with a temporary placeholder\n // we need this to make sure size of hostname is not\n // broken by replacing non-ASCII by nothing\n newpart += 'x';\n } else {\n newpart += part[j];\n }\n }\n // we test again with ASCII char only\n if (!newpart.match(hostnamePartPattern)) {\n var validParts = hostparts.slice(0, i);\n var notHost = hostparts.slice(i + 1);\n var bit = part.match(hostnamePartStart);\n if (bit) {\n validParts.push(bit[1]);\n notHost.unshift(bit[2]);\n }\n if (notHost.length) {\n rest = '/' + notHost.join('.') + rest;\n }\n this.hostname = validParts.join('.');\n break;\n }\n }\n }\n }\n\n if (this.hostname.length > hostnameMaxLen) {\n this.hostname = '';\n } else {\n // hostnames are always lower case.\n this.hostname = this.hostname.toLowerCase();\n }\n\n if (!ipv6Hostname) {\n // IDNA Support: Returns a punycoded representation of \"domain\".\n // It only converts parts of the domain name that\n // have non-ASCII characters, i.e. it doesn't matter if\n // you call it with a domain that already is ASCII-only.\n this.hostname = punycode.toASCII(this.hostname);\n }\n\n var p = this.port ? ':' + this.port : '';\n var h = this.hostname || '';\n this.host = h + p;\n this.href += this.host;\n\n // strip [ and ] from the hostname\n // the host field still retains them, though\n if (ipv6Hostname) {\n this.hostname = this.hostname.substr(1, this.hostname.length - 2);\n if (rest[0] !== '/') {\n rest = '/' + rest;\n }\n }\n }\n\n // now rest is set to the post-host stuff.\n // chop off any delim chars.\n if (!unsafeProtocol[lowerProto]) {\n\n // First, make 100% sure that any \"autoEscape\" chars get\n // escaped, even if encodeURIComponent doesn't think they\n // need to be.\n for (var i = 0, l = autoEscape.length; i < l; i++) {\n var ae = autoEscape[i];\n if (rest.indexOf(ae) === -1)\n continue;\n var esc = encodeURIComponent(ae);\n if (esc === ae) {\n esc = escape(ae);\n }\n rest = rest.split(ae).join(esc);\n }\n }\n\n\n // chop off from the tail first.\n var hash = rest.indexOf('#');\n if (hash !== -1) {\n // got a fragment string.\n this.hash = rest.substr(hash);\n rest = rest.slice(0, hash);\n }\n var qm = rest.indexOf('?');\n if (qm !== -1) {\n this.search = rest.substr(qm);\n this.query = rest.substr(qm + 1);\n if (parseQueryString) {\n this.query = querystring.parse(this.query);\n }\n rest = rest.slice(0, qm);\n } else if (parseQueryString) {\n // no query string, but parseQueryString still requested\n this.search = '';\n this.query = {};\n }\n if (rest) this.pathname = rest;\n if (slashedProtocol[lowerProto] &&\n this.hostname && !this.pathname) {\n this.pathname = '/';\n }\n\n //to support http.request\n if (this.pathname || this.search) {\n var p = this.pathname || '';\n var s = this.search || '';\n this.path = p + s;\n }\n\n // finally, reconstruct the href based on what has been validated.\n this.href = this.format();\n return this;\n};\n\n// format a parsed object into a url string\nfunction urlFormat(obj) {\n // ensure it's an object, and not a string url.\n // If it's an obj, this is a no-op.\n // this way, you can call url_format() on strings\n // to clean up potentially wonky urls.\n if (util.isString(obj)) obj = urlParse(obj);\n if (!(obj instanceof Url)) return Url.prototype.format.call(obj);\n return obj.format();\n}\n\nUrl.prototype.format = function() {\n var auth = this.auth || '';\n if (auth) {\n auth = encodeURIComponent(auth);\n auth = auth.replace(/%3A/i, ':');\n auth += '@';\n }\n\n var protocol = this.protocol || '',\n pathname = this.pathname || '',\n hash = this.hash || '',\n host = false,\n query = '';\n\n if (this.host) {\n host = auth + this.host;\n } else if (this.hostname) {\n host = auth + (this.hostname.indexOf(':') === -1 ?\n this.hostname :\n '[' + this.hostname + ']');\n if (this.port) {\n host += ':' + this.port;\n }\n }\n\n if (this.query &&\n util.isObject(this.query) &&\n Object.keys(this.query).length) {\n query = querystring.stringify(this.query);\n }\n\n var search = this.search || (query && ('?' + query)) || '';\n\n if (protocol && protocol.substr(-1) !== ':') protocol += ':';\n\n // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.\n // unless they had them to begin with.\n if (this.slashes ||\n (!protocol || slashedProtocol[protocol]) && host !== false) {\n host = '//' + (host || '');\n if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;\n } else if (!host) {\n host = '';\n }\n\n if (hash && hash.charAt(0) !== '#') hash = '#' + hash;\n if (search && search.charAt(0) !== '?') search = '?' + search;\n\n pathname = pathname.replace(/[?#]/g, function(match) {\n return encodeURIComponent(match);\n });\n search = search.replace('#', '%23');\n\n return protocol + host + pathname + search + hash;\n};\n\nfunction urlResolve(source, relative) {\n return urlParse(source, false, true).resolve(relative);\n}\n\nUrl.prototype.resolve = function(relative) {\n return this.resolveObject(urlParse(relative, false, true)).format();\n};\n\nfunction urlResolveObject(source, relative) {\n if (!source) return relative;\n return urlParse(source, false, true).resolveObject(relative);\n}\n\nUrl.prototype.resolveObject = function(relative) {\n if (util.isString(relative)) {\n var rel = new Url();\n rel.parse(relative, false, true);\n relative = rel;\n }\n\n var result = new Url();\n var tkeys = Object.keys(this);\n for (var tk = 0; tk < tkeys.length; tk++) {\n var tkey = tkeys[tk];\n result[tkey] = this[tkey];\n }\n\n // hash is always overridden, no matter what.\n // even href=\"\" will remove it.\n result.hash = relative.hash;\n\n // if the relative url is empty, then there's nothing left to do here.\n if (relative.href === '') {\n result.href = result.format();\n return result;\n }\n\n // hrefs like //foo/bar always cut to the protocol.\n if (relative.slashes && !relative.protocol) {\n // take everything except the protocol from relative\n var rkeys = Object.keys(relative);\n for (var rk = 0; rk < rkeys.length; rk++) {\n var rkey = rkeys[rk];\n if (rkey !== 'protocol')\n result[rkey] = relative[rkey];\n }\n\n //urlParse appends trailing / to urls like http://www.example.com\n if (slashedProtocol[result.protocol] &&\n result.hostname && !result.pathname) {\n result.path = result.pathname = '/';\n }\n\n result.href = result.format();\n return result;\n }\n\n if (relative.protocol && relative.protocol !== result.protocol) {\n // if it's a known url protocol, then changing\n // the protocol does weird things\n // first, if it's not file:, then we MUST have a host,\n // and if there was a path\n // to begin with, then we MUST have a path.\n // if it is file:, then the host is dropped,\n // because that's known to be hostless.\n // anything else is assumed to be absolute.\n if (!slashedProtocol[relative.protocol]) {\n var keys = Object.keys(relative);\n for (var v = 0; v < keys.length; v++) {\n var k = keys[v];\n result[k] = relative[k];\n }\n result.href = result.format();\n return result;\n }\n\n result.protocol = relative.protocol;\n if (!relative.host && !hostlessProtocol[relative.protocol]) {\n var relPath = (relative.pathname || '').split('/');\n while (relPath.length && !(relative.host = relPath.shift()));\n if (!relative.host) relative.host = '';\n if (!relative.hostname) relative.hostname = '';\n if (relPath[0] !== '') relPath.unshift('');\n if (relPath.length < 2) relPath.unshift('');\n result.pathname = relPath.join('/');\n } else {\n result.pathname = relative.pathname;\n }\n result.search = relative.search;\n result.query = relative.query;\n result.host = relative.host || '';\n result.auth = relative.auth;\n result.hostname = relative.hostname || relative.host;\n result.port = relative.port;\n // to support http.request\n if (result.pathname || result.search) {\n var p = result.pathname || '';\n var s = result.search || '';\n result.path = p + s;\n }\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n }\n\n var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),\n isRelAbs = (\n relative.host ||\n relative.pathname && relative.pathname.charAt(0) === '/'\n ),\n mustEndAbs = (isRelAbs || isSourceAbs ||\n (result.host && relative.pathname)),\n removeAllDots = mustEndAbs,\n srcPath = result.pathname && result.pathname.split('/') || [],\n relPath = relative.pathname && relative.pathname.split('/') || [],\n psychotic = result.protocol && !slashedProtocol[result.protocol];\n\n // if the url is a non-slashed url, then relative\n // links like ../.. should be able\n // to crawl up to the hostname, as well. This is strange.\n // result.protocol has already been set by now.\n // Later on, put the first path part into the host field.\n if (psychotic) {\n result.hostname = '';\n result.port = null;\n if (result.host) {\n if (srcPath[0] === '') srcPath[0] = result.host;\n else srcPath.unshift(result.host);\n }\n result.host = '';\n if (relative.protocol) {\n relative.hostname = null;\n relative.port = null;\n if (relative.host) {\n if (relPath[0] === '') relPath[0] = relative.host;\n else relPath.unshift(relative.host);\n }\n relative.host = null;\n }\n mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');\n }\n\n if (isRelAbs) {\n // it's absolute.\n result.host = (relative.host || relative.host === '') ?\n relative.host : result.host;\n result.hostname = (relative.hostname || relative.hostname === '') ?\n relative.hostname : result.hostname;\n result.search = relative.search;\n result.query = relative.query;\n srcPath = relPath;\n // fall through to the dot-handling below.\n } else if (relPath.length) {\n // it's relative\n // throw away the existing file, and take the new path instead.\n if (!srcPath) srcPath = [];\n srcPath.pop();\n srcPath = srcPath.concat(relPath);\n result.search = relative.search;\n result.query = relative.query;\n } else if (!util.isNullOrUndefined(relative.search)) {\n // just pull out the search.\n // like href='?foo'.\n // Put this after the other two cases because it simplifies the booleans\n if (psychotic) {\n result.hostname = result.host = srcPath.shift();\n //occationaly the auth can get stuck only in host\n //this especially happens in cases like\n //url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n var authInHost = result.host && result.host.indexOf('@') > 0 ?\n result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.host = result.hostname = authInHost.shift();\n }\n }\n result.search = relative.search;\n result.query = relative.query;\n //to support http.request\n if (!util.isNull(result.pathname) || !util.isNull(result.search)) {\n result.path = (result.pathname ? result.pathname : '') +\n (result.search ? result.search : '');\n }\n result.href = result.format();\n return result;\n }\n\n if (!srcPath.length) {\n // no path at all. easy.\n // we've already handled the other stuff above.\n result.pathname = null;\n //to support http.request\n if (result.search) {\n result.path = '/' + result.search;\n } else {\n result.path = null;\n }\n result.href = result.format();\n return result;\n }\n\n // if a url ENDs in . or .., then it must get a trailing slash.\n // however, if it ends in anything else non-slashy,\n // then it must NOT get a trailing slash.\n var last = srcPath.slice(-1)[0];\n var hasTrailingSlash = (\n (result.host || relative.host || srcPath.length > 1) &&\n (last === '.' || last === '..') || last === '');\n\n // strip single dots, resolve double dots to parent dir\n // if the path tries to go above the root, `up` ends up > 0\n var up = 0;\n for (var i = srcPath.length; i >= 0; i--) {\n last = srcPath[i];\n if (last === '.') {\n srcPath.splice(i, 1);\n } else if (last === '..') {\n srcPath.splice(i, 1);\n up++;\n } else if (up) {\n srcPath.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (!mustEndAbs && !removeAllDots) {\n for (; up--; up) {\n srcPath.unshift('..');\n }\n }\n\n if (mustEndAbs && srcPath[0] !== '' &&\n (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {\n srcPath.unshift('');\n }\n\n if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {\n srcPath.push('');\n }\n\n var isAbsolute = srcPath[0] === '' ||\n (srcPath[0] && srcPath[0].charAt(0) === '/');\n\n // put the host back\n if (psychotic) {\n result.hostname = result.host = isAbsolute ? '' :\n srcPath.length ? srcPath.shift() : '';\n //occationaly the auth can get stuck only in host\n //this especially happens in cases like\n //url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n var authInHost = result.host && result.host.indexOf('@') > 0 ?\n result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.host = result.hostname = authInHost.shift();\n }\n }\n\n mustEndAbs = mustEndAbs || (result.host && srcPath.length);\n\n if (mustEndAbs && !isAbsolute) {\n srcPath.unshift('');\n }\n\n if (!srcPath.length) {\n result.pathname = null;\n result.path = null;\n } else {\n result.pathname = srcPath.join('/');\n }\n\n //to support request.http\n if (!util.isNull(result.pathname) || !util.isNull(result.search)) {\n result.path = (result.pathname ? result.pathname : '') +\n (result.search ? result.search : '');\n }\n result.auth = relative.auth || result.auth;\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n};\n\nUrl.prototype.parseHost = function() {\n var host = this.host;\n var port = portPattern.exec(host);\n if (port) {\n port = port[0];\n if (port !== ':') {\n this.port = port.substr(1);\n }\n host = host.substr(0, host.length - port.length);\n }\n if (host) this.hostname = host;\n};\n","'use strict';\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nvar _defineProperty2 = require('babel-runtime/helpers/defineProperty');\n\nvar _defineProperty3 = _interopRequireDefault(_defineProperty2);\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _regenerator = require('babel-runtime/regenerator');\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _promise = require('babel-runtime/core-js/promise');\n\nvar _promise2 = _interopRequireDefault(_promise);\n\nvar _bluebird = require('bluebird');\n\n// Limit the maximum number of ongoing promises returned by fn to LIMIT and\n// use a FIFO queue to handle the backlog.\nvar limitConcurrency = function () {\n var _ref = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee(fn) {\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n if (!(ongoingRequestCount >= LIMIT)) {\n _context.next = 3;\n break;\n }\n\n _context.next = 3;\n return (0, _bluebird.resolve)(new _promise2.default(function (resolve, reject) {\n backlogQueue.push(resolve);\n }));\n\n case 3:\n\n ongoingRequestCount++;\n _context.prev = 4;\n _context.next = 7;\n return (0, _bluebird.resolve)(fn());\n\n case 7:\n return _context.abrupt('return', _context.sent);\n\n case 10:\n _context.prev = 10;\n _context.t0 = _context['catch'](4);\n throw _context.t0;\n\n case 13:\n _context.prev = 13;\n\n ongoingRequestCount--;\n checkBacklog();\n return _context.finish(13);\n\n case 17:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, this, [[4, 10, 13, 17]]);\n }));\n\n return function limitConcurrency(_x) {\n return _ref.apply(this, arguments);\n };\n}();\n\n/**\n * Global store for tracking group summary, members, invited members and rooms.\n */\n\n\nvar _events = require('events');\n\nvar _events2 = _interopRequireDefault(_events);\n\nvar _groups = require('../groups');\n\nvar _FlairStore = require('./FlairStore');\n\nvar _FlairStore2 = _interopRequireDefault(_FlairStore);\n\nvar _MatrixClientPeg = require('../MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nfunction parseMembersResponse(response) {\n return response.chunk.map(function (apiMember) {\n return (0, _groups.groupMemberFromApiObject)(apiMember);\n });\n}\n\nfunction parseRoomsResponse(response) {\n return response.chunk.map(function (apiRoom) {\n return (0, _groups.groupRoomFromApiObject)(apiRoom);\n });\n}\n\n// The number of ongoing group requests\nvar ongoingRequestCount = 0;\n\n// This has arbitrarily been set to a small number to lower the priority\n// of doing group-related requests because we care about other important\n// requests like hitting /sync.\nvar LIMIT = 3; // Maximum number of ongoing group requests\n\n// FIFO queue of functions to call in the backlog\nvar backlogQueue = [\n // () => {...}\n];\n\n// Pull from the FIFO queue\nfunction checkBacklog() {\n var item = backlogQueue.shift();\n if (typeof item === 'function') item();\n}\nvar GroupStore = function (_EventEmitter) {\n (0, _inherits3.default)(GroupStore, _EventEmitter);\n\n function GroupStore() {\n var _this$_fetchResourceP, _this$_resourceFetche;\n\n (0, _classCallCheck3.default)(this, GroupStore);\n\n var _this = (0, _possibleConstructorReturn3.default)(this, (GroupStore.__proto__ || (0, _getPrototypeOf2.default)(GroupStore)).call(this));\n\n _this.STATE_KEY = {\n GroupMembers: 'GroupMembers',\n GroupInvitedMembers: 'GroupInvitedMembers',\n Summary: 'Summary',\n GroupRooms: 'GroupRooms'\n };\n\n _this._state = {};\n _this._state[_this.STATE_KEY.Summary] = {};\n _this._state[_this.STATE_KEY.GroupRooms] = {};\n _this._state[_this.STATE_KEY.GroupMembers] = {};\n _this._state[_this.STATE_KEY.GroupInvitedMembers] = {};\n\n _this._ready = {};\n _this._ready[_this.STATE_KEY.Summary] = {};\n _this._ready[_this.STATE_KEY.GroupRooms] = {};\n _this._ready[_this.STATE_KEY.GroupMembers] = {};\n _this._ready[_this.STATE_KEY.GroupInvitedMembers] = {};\n\n _this._fetchResourcePromise = (_this$_fetchResourceP = {}, (0, _defineProperty3.default)(_this$_fetchResourceP, _this.STATE_KEY.Summary, {}), (0, _defineProperty3.default)(_this$_fetchResourceP, _this.STATE_KEY.GroupRooms, {}), (0, _defineProperty3.default)(_this$_fetchResourceP, _this.STATE_KEY.GroupMembers, {}), (0, _defineProperty3.default)(_this$_fetchResourceP, _this.STATE_KEY.GroupInvitedMembers, {}), _this$_fetchResourceP);\n\n _this._resourceFetcher = (_this$_resourceFetche = {}, (0, _defineProperty3.default)(_this$_resourceFetche, _this.STATE_KEY.Summary, function (groupId) {\n return limitConcurrency(function () {\n return _MatrixClientPeg2.default.get().getGroupSummary(groupId);\n });\n }), (0, _defineProperty3.default)(_this$_resourceFetche, _this.STATE_KEY.GroupRooms, function (groupId) {\n return limitConcurrency(function () {\n return _MatrixClientPeg2.default.get().getGroupRooms(groupId).then(parseRoomsResponse);\n });\n }), (0, _defineProperty3.default)(_this$_resourceFetche, _this.STATE_KEY.GroupMembers, function (groupId) {\n return limitConcurrency(function () {\n return _MatrixClientPeg2.default.get().getGroupUsers(groupId).then(parseMembersResponse);\n });\n }), (0, _defineProperty3.default)(_this$_resourceFetche, _this.STATE_KEY.GroupInvitedMembers, function (groupId) {\n return limitConcurrency(function () {\n return _MatrixClientPeg2.default.get().getGroupInvitedUsers(groupId).then(parseMembersResponse);\n });\n }), _this$_resourceFetche);\n return _this;\n }\n\n (0, _createClass3.default)(GroupStore, [{\n key: '_fetchResource',\n value: function _fetchResource(stateKey, groupId) {\n var _this2 = this;\n\n // Ongoing request, ignore\n if (this._fetchResourcePromise[stateKey][groupId]) return;\n\n var clientPromise = this._resourceFetcher[stateKey](groupId);\n\n // Indicate ongoing request\n this._fetchResourcePromise[stateKey][groupId] = clientPromise;\n\n clientPromise.then(function (result) {\n _this2._state[stateKey][groupId] = result;\n _this2._ready[stateKey][groupId] = true;\n _this2._notifyListeners();\n }).catch(function (err) {\n // Invited users not visible to non-members\n if (stateKey === _this2.STATE_KEY.GroupInvitedMembers && err.httpStatus === 403) {\n return;\n }\n\n console.error('Failed to get resource ' + stateKey + ' for ' + groupId, err);\n _this2.emit('error', err, groupId, stateKey);\n }).finally(function () {\n // Indicate finished request, allow for future fetches\n delete _this2._fetchResourcePromise[stateKey][groupId];\n });\n\n return clientPromise;\n }\n }, {\n key: '_notifyListeners',\n value: function _notifyListeners() {\n this.emit('update');\n }\n\n /**\n * Register a listener to recieve updates from the store. This also\n * immediately triggers an update to send the current state of the\n * store (which could be the initial state).\n *\n * If a group ID is specified, this also causes a fetch of all data\n * of the specified group, which might cause 4 separate HTTP\n * requests, but only if said requests aren't already ongoing.\n *\n * @param {string?} groupId the ID of the group to fetch data for.\n * Optional.\n * @param {function} fn the function to call when the store updates.\n * @return {Object} tok a registration \"token\" with a single\n * property `unregister`, a function that can\n * be called to unregister the listener such\n * that it won't be called any more.\n */\n\n }, {\n key: 'registerListener',\n value: function registerListener(groupId, fn) {\n var _this3 = this;\n\n this.on('update', fn);\n // Call to set initial state (before fetching starts)\n this.emit('update');\n\n if (groupId) {\n this._fetchResource(this.STATE_KEY.Summary, groupId);\n this._fetchResource(this.STATE_KEY.GroupRooms, groupId);\n this._fetchResource(this.STATE_KEY.GroupMembers, groupId);\n this._fetchResource(this.STATE_KEY.GroupInvitedMembers, groupId);\n }\n\n // Similar to the Store of flux/utils, we return a \"token\" that\n // can be used to unregister the listener.\n return {\n unregister: function unregister() {\n _this3.unregisterListener(fn);\n }\n };\n }\n }, {\n key: 'unregisterListener',\n value: function unregisterListener(fn) {\n this.removeListener('update', fn);\n }\n }, {\n key: 'isStateReady',\n value: function isStateReady(groupId, id) {\n return this._ready[id][groupId];\n }\n }, {\n key: 'getGroupIdsForRoomId',\n value: function getGroupIdsForRoomId(roomId) {\n var _this4 = this;\n\n var groupIds = (0, _keys2.default)(this._state[this.STATE_KEY.GroupRooms]);\n return groupIds.filter(function (groupId) {\n var rooms = _this4._state[_this4.STATE_KEY.GroupRooms][groupId] || [];\n return rooms.some(function (room) {\n return room.roomId === roomId;\n });\n });\n }\n }, {\n key: 'getSummary',\n value: function getSummary(groupId) {\n return this._state[this.STATE_KEY.Summary][groupId] || {};\n }\n }, {\n key: 'getGroupRooms',\n value: function getGroupRooms(groupId) {\n return this._state[this.STATE_KEY.GroupRooms][groupId] || [];\n }\n }, {\n key: 'getGroupMembers',\n value: function getGroupMembers(groupId) {\n return this._state[this.STATE_KEY.GroupMembers][groupId] || [];\n }\n }, {\n key: 'getGroupInvitedMembers',\n value: function getGroupInvitedMembers(groupId) {\n return this._state[this.STATE_KEY.GroupInvitedMembers][groupId] || [];\n }\n }, {\n key: 'getGroupPublicity',\n value: function getGroupPublicity(groupId) {\n return (this._state[this.STATE_KEY.Summary][groupId] || {}).user ? (this._state[this.STATE_KEY.Summary][groupId] || {}).user.is_publicised : null;\n }\n }, {\n key: 'isUserPrivileged',\n value: function isUserPrivileged(groupId) {\n return (this._state[this.STATE_KEY.Summary][groupId] || {}).user ? (this._state[this.STATE_KEY.Summary][groupId] || {}).user.is_privileged : null;\n }\n }, {\n key: 'refreshGroupRooms',\n value: function refreshGroupRooms(groupId) {\n return this._fetchResource(this.STATE_KEY.GroupRooms, groupId);\n }\n }, {\n key: 'refreshGroupMembers',\n value: function refreshGroupMembers(groupId) {\n return this._fetchResource(this.STATE_KEY.GroupMembers, groupId);\n }\n }, {\n key: 'addRoomToGroup',\n value: function addRoomToGroup(groupId, roomId, isPublic) {\n return _MatrixClientPeg2.default.get().addRoomToGroup(groupId, roomId, isPublic).then(this._fetchResource.bind(this, this.STATE_KEY.GroupRooms, groupId));\n }\n }, {\n key: 'updateGroupRoomVisibility',\n value: function updateGroupRoomVisibility(groupId, roomId, isPublic) {\n return _MatrixClientPeg2.default.get().updateGroupRoomVisibility(groupId, roomId, isPublic).then(this._fetchResource.bind(this, this.STATE_KEY.GroupRooms, groupId));\n }\n }, {\n key: 'removeRoomFromGroup',\n value: function removeRoomFromGroup(groupId, roomId) {\n return _MatrixClientPeg2.default.get().removeRoomFromGroup(groupId, roomId)\n // Room might be in the summary, refresh just in case\n .then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId)).then(this._fetchResource.bind(this, this.STATE_KEY.GroupRooms, groupId));\n }\n }, {\n key: 'inviteUserToGroup',\n value: function inviteUserToGroup(groupId, userId) {\n return _MatrixClientPeg2.default.get().inviteUserToGroup(groupId, userId).then(this._fetchResource.bind(this, this.STATE_KEY.GroupInvitedMembers, groupId));\n }\n }, {\n key: 'acceptGroupInvite',\n value: function acceptGroupInvite(groupId) {\n return _MatrixClientPeg2.default.get().acceptGroupInvite(groupId)\n // The user should now be able to access (personal) group settings\n .then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId))\n // The user might be able to see more rooms now\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupRooms, groupId))\n // The user should now appear as a member\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupMembers, groupId))\n // The user should now not appear as an invited member\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupInvitedMembers, groupId));\n }\n }, {\n key: 'joinGroup',\n value: function joinGroup(groupId) {\n return _MatrixClientPeg2.default.get().joinGroup(groupId)\n // The user should now be able to access (personal) group settings\n .then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId))\n // The user might be able to see more rooms now\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupRooms, groupId))\n // The user should now appear as a member\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupMembers, groupId))\n // The user should now not appear as an invited member\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupInvitedMembers, groupId));\n }\n }, {\n key: 'leaveGroup',\n value: function leaveGroup(groupId) {\n return _MatrixClientPeg2.default.get().leaveGroup(groupId)\n // The user should now not be able to access group settings\n .then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId))\n // The user might only be able to see a subset of rooms now\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupRooms, groupId))\n // The user should now not appear as a member\n .then(this._fetchResource.bind(this, this.STATE_KEY.GroupMembers, groupId));\n }\n }, {\n key: 'addRoomToGroupSummary',\n value: function addRoomToGroupSummary(groupId, roomId, categoryId) {\n return _MatrixClientPeg2.default.get().addRoomToGroupSummary(groupId, roomId, categoryId).then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId));\n }\n }, {\n key: 'addUserToGroupSummary',\n value: function addUserToGroupSummary(groupId, userId, roleId) {\n return _MatrixClientPeg2.default.get().addUserToGroupSummary(groupId, userId, roleId).then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId));\n }\n }, {\n key: 'removeRoomFromGroupSummary',\n value: function removeRoomFromGroupSummary(groupId, roomId) {\n return _MatrixClientPeg2.default.get().removeRoomFromGroupSummary(groupId, roomId).then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId));\n }\n }, {\n key: 'removeUserFromGroupSummary',\n value: function removeUserFromGroupSummary(groupId, userId) {\n return _MatrixClientPeg2.default.get().removeUserFromGroupSummary(groupId, userId).then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId));\n }\n }, {\n key: 'setGroupPublicity',\n value: function setGroupPublicity(groupId, isPublished) {\n return _MatrixClientPeg2.default.get().setGroupPublicity(groupId, isPublished).then(function () {\n _FlairStore2.default.invalidatePublicisedGroups(_MatrixClientPeg2.default.get().credentials.userId);\n }).then(this._fetchResource.bind(this, this.STATE_KEY.Summary, groupId));\n }\n }]);\n return GroupStore;\n}(_events2.default);\n\nvar singletonGroupStore = null;\nif (!singletonGroupStore) {\n singletonGroupStore = new GroupStore();\n}\nmodule.exports = singletonGroupStore;\n//# sourceMappingURL=GroupStore.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.closest = exports.distance = exports.patch = exports.absolute = exports.negate = exports.isEqual = exports.subtract = exports.add = undefined;\n\nvar _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');\n\nvar _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);\n\nvar _defineProperty2 = require('babel-runtime/helpers/defineProperty');\n\nvar _defineProperty3 = _interopRequireDefault(_defineProperty2);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar add = exports.add = function add(point1, point2) {\n return {\n x: point1.x + point2.x,\n y: point1.y + point2.y\n };\n};\n\nvar subtract = exports.subtract = function subtract(point1, point2) {\n return {\n x: point1.x - point2.x,\n y: point1.y - point2.y\n };\n};\n\nvar isEqual = exports.isEqual = function isEqual(point1, point2) {\n return point1.x === point2.x && point1.y === point2.y;\n};\n\nvar negate = exports.negate = function negate(point) {\n return {\n x: point.x !== 0 ? -point.x : 0,\n y: point.y !== 0 ? -point.y : 0\n };\n};\n\nvar absolute = exports.absolute = function absolute(point) {\n return {\n x: Math.abs(point.x),\n y: Math.abs(point.y)\n };\n};\n\nvar patch = exports.patch = function patch(line, value) {\n var _ref;\n\n var otherValue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;\n return _ref = {}, (0, _defineProperty3.default)(_ref, line, value), (0, _defineProperty3.default)(_ref, line === 'x' ? 'y' : 'x', otherValue), _ref;\n};\n\nvar distance = exports.distance = function distance(point1, point2) {\n return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2));\n};\n\nvar closest = exports.closest = function closest(target, points) {\n return Math.min.apply(Math, (0, _toConsumableArray3.default)(points.map(function (point) {\n return distance(target, point);\n })));\n};","\"use strict\";\n\nvar _classCallCheck2 = require(\"babel-runtime/helpers/classCallCheck\");\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require(\"babel-runtime/helpers/createClass\");\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\nCopyright 2016 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\n * Holds the current Platform object used by the code to do anything\n * specific to the platform we're running on (eg. web, electron)\n * Platforms are provided by the app layer.\n * This allows the app layer to set a Platform without necessarily\n * having to have a MatrixChat object\n */\nvar PlatformPeg = function () {\n function PlatformPeg() {\n (0, _classCallCheck3.default)(this, PlatformPeg);\n\n this.platform = null;\n }\n\n /**\n * Returns the current Platform object for the application.\n * This should be an instance of a class extending BasePlatform.\n */\n\n\n (0, _createClass3.default)(PlatformPeg, [{\n key: \"get\",\n value: function get() {\n return this.platform;\n }\n\n /**\n * Sets the current platform handler object to use for the\n * application.\n * This should be an instance of a class extending BasePlatform.\n */\n\n }, {\n key: \"set\",\n value: function set(plaf) {\n this.platform = plaf;\n }\n }]);\n return PlatformPeg;\n}();\n\nif (!global.mxPlatformPeg) {\n global.mxPlatformPeg = new PlatformPeg();\n}\nmodule.exports = global.mxPlatformPeg;\n//# sourceMappingURL=PlatformPeg.js.map","var dP = require('./_object-dp');\nvar createDesc = require('./_property-desc');\nmodule.exports = require('./_descriptors') ? function (object, key, value) {\n return dP.f(object, key, createDesc(1, value));\n} : function (object, key, value) {\n object[key] = value;\n return object;\n};\n","var global = require('./_global');\nvar hide = require('./_hide');\nvar has = require('./_has');\nvar SRC = require('./_uid')('src');\nvar $toString = require('./_function-to-string');\nvar TO_STRING = 'toString';\nvar TPL = ('' + $toString).split(TO_STRING);\n\nrequire('./_core').inspectSource = function (it) {\n return $toString.call(it);\n};\n\n(module.exports = function (O, key, val, safe) {\n var isFunction = typeof val == 'function';\n if (isFunction) has(val, 'name') || hide(val, 'name', key);\n if (O[key] === val) return;\n if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));\n if (O === global) {\n O[key] = val;\n } else if (!safe) {\n delete O[key];\n hide(O, key, val);\n } else if (O[key]) {\n O[key] = val;\n } else {\n hide(O, key, val);\n }\n// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative\n})(Function.prototype, TO_STRING, function toString() {\n return typeof this == 'function' && this[SRC] || $toString.call(this);\n});\n","var $export = require('./_export');\nvar fails = require('./_fails');\nvar defined = require('./_defined');\nvar quot = /\"/g;\n// B.2.3.2.1 CreateHTML(string, tag, attribute, value)\nvar createHTML = function (string, tag, attribute, value) {\n var S = String(defined(string));\n var p1 = '<' + tag;\n if (attribute !== '') p1 += ' ' + attribute + '=\"' + String(value).replace(quot, '"') + '\"';\n return p1 + '>' + S + '' + tag + '>';\n};\nmodule.exports = function (NAME, exec) {\n var O = {};\n O[NAME] = exec(createHTML);\n $export($export.P + $export.F * fails(function () {\n var test = ''[NAME]('\"');\n return test !== test.toLowerCase() || test.split('\"').length > 3;\n }), 'String', O);\n};\n","module.exports = function (bitmap, value) {\n return {\n enumerable: !(bitmap & 1),\n configurable: !(bitmap & 2),\n writable: !(bitmap & 4),\n value: value\n };\n};\n","module.exports = {};\n","// 19.1.2.14 / 15.2.3.14 Object.keys(O)\nvar $keys = require('./_object-keys-internal');\nvar enumBugKeys = require('./_enum-bug-keys');\n\nmodule.exports = Object.keys || function keys(O) {\n return $keys(O, enumBugKeys);\n};\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.RoomPermalinkCreator = exports.baseUrl = exports.host = undefined;\n\nvar _keys = require(\"babel-runtime/core-js/object/keys\");\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nvar _getIterator2 = require(\"babel-runtime/core-js/get-iterator\");\n\nvar _getIterator3 = _interopRequireDefault(_getIterator2);\n\nvar _slicedToArray2 = require(\"babel-runtime/helpers/slicedToArray\");\n\nvar _slicedToArray3 = _interopRequireDefault(_slicedToArray2);\n\nvar _entries = require(\"babel-runtime/core-js/object/entries\");\n\nvar _entries2 = _interopRequireDefault(_entries);\n\nvar _classCallCheck2 = require(\"babel-runtime/helpers/classCallCheck\");\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require(\"babel-runtime/helpers/createClass\");\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nexports.makeUserPermalink = makeUserPermalink;\nexports.makeRoomPermalink = makeRoomPermalink;\nexports.makeGroupPermalink = makeGroupPermalink;\nexports.encodeServerCandidates = encodeServerCandidates;\n\nvar _MatrixClientPeg = require(\"./MatrixClientPeg\");\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _isIp = require(\"is-ip\");\n\nvar _isIp2 = _interopRequireDefault(_isIp);\n\nvar _utils = require(\"matrix-js-sdk/lib/utils\");\n\nvar _utils2 = _interopRequireDefault(_utils);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar host = exports.host = \"matrix.to\"; /*\n Copyright 2019 New Vector Ltd\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nvar baseUrl = exports.baseUrl = \"https://\" + host;\n\n// The maximum number of servers to pick when working out which servers\n// to add to permalinks. The servers are appended as ?via=example.org\nvar MAX_SERVER_CANDIDATES = 3;\n\n// Permalinks can have servers appended to them so that the user\n// receiving them can have a fighting chance at joining the room.\n// These servers are called \"candidates\" at this point because\n// it is unclear whether they are going to be useful to actually\n// join in the future.\n//\n// We pick 3 servers based on the following criteria:\n//\n// Server 1: The highest power level user in the room, provided\n// they are at least PL 50. We don't calculate \"what is a moderator\"\n// here because it is less relevant for the vast majority of rooms.\n// We also want to ensure that we get an admin or high-ranking mod\n// as they are less likely to leave the room. If no user happens\n// to meet this criteria, we'll pick the most popular server in the\n// room.\n//\n// Server 2: The next most popular server in the room (in user\n// distribution). This cannot be the same as Server 1. If no other\n// servers are available then we'll only return Server 1.\n//\n// Server 3: The next most popular server by user distribution. This\n// has the same rules as Server 2, with the added exception that it\n// must be unique from Server 1 and 2.\n\n// Rationale for popular servers: It's hard to get rid of people when\n// they keep flocking in from a particular server. Sure, the server could\n// be ACL'd in the future or for some reason be evicted from the room\n// however an event like that is unlikely the larger the room gets. If\n// the server is ACL'd at the time of generating the link however, we\n// shouldn't pick them. We also don't pick IP addresses.\n\n// Note: we don't pick the server the room was created on because the\n// homeserver should already be using that server as a last ditch attempt\n// and there's less of a guarantee that the server is a resident server.\n// Instead, we actively figure out which servers are likely to be residents\n// in the future and try to use those.\n\n// Note: Users receiving permalinks that happen to have all 3 potential\n// servers fail them (in terms of joining) are somewhat expected to hunt\n// down the person who gave them the link to ask for a participating server.\n// The receiving user can then manually append the known-good server to\n// the list and magically have the link work.\n\nvar RoomPermalinkCreator = exports.RoomPermalinkCreator = function () {\n // We support being given a roomId as a fallback in the event the `room` object\n // doesn't exist or is not healthy for us to rely on. For example, loading a\n // permalink to a room which the MatrixClient doesn't know about.\n function RoomPermalinkCreator(room) {\n var roomId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n (0, _classCallCheck3.default)(this, RoomPermalinkCreator);\n\n this._room = room;\n this._roomId = room ? room.roomId : roomId;\n this._highestPlUserId = null;\n this._populationMap = null;\n this._bannedHostsRegexps = null;\n this._allowedHostsRegexps = null;\n this._serverCandidates = null;\n this._started = false;\n\n if (!this._roomId) {\n throw new Error(\"Failed to resolve a roomId for the permalink creator to use\");\n }\n\n this.onMembership = this.onMembership.bind(this);\n this.onRoomState = this.onRoomState.bind(this);\n }\n\n (0, _createClass3.default)(RoomPermalinkCreator, [{\n key: \"load\",\n value: function load() {\n if (!this._room || !this._room.currentState) {\n // Under rare and unknown circumstances it is possible to have a room with no\n // currentState, at least potentially at the early stages of joining a room.\n // To avoid breaking everything, we'll just warn rather than throw as well as\n // not bother updating the various aspects of the share link.\n console.warn(\"Tried to load a permalink creator with no room state\");\n return;\n }\n this._updateAllowedServers();\n this._updateHighestPlUser();\n this._updatePopulationMap();\n this._updateServerCandidates();\n }\n }, {\n key: \"start\",\n value: function start() {\n this.load();\n this._room.on(\"RoomMember.membership\", this.onMembership);\n this._room.on(\"RoomState.events\", this.onRoomState);\n this._started = true;\n }\n }, {\n key: \"stop\",\n value: function stop() {\n this._room.removeListener(\"RoomMember.membership\", this.onMembership);\n this._room.removeListener(\"RoomState.events\", this.onRoomState);\n this._started = false;\n }\n }, {\n key: \"isStarted\",\n value: function isStarted() {\n return this._started;\n }\n }, {\n key: \"forEvent\",\n value: function forEvent(eventId) {\n var roomId = this._roomId;\n var permalinkBase = baseUrl + \"/#/\" + roomId + \"/\" + eventId;\n return \"\" + permalinkBase + encodeServerCandidates(this._serverCandidates);\n }\n }, {\n key: \"forRoom\",\n value: function forRoom() {\n var roomId = this._roomId;\n var permalinkBase = baseUrl + \"/#/\" + roomId;\n return \"\" + permalinkBase + encodeServerCandidates(this._serverCandidates);\n }\n }, {\n key: \"onRoomState\",\n value: function onRoomState(event) {\n switch (event.getType()) {\n case \"m.room.server_acl\":\n this._updateAllowedServers();\n this._updateHighestPlUser();\n this._updatePopulationMap();\n this._updateServerCandidates();\n return;\n case \"m.room.power_levels\":\n this._updateHighestPlUser();\n this._updateServerCandidates();\n return;\n }\n }\n }, {\n key: \"onMembership\",\n value: function onMembership(evt, member, oldMembership) {\n var userId = member.userId;\n var membership = member.membership;\n var serverName = getServerName(userId);\n var hasJoined = oldMembership !== \"join\" && membership === \"join\";\n var hasLeft = oldMembership === \"join\" && membership !== \"join\";\n\n if (hasLeft) {\n this._populationMap[serverName]--;\n } else if (hasJoined) {\n this._populationMap[serverName]++;\n }\n\n this._updateHighestPlUser();\n this._updateServerCandidates();\n }\n }, {\n key: \"_updateHighestPlUser\",\n value: function _updateHighestPlUser() {\n var _this = this;\n\n var plEvent = this._room.currentState.getStateEvents(\"m.room.power_levels\", \"\");\n if (plEvent) {\n var content = plEvent.getContent();\n if (content) {\n var users = content.users;\n if (users) {\n var entries = (0, _entries2.default)(users);\n var allowedEntries = entries.filter(function (_ref) {\n var _ref2 = (0, _slicedToArray3.default)(_ref, 1),\n userId = _ref2[0];\n\n var member = _this._room.getMember(userId);\n if (!member || member.membership !== \"join\") {\n return false;\n }\n var serverName = getServerName(userId);\n return !isHostnameIpAddress(serverName) && !isHostInRegex(serverName, _this._bannedHostsRegexps) && isHostInRegex(serverName, _this._allowedHostsRegexps);\n });\n var maxEntry = allowedEntries.reduce(function (max, entry) {\n return entry[1] > max[1] ? entry : max;\n }, [null, 0]);\n\n var _maxEntry = (0, _slicedToArray3.default)(maxEntry, 2),\n userId = _maxEntry[0],\n powerLevel = _maxEntry[1];\n // object wasn't empty, and max entry wasn't a demotion from the default\n\n\n if (userId !== null && powerLevel >= 50) {\n this._highestPlUserId = userId;\n return;\n }\n }\n }\n }\n this._highestPlUserId = null;\n }\n }, {\n key: \"_updateAllowedServers\",\n value: function _updateAllowedServers() {\n var bannedHostsRegexps = [];\n var allowedHostsRegexps = [new RegExp(\".*\")]; // default allow everyone\n if (this._room.currentState) {\n var aclEvent = this._room.currentState.getStateEvents(\"m.room.server_acl\", \"\");\n if (aclEvent && aclEvent.getContent()) {\n var getRegex = function getRegex(hostname) {\n return new RegExp(\"^\" + _utils2.default.globToRegexp(hostname, false) + \"$\");\n };\n\n var denied = aclEvent.getContent().deny || [];\n denied.forEach(function (h) {\n return bannedHostsRegexps.push(getRegex(h));\n });\n\n var allowed = aclEvent.getContent().allow || [];\n allowedHostsRegexps = []; // we don't want to use the default rule here\n allowed.forEach(function (h) {\n return allowedHostsRegexps.push(getRegex(h));\n });\n }\n }\n this._bannedHostsRegexps = bannedHostsRegexps;\n this._allowedHostsRegexps = allowedHostsRegexps;\n }\n }, {\n key: \"_updatePopulationMap\",\n value: function _updatePopulationMap() {\n var populationMap = {};\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = (0, _getIterator3.default)(this._room.getJoinedMembers()), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var member = _step.value;\n\n var serverName = getServerName(member.userId);\n if (!populationMap[serverName]) {\n populationMap[serverName] = 0;\n }\n populationMap[serverName]++;\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n this._populationMap = populationMap;\n }\n }, {\n key: \"_updateServerCandidates\",\n value: function _updateServerCandidates() {\n var _this2 = this;\n\n var candidates = [];\n if (this._highestPlUserId) {\n candidates.push(getServerName(this._highestPlUserId));\n }\n\n var serversByPopulation = (0, _keys2.default)(this._populationMap).sort(function (a, b) {\n return _this2._populationMap[b] - _this2._populationMap[a];\n }).filter(function (a) {\n return !candidates.includes(a) && !isHostnameIpAddress(a) && !isHostInRegex(a, _this2._bannedHostsRegexps) && isHostInRegex(a, _this2._allowedHostsRegexps);\n });\n\n var remainingServers = serversByPopulation.slice(0, MAX_SERVER_CANDIDATES - candidates.length);\n candidates = candidates.concat(remainingServers);\n\n this._serverCandidates = candidates;\n }\n }]);\n return RoomPermalinkCreator;\n}();\n\nfunction makeUserPermalink(userId) {\n return baseUrl + \"/#/\" + userId;\n}\n\nfunction makeRoomPermalink(roomId) {\n var permalinkBase = baseUrl + \"/#/\" + roomId;\n\n if (!roomId) {\n throw new Error(\"can't permalink a falsey roomId\");\n }\n\n // If the roomId isn't actually a room ID, don't try to list the servers.\n // Aliases are already routable, and don't need extra information.\n if (roomId[0] !== '!') return permalinkBase;\n\n var client = _MatrixClientPeg2.default.get();\n var room = client.getRoom(roomId);\n if (!room) {\n return permalinkBase;\n }\n var permalinkCreator = new RoomPermalinkCreator(room);\n permalinkCreator.load();\n return permalinkCreator.forRoom();\n}\n\nfunction makeGroupPermalink(groupId) {\n return baseUrl + \"/#/\" + groupId;\n}\n\nfunction encodeServerCandidates(candidates) {\n if (!candidates || candidates.length === 0) return '';\n return \"?via=\" + candidates.map(function (c) {\n return encodeURIComponent(c);\n }).join(\"&via=\");\n}\n\nfunction getServerName(userId) {\n return userId.split(\":\").splice(1).join(\":\");\n}\n\nfunction getHostnameFromMatrixDomain(domain) {\n if (!domain) return null;\n return new URL(\"https://\" + domain).hostname;\n}\n\nfunction isHostInRegex(hostname, regexps) {\n hostname = getHostnameFromMatrixDomain(hostname);\n if (!hostname) return true; // assumed\n if (regexps.length > 0 && !regexps[0].test) throw new Error(regexps[0]);\n\n return regexps.filter(function (h) {\n return h.test(hostname);\n }).length > 0;\n}\n\nfunction isHostnameIpAddress(hostname) {\n hostname = getHostnameFromMatrixDomain(hostname);\n if (!hostname) return false;\n\n // is-ip doesn't want IPv6 addresses surrounded by brackets, so\n // take them off.\n if (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n hostname = hostname.substring(1, hostname.length - 1);\n }\n\n return (0, _isIp2.default)(hostname);\n}\n//# sourceMappingURL=matrix-to.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.isOnlyCtrlOrCmdKeyEvent = isOnlyCtrlOrCmdKeyEvent;\nexports.isOnlyCtrlOrCmdIgnoreShiftKeyEvent = isOnlyCtrlOrCmdIgnoreShiftKeyEvent;\n/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/* a selection of key codes, as used in KeyboardEvent.keyCode */\nvar KeyCode = exports.KeyCode = {\n BACKSPACE: 8,\n TAB: 9,\n ENTER: 13,\n SHIFT: 16,\n ESCAPE: 27,\n SPACE: 32,\n PAGE_UP: 33,\n PAGE_DOWN: 34,\n END: 35,\n HOME: 36,\n LEFT: 37,\n UP: 38,\n RIGHT: 39,\n DOWN: 40,\n DELETE: 46,\n KEY_A: 65,\n KEY_B: 66,\n KEY_C: 67,\n KEY_D: 68,\n KEY_E: 69,\n KEY_F: 70,\n KEY_G: 71,\n KEY_H: 72,\n KEY_I: 73,\n KEY_J: 74,\n KEY_K: 75,\n KEY_L: 76,\n KEY_M: 77,\n KEY_N: 78,\n KEY_O: 79,\n KEY_P: 80,\n KEY_Q: 81,\n KEY_R: 82,\n KEY_S: 83,\n KEY_T: 84,\n KEY_U: 85,\n KEY_V: 86,\n KEY_W: 87,\n KEY_X: 88,\n KEY_Y: 89,\n KEY_Z: 90\n};\n\nfunction isOnlyCtrlOrCmdKeyEvent(ev) {\n var isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;\n if (isMac) {\n return ev.metaKey && !ev.altKey && !ev.ctrlKey && !ev.shiftKey;\n } else {\n return ev.ctrlKey && !ev.altKey && !ev.metaKey && !ev.shiftKey;\n }\n}\n\nfunction isOnlyCtrlOrCmdIgnoreShiftKeyEvent(ev) {\n var isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;\n if (isMac) {\n return ev.metaKey && !ev.altKey && !ev.ctrlKey;\n } else {\n return ev.ctrlKey && !ev.altKey && !ev.metaKey;\n }\n}\n//# sourceMappingURL=Keyboard.js.map","\n\nvar simpleIsEqual = function simpleIsEqual(a, b) {\n return a === b;\n};\n\nexport default function (resultFn) {\n var isEqual = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : simpleIsEqual;\n\n var lastThis = void 0;\n var lastArgs = [];\n var lastResult = void 0;\n var calledOnce = false;\n\n var isNewArgEqualToLast = function isNewArgEqualToLast(newArg, index) {\n return isEqual(newArg, lastArgs[index]);\n };\n\n var result = function result() {\n for (var _len = arguments.length, newArgs = Array(_len), _key = 0; _key < _len; _key++) {\n newArgs[_key] = arguments[_key];\n }\n\n if (calledOnce && lastThis === this && newArgs.length === lastArgs.length && newArgs.every(isNewArgEqualToLast)) {\n return lastResult;\n }\n\n calledOnce = true;\n lastThis = this;\n lastArgs = newArgs;\n lastResult = resultFn.apply(this, newArgs);\n return lastResult;\n };\n\n return result;\n}","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');\n\nvar _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);\n\nvar _regenerator = require('babel-runtime/regenerator');\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _bluebird = require('bluebird');\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _react = require('react');\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _propTypes = require('prop-types');\n\nvar _propTypes2 = _interopRequireDefault(_propTypes);\n\nvar _classnames = require('classnames');\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar _index = require('../../../index');\n\nvar _index2 = _interopRequireDefault(_index);\n\nvar _lodash = require('lodash');\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// Invoke validation from user input (when typing, etc.) at most once every N ms.\nvar VALIDATION_THROTTLE_MS = 200; /*\n Copyright 2019 New Vector Ltd\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nvar Field = function (_React$PureComponent) {\n (0, _inherits3.default)(Field, _React$PureComponent);\n\n function Field() {\n (0, _classCallCheck3.default)(this, Field);\n\n var _this = (0, _possibleConstructorReturn3.default)(this, (Field.__proto__ || (0, _getPrototypeOf2.default)(Field)).call(this));\n\n _this.onFocus = function (ev) {\n _this.validate({\n focused: true\n });\n // Parent component may have supplied its own `onFocus` as well\n if (_this.props.onFocus) {\n _this.props.onFocus(ev);\n }\n };\n\n _this.onChange = function (ev) {\n _this.validateOnChange();\n // Parent component may have supplied its own `onChange` as well\n if (_this.props.onChange) {\n _this.props.onChange(ev);\n }\n };\n\n _this.onBlur = function (ev) {\n _this.validate({\n focused: false\n });\n // Parent component may have supplied its own `onBlur` as well\n if (_this.props.onBlur) {\n _this.props.onBlur(ev);\n }\n };\n\n _this.validateOnChange = (0, _lodash.throttle)(function () {\n _this.validate({\n focused: true\n });\n }, VALIDATION_THROTTLE_MS);\n\n _this.state = {\n valid: undefined,\n feedback: undefined\n };\n return _this;\n }\n\n (0, _createClass3.default)(Field, [{\n key: 'focus',\n value: function focus() {\n this.input.focus();\n }\n }, {\n key: 'validate',\n value: function () {\n var _ref = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee(_ref2) {\n var focused = _ref2.focused,\n _ref2$allowEmpty = _ref2.allowEmpty,\n allowEmpty = _ref2$allowEmpty === undefined ? true : _ref2$allowEmpty;\n\n var value, _ref3, valid, feedback;\n\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n if (this.props.onValidate) {\n _context.next = 2;\n break;\n }\n\n return _context.abrupt('return');\n\n case 2:\n value = this.input ? this.input.value : null;\n _context.next = 5;\n return (0, _bluebird.resolve)(this.props.onValidate({\n value: value,\n focused: focused,\n allowEmpty: allowEmpty\n }));\n\n case 5:\n _ref3 = _context.sent;\n valid = _ref3.valid;\n feedback = _ref3.feedback;\n\n\n if (feedback) {\n this.setState({\n valid: valid,\n feedback: feedback,\n feedbackVisible: true\n });\n } else {\n // When we receive null `feedback`, we want to hide the tooltip.\n // We leave the previous `feedback` content in state without updating it,\n // so that we can hide the tooltip containing the most recent feedback\n // via CSS animation.\n this.setState({\n valid: valid,\n feedbackVisible: false\n });\n }\n\n case 9:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, this);\n }));\n\n function validate(_x) {\n return _ref.apply(this, arguments);\n }\n\n return validate;\n }()\n }, {\n key: 'render',\n value: function render() {\n var _this2 = this;\n\n var _props = this.props,\n element = _props.element,\n prefix = _props.prefix,\n onValidate = _props.onValidate,\n children = _props.children,\n inputProps = (0, _objectWithoutProperties3.default)(_props, ['element', 'prefix', 'onValidate', 'children']);\n\n\n var inputElement = element || \"input\";\n\n // Set some defaults for the element\n inputProps.type = inputProps.type || \"text\";\n inputProps.ref = function (input) {\n return _this2.input = input;\n };\n inputProps.placeholder = inputProps.placeholder || inputProps.label;\n\n inputProps.onFocus = this.onFocus;\n inputProps.onChange = this.onChange;\n inputProps.onBlur = this.onBlur;\n\n var fieldInput = _react2.default.createElement(inputElement, inputProps, children);\n\n var prefixContainer = null;\n if (prefix) {\n prefixContainer = _react2.default.createElement(\n 'span',\n { className: 'mx_Field_prefix' },\n prefix\n );\n }\n\n var fieldClasses = (0, _classnames2.default)(\"mx_Field\", 'mx_Field_' + inputElement, {\n // If we have a prefix element, leave the label always at the top left and\n // don't animate it, as it looks a bit clunky and would add complexity to do\n // properly.\n mx_Field_labelAlwaysTopLeft: prefix,\n mx_Field_valid: onValidate && this.state.valid === true,\n mx_Field_invalid: onValidate && this.state.valid === false\n });\n\n // Handle displaying feedback on validity\n var Tooltip = _index2.default.getComponent(\"elements.Tooltip\");\n var tooltip = void 0;\n if (this.state.feedback) {\n tooltip = _react2.default.createElement(Tooltip, {\n tooltipClassName: 'mx_Field_tooltip',\n visible: this.state.feedbackVisible,\n label: this.state.feedback\n });\n }\n\n return _react2.default.createElement(\n 'div',\n { className: fieldClasses },\n prefixContainer,\n fieldInput,\n _react2.default.createElement(\n 'label',\n { htmlFor: this.props.id },\n this.props.label\n ),\n tooltip\n );\n }\n }]);\n return Field;\n}(_react2.default.PureComponent);\n\nField.propTypes = {\n // The field's ID, which binds the input and label together.\n id: _propTypes2.default.string.isRequired,\n // The element to create. Defaults to \"input\".\n // To define options for a select, use \n element: _propTypes2.default.oneOf([\"input\", \"select\", \"textarea\"]),\n // The field's type (when used as an ). Defaults to \"text\".\n type: _propTypes2.default.string,\n // The field's label string.\n label: _propTypes2.default.string,\n // The field's placeholder string. Defaults to the label.\n placeholder: _propTypes2.default.string,\n // The field's value.\n // This is a controlled component, so the value is required.\n value: _propTypes2.default.string.isRequired,\n // Optional component to include inside the field before the input.\n prefix: _propTypes2.default.node,\n // The callback called whenever the contents of the field\n // changes. Returns an object with `valid` boolean field\n // and a `feedback` react component field to provide feedback\n // to the user.\n onValidate: _propTypes2.default.func\n // All other props pass through to the .\n};\nexports.default = Field;\nmodule.exports = exports['default'];\n//# sourceMappingURL=Field.js.map","var hasOwnProperty = {}.hasOwnProperty;\nmodule.exports = function (it, key) {\n return hasOwnProperty.call(it, key);\n};\n","// to indexed object, toObject with fallback for non-array-like ES3 strings\nvar IObject = require('./_iobject');\nvar defined = require('./_defined');\nmodule.exports = function (it) {\n return IObject(defined(it));\n};\n","var pIE = require('./_object-pie');\nvar createDesc = require('./_property-desc');\nvar toIObject = require('./_to-iobject');\nvar toPrimitive = require('./_to-primitive');\nvar has = require('./_has');\nvar IE8_DOM_DEFINE = require('./_ie8-dom-define');\nvar gOPD = Object.getOwnPropertyDescriptor;\n\nexports.f = require('./_descriptors') ? gOPD : function getOwnPropertyDescriptor(O, P) {\n O = toIObject(O);\n P = toPrimitive(P, true);\n if (IE8_DOM_DEFINE) try {\n return gOPD(O, P);\n } catch (e) { /* empty */ }\n if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);\n};\n","// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)\nvar has = require('./_has');\nvar toObject = require('./_to-object');\nvar IE_PROTO = require('./_shared-key')('IE_PROTO');\nvar ObjectProto = Object.prototype;\n\nmodule.exports = Object.getPrototypeOf || function (O) {\n O = toObject(O);\n if (has(O, IE_PROTO)) return O[IE_PROTO];\n if (typeof O.constructor == 'function' && O instanceof O.constructor) {\n return O.constructor.prototype;\n } return O instanceof Object ? ObjectProto : null;\n};\n","'use strict';\nvar $at = require('./_string-at')(true);\n\n// 21.1.3.27 String.prototype[@@iterator]()\nrequire('./_iter-define')(String, 'String', function (iterated) {\n this._t = String(iterated); // target\n this._i = 0; // next index\n// 21.1.5.2.1 %StringIteratorPrototype%.next()\n}, function () {\n var O = this._t;\n var index = this._i;\n var point;\n if (index >= O.length) return { value: undefined, done: true };\n point = $at(O, index);\n this._i += point.length;\n return { value: point, done: false };\n});\n","module.exports = true;\n","// 7.1.13 ToObject(argument)\nvar defined = require('./_defined');\nmodule.exports = function (it) {\n return Object(defined(it));\n};\n","/**\n * Copyright (c) 2016-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * \n */\n\n'use strict';\n\n// Trust the developer to only use ReactInstrumentation with a __DEV__ check\n\nvar debugTool = null;\n\nif (process.env.NODE_ENV !== 'production') {\n var ReactDebugTool = require('./ReactDebugTool');\n debugTool = ReactDebugTool;\n}\n\nmodule.exports = { debugTool: debugTool };","\"use strict\";\n\n/*\nCopyright 2018 André Jaenisch\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module logger\n */\nvar log = require(\"loglevel\");\n\n// This is to demonstrate, that you can use any namespace you want.\n// Namespaces allow you to turn on/off the logging for specific parts of the\n// application.\n// An idea would be to control this via an environment variable (on Node.js).\n// See https://www.npmjs.com/package/debug to see how this could be implemented\n// Part of #332 is introducing a logging library in the first place.\nvar DEFAULT_NAME_SPACE = \"matrix\";\nvar logger = log.getLogger(DEFAULT_NAME_SPACE);\nlogger.setLevel(log.levels.DEBUG);\n\n/**\n * Drop-in replacement for console
using {@link https://www.npmjs.com/package/loglevel|loglevel}.\n * Can be tailored down to specific use cases if needed.\n*/\nmodule.exports = logger;\n//# sourceMappingURL=logger.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.formatCount = formatCount;\nexports.formatCryptoKey = formatCryptoKey;\nexports.hashCode = hashCode;\nexports.getUserNameColorClass = getUserNameColorClass;\nexports.formatCommaSeparatedList = formatCommaSeparatedList;\n\nvar _languageHandler = require(\"../languageHandler\");\n\n/**\n * formats numbers to fit into ~3 characters, suitable for badge counts\n * e.g: 999, 9.9K, 99K, 0.9M, 9.9M, 99M, 0.9B, 9.9B\n */\nfunction formatCount(count) {\n if (count < 1000) return count;\n if (count < 10000) return (count / 1000).toFixed(1) + \"K\";\n if (count < 100000) return (count / 1000).toFixed(0) + \"K\";\n if (count < 10000000) return (count / 1000000).toFixed(1) + \"M\";\n if (count < 100000000) return (count / 1000000).toFixed(0) + \"M\";\n return (count / 1000000000).toFixed(1) + \"B\"; // 10B is enough for anyone, right? :S\n}\n\n/**\n * format a key into groups of 4 characters, for easier visual inspection\n *\n * @param {string} key key to format\n *\n * @return {string}\n */\n/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nfunction formatCryptoKey(key) {\n return key.match(/.{1,4}/g).join(\" \");\n}\n/**\n * calculates a numeric hash for a given string\n *\n * @param {string} str string to hash\n *\n * @return {number}\n */\nfunction hashCode(str) {\n var hash = 0;\n var i = void 0;\n var chr = void 0;\n if (str.length === 0) {\n return hash;\n }\n for (i = 0; i < str.length; i++) {\n chr = str.charCodeAt(i);\n hash = (hash << 5) - hash + chr;\n hash |= 0;\n }\n return Math.abs(hash);\n}\n\nfunction getUserNameColorClass(userId) {\n var colorNumber = hashCode(userId) % 8 + 1;\n return \"mx_Username_color\" + colorNumber;\n}\n\n/**\n * Constructs a written English string representing `items`, with an optional\n * limit on the number of items included in the result. If specified and if the\n * length of `items` is greater than the limit, the string \"and n others\" will\n * be appended onto the result. If `items` is empty, returns the empty string.\n * If there is only one item, return it.\n * @param {string[]} items the items to construct a string from.\n * @param {number?} itemLimit the number by which to limit the list.\n * @returns {string} a string constructed by joining `items` with a comma\n * between each item, but with the last item appended as \" and [lastItem]\".\n */\nfunction formatCommaSeparatedList(items, itemLimit) {\n var remaining = itemLimit === undefined ? 0 : Math.max(items.length - itemLimit, 0);\n if (items.length === 0) {\n return \"\";\n } else if (items.length === 1) {\n return items[0];\n } else if (remaining > 0) {\n items = items.slice(0, itemLimit);\n return (0, _languageHandler._t)(\"%(items)s and %(count)s others\", { items: items.join(', '), count: remaining });\n } else {\n var lastItem = items.pop();\n return (0, _languageHandler._t)(\"%(items)s and %(lastItem)s\", { items: items.join(', '), lastItem: lastItem });\n }\n}\n//# sourceMappingURL=FormattingUtils.js.map","'use strict';\n\nvar _stringify = require('babel-runtime/core-js/json/stringify');\n\nvar _stringify2 = _interopRequireDefault(_stringify);\n\nvar _assign = require('babel-runtime/core-js/object/assign');\n\nvar _assign2 = _interopRequireDefault(_assign);\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _dispatcher = require('../dispatcher');\n\nvar _dispatcher2 = _interopRequireDefault(_dispatcher);\n\nvar _utils = require('flux/utils');\n\nvar _MatrixClientPeg = require('../MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _index = require('../index');\n\nvar _index2 = _interopRequireDefault(_index);\n\nvar _Modal = require('../Modal');\n\nvar _Modal2 = _interopRequireDefault(_Modal);\n\nvar _languageHandler = require('../languageHandler');\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\nCopyright 2017 Vector Creations Ltd\nCopyright 2017, 2018 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nvar INITIAL_STATE = {\n // Whether we're joining the currently viewed room (see isJoining())\n joining: false,\n // Any error that has occurred during joining\n joinError: null,\n // The room ID of the room currently being viewed\n roomId: null,\n\n // The event to scroll to when the room is first viewed\n initialEventId: null,\n // Whether to highlight the initial event\n isInitialEventHighlighted: false,\n\n // The room alias of the room (or null if not originally specified in view_room)\n roomAlias: null,\n // Whether the current room is loading\n roomLoading: false,\n // Any error that has occurred during loading\n roomLoadError: null,\n\n forwardingEvent: null,\n\n quotingEvent: null\n};\n\n/**\n * A class for storing application state for RoomView. This is the RoomView's interface\n* with a subset of the js-sdk.\n * ```\n */\n\nvar RoomViewStore = function (_Store) {\n (0, _inherits3.default)(RoomViewStore, _Store);\n\n function RoomViewStore() {\n (0, _classCallCheck3.default)(this, RoomViewStore);\n\n // Initialise state\n var _this = (0, _possibleConstructorReturn3.default)(this, (RoomViewStore.__proto__ || (0, _getPrototypeOf2.default)(RoomViewStore)).call(this, _dispatcher2.default));\n\n _this._state = INITIAL_STATE;\n return _this;\n }\n\n (0, _createClass3.default)(RoomViewStore, [{\n key: '_setState',\n value: function _setState(newState) {\n this._state = (0, _assign2.default)(this._state, newState);\n this.__emitChange();\n }\n }, {\n key: '__onDispatch',\n value: function __onDispatch(payload) {\n switch (payload.action) {\n // view_room:\n // - room_alias: '#somealias:matrix.org'\n // - room_id: '!roomid123:matrix.org'\n // - event_id: '$213456782:matrix.org'\n // - event_offset: 100\n // - highlighted: true\n case 'view_room':\n this._viewRoom(payload);\n break;\n case 'view_my_groups':\n case 'view_group':\n this._setState({\n roomId: null,\n roomAlias: null\n });\n break;\n case 'view_room_error':\n this._viewRoomError(payload);\n break;\n case 'will_join':\n this._setState({\n joining: true\n });\n break;\n case 'cancel_join':\n this._setState({\n joining: false\n });\n break;\n // join_room:\n // - opts: options for joinRoom\n case 'join_room':\n this._joinRoom(payload);\n break;\n case 'join_room_error':\n this._joinRoomError(payload);\n break;\n case 'on_logged_out':\n this.reset();\n break;\n case 'forward_event':\n this._setState({\n forwardingEvent: payload.event\n });\n break;\n case 'reply_to_event':\n this._setState({\n replyingToEvent: payload.event\n });\n break;\n case 'open_room_settings':\n {\n var RoomSettingsDialog = _index2.default.getComponent(\"dialogs.RoomSettingsDialog\");\n _Modal2.default.createTrackedDialog('Room settings', '', RoomSettingsDialog, {\n roomId: payload.room_id || this._state.roomId\n }, /*className=*/null, /*isPriority=*/false, /*isStatic=*/true);\n break;\n }\n }\n }\n }, {\n key: '_viewRoom',\n value: function _viewRoom(payload) {\n if (payload.room_id) {\n var newState = {\n roomId: payload.room_id,\n roomAlias: payload.room_alias,\n initialEventId: payload.event_id,\n isInitialEventHighlighted: payload.highlighted,\n forwardingEvent: null,\n roomLoading: false,\n roomLoadError: null,\n // should peek by default\n shouldPeek: payload.should_peek === undefined ? true : payload.should_peek,\n // have we sent a join request for this room and are waiting for a response?\n joining: payload.joining || false,\n // Reset replyingToEvent because we don't want cross-room because bad UX\n replyingToEvent: null,\n // pull the user out of Room Settings\n isEditingSettings: false\n };\n\n if (this._state.forwardingEvent) {\n _dispatcher2.default.dispatch({\n action: 'send_event',\n room_id: newState.roomId,\n event: this._state.forwardingEvent\n });\n }\n\n this._setState(newState);\n\n if (payload.auto_join) {\n this._joinRoom(payload);\n }\n } else if (payload.room_alias) {\n // Resolve the alias and then do a second dispatch with the room ID acquired\n this._setState({\n roomId: null,\n initialEventId: null,\n initialEventPixelOffset: null,\n isInitialEventHighlighted: null,\n roomAlias: payload.room_alias,\n roomLoading: true,\n roomLoadError: null\n });\n _MatrixClientPeg2.default.get().getRoomIdForAlias(payload.room_alias).done(function (result) {\n _dispatcher2.default.dispatch({\n action: 'view_room',\n room_id: result.room_id,\n event_id: payload.event_id,\n highlighted: payload.highlighted,\n room_alias: payload.room_alias,\n auto_join: payload.auto_join,\n oob_data: payload.oob_data\n });\n }, function (err) {\n _dispatcher2.default.dispatch({\n action: 'view_room_error',\n room_id: null,\n room_alias: payload.room_alias,\n err: err\n });\n });\n }\n }\n }, {\n key: '_viewRoomError',\n value: function _viewRoomError(payload) {\n this._setState({\n roomId: payload.room_id,\n roomAlias: payload.room_alias,\n roomLoading: false,\n roomLoadError: payload.err\n });\n }\n }, {\n key: '_joinRoom',\n value: function _joinRoom(payload) {\n this._setState({\n joining: true\n });\n _MatrixClientPeg2.default.get().joinRoom(this._state.roomAlias || this._state.roomId, payload.opts).done(function () {\n // We don't actually need to do anything here: we do *not*\n // clear the 'joining' flag because the Room object and/or\n // our 'joined' member event may not have come down the sync\n // stream yet, and that's the point at which we'd consider\n // the user joined to the room.\n }, function (err) {\n _dispatcher2.default.dispatch({\n action: 'join_room_error',\n err: err\n });\n var msg = err.message ? err.message : (0, _stringify2.default)(err);\n // XXX: We are relying on the error message returned by browsers here.\n // This isn't great, but it does generalize the error being shown to users.\n if (msg && msg.startsWith(\"CORS request rejected\")) {\n msg = (0, _languageHandler._t)(\"There was an error joining the room\");\n }\n if (err.errcode === 'M_INCOMPATIBLE_ROOM_VERSION') {\n msg = React.createElement(\n 'div',\n null,\n (0, _languageHandler._t)(\"Sorry, your homeserver is too old to participate in this room.\"),\n React.createElement('br', null),\n (0, _languageHandler._t)(\"Please contact your homeserver administrator.\")\n );\n }\n var ErrorDialog = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n _Modal2.default.createTrackedDialog('Failed to join room', '', ErrorDialog, {\n title: (0, _languageHandler._t)(\"Failed to join room\"),\n description: msg\n });\n });\n }\n }, {\n key: '_joinRoomError',\n value: function _joinRoomError(payload) {\n this._setState({\n joining: false,\n joinError: payload.err\n });\n }\n }, {\n key: 'reset',\n value: function reset() {\n this._state = (0, _assign2.default)({}, INITIAL_STATE);\n }\n\n // The room ID of the room currently being viewed\n\n }, {\n key: 'getRoomId',\n value: function getRoomId() {\n return this._state.roomId;\n }\n\n // The event to scroll to when the room is first viewed\n\n }, {\n key: 'getInitialEventId',\n value: function getInitialEventId() {\n return this._state.initialEventId;\n }\n\n // Whether to highlight the initial event\n\n }, {\n key: 'isInitialEventHighlighted',\n value: function isInitialEventHighlighted() {\n return this._state.isInitialEventHighlighted;\n }\n\n // The room alias of the room (or null if not originally specified in view_room)\n\n }, {\n key: 'getRoomAlias',\n value: function getRoomAlias() {\n return this._state.roomAlias;\n }\n\n // Whether the current room is loading (true whilst resolving an alias)\n\n }, {\n key: 'isRoomLoading',\n value: function isRoomLoading() {\n return this._state.roomLoading;\n }\n\n // Any error that has occurred during loading\n\n }, {\n key: 'getRoomLoadError',\n value: function getRoomLoadError() {\n return this._state.roomLoadError;\n }\n\n // True if we're expecting the user to be joined to the room currently being\n // viewed. Note that this is left true after the join request has finished,\n // since we should still consider a join to be in progress until the room\n // & member events come down the sync.\n //\n // This flag remains true after the room has been sucessfully joined,\n // (this store doesn't listen for the appropriate member events)\n // so you should always observe the joined state from the member event\n // if a room object is present.\n // ie. The correct logic is:\n // if (room) {\n // if (myMember.membership == 'joined') {\n // // user is joined to the room\n // } else {\n // // Not joined\n // }\n // } else {\n // if (RoomViewStore.isJoining()) {\n // // show spinner\n // } else {\n // // show join prompt\n // }\n // }\n\n }, {\n key: 'isJoining',\n value: function isJoining() {\n return this._state.joining;\n }\n\n // Any error that has occurred during joining\n\n }, {\n key: 'getJoinError',\n value: function getJoinError() {\n return this._state.joinError;\n }\n\n // The mxEvent if one is about to be forwarded\n\n }, {\n key: 'getForwardingEvent',\n value: function getForwardingEvent() {\n return this._state.forwardingEvent;\n }\n\n // The mxEvent if one is currently being replied to/quoted\n\n }, {\n key: 'getQuotingEvent',\n value: function getQuotingEvent() {\n return this._state.replyingToEvent;\n }\n }, {\n key: 'shouldPeek',\n value: function shouldPeek() {\n return this._state.shouldPeek;\n }\n }]);\n return RoomViewStore;\n}(_utils.Store);\n\nvar singletonRoomViewStore = null;\nif (!singletonRoomViewStore) {\n singletonRoomViewStore = new RoomViewStore();\n}\nmodule.exports = singletonRoomViewStore;\n//# sourceMappingURL=RoomViewStore.js.map","module.exports = __webpack_public_path__ + \"img/warning.05cc423.svg\";","var core = module.exports = { version: '2.6.5' };\nif (typeof __e == 'number') __e = core; // eslint-disable-line no-undef\n","// optional / simple context binding\nvar aFunction = require('./_a-function');\nmodule.exports = function (fn, that, length) {\n aFunction(fn);\n if (that === undefined) return fn;\n switch (length) {\n case 1: return function (a) {\n return fn.call(that, a);\n };\n case 2: return function (a, b) {\n return fn.call(that, a, b);\n };\n case 3: return function (a, b, c) {\n return fn.call(that, a, b, c);\n };\n }\n return function (/* ...args */) {\n return fn.apply(that, arguments);\n };\n};\n","var toString = {}.toString;\n\nmodule.exports = function (it) {\n return toString.call(it).slice(8, -1);\n};\n","// 7.1.4 ToInteger\nvar ceil = Math.ceil;\nvar floor = Math.floor;\nmodule.exports = function (it) {\n return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);\n};\n","'use strict';\nvar fails = require('./_fails');\n\nmodule.exports = function (method, arg) {\n return !!method && fails(function () {\n // eslint-disable-next-line no-useless-call\n arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null);\n });\n};\n","module.exports = { \"default\": require(\"core-js/library/fn/array/from\"), __esModule: true };","module.exports = function (it) {\n if (typeof it != 'function') throw TypeError(it + ' is not a function!');\n return it;\n};\n","var toString = {}.toString;\n\nmodule.exports = function (it) {\n return toString.call(it).slice(8, -1);\n};\n","var id = 0;\nvar px = Math.random();\nmodule.exports = function (key) {\n return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));\n};\n","\"use strict\";\n\n/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * \n */\n\nfunction makeEmptyFunction(arg) {\n return function () {\n return arg;\n };\n}\n\n/**\n * This function accepts and discards inputs; it has no side effects. This is\n * primarily useful idiomatically for overridable function endpoints which\n * always need to be callable, since JS lacks a null-call idiom ala Cocoa.\n */\nvar emptyFunction = function emptyFunction() {};\n\nemptyFunction.thatReturns = makeEmptyFunction;\nemptyFunction.thatReturnsFalse = makeEmptyFunction(false);\nemptyFunction.thatReturnsTrue = makeEmptyFunction(true);\nemptyFunction.thatReturnsNull = makeEmptyFunction(null);\nemptyFunction.thatReturnsThis = function () {\n return this;\n};\nemptyFunction.thatReturnsArgument = function (arg) {\n return arg;\n};\n\nmodule.exports = emptyFunction;","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\n'use strict';\n\nvar _prodInvariant = require('./reactProdInvariant'),\n _assign = require('object-assign');\n\nvar CallbackQueue = require('./CallbackQueue');\nvar PooledClass = require('./PooledClass');\nvar ReactFeatureFlags = require('./ReactFeatureFlags');\nvar ReactReconciler = require('./ReactReconciler');\nvar Transaction = require('./Transaction');\n\nvar invariant = require('fbjs/lib/invariant');\n\nvar dirtyComponents = [];\nvar updateBatchNumber = 0;\nvar asapCallbackQueue = CallbackQueue.getPooled();\nvar asapEnqueued = false;\n\nvar batchingStrategy = null;\n\nfunction ensureInjected() {\n !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching strategy') : _prodInvariant('123') : void 0;\n}\n\nvar NESTED_UPDATES = {\n initialize: function () {\n this.dirtyComponentsLength = dirtyComponents.length;\n },\n close: function () {\n if (this.dirtyComponentsLength !== dirtyComponents.length) {\n // Additional updates were enqueued by componentDidUpdate handlers or\n // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run\n // these new updates so that if A's componentDidUpdate calls setState on\n // B, B will update before the callback A's updater provided when calling\n // setState.\n dirtyComponents.splice(0, this.dirtyComponentsLength);\n flushBatchedUpdates();\n } else {\n dirtyComponents.length = 0;\n }\n }\n};\n\nvar UPDATE_QUEUEING = {\n initialize: function () {\n this.callbackQueue.reset();\n },\n close: function () {\n this.callbackQueue.notifyAll();\n }\n};\n\nvar TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING];\n\nfunction ReactUpdatesFlushTransaction() {\n this.reinitializeTransaction();\n this.dirtyComponentsLength = null;\n this.callbackQueue = CallbackQueue.getPooled();\n this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(\n /* useCreateElement */true);\n}\n\n_assign(ReactUpdatesFlushTransaction.prototype, Transaction, {\n getTransactionWrappers: function () {\n return TRANSACTION_WRAPPERS;\n },\n\n destructor: function () {\n this.dirtyComponentsLength = null;\n CallbackQueue.release(this.callbackQueue);\n this.callbackQueue = null;\n ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction);\n this.reconcileTransaction = null;\n },\n\n perform: function (method, scope, a) {\n // Essentially calls `this.reconcileTransaction.perform(method, scope, a)`\n // with this transaction's wrappers around it.\n return Transaction.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a);\n }\n});\n\nPooledClass.addPoolingTo(ReactUpdatesFlushTransaction);\n\nfunction batchedUpdates(callback, a, b, c, d, e) {\n ensureInjected();\n return batchingStrategy.batchedUpdates(callback, a, b, c, d, e);\n}\n\n/**\n * Array comparator for ReactComponents by mount ordering.\n *\n * @param {ReactComponent} c1 first component you're comparing\n * @param {ReactComponent} c2 second component you're comparing\n * @return {number} Return value usable by Array.prototype.sort().\n */\nfunction mountOrderComparator(c1, c2) {\n return c1._mountOrder - c2._mountOrder;\n}\n\nfunction runBatchedUpdates(transaction) {\n var len = transaction.dirtyComponentsLength;\n !(len === dirtyComponents.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected flush transaction\\'s stored dirty-components length (%s) to match dirty-components array length (%s).', len, dirtyComponents.length) : _prodInvariant('124', len, dirtyComponents.length) : void 0;\n\n // Since reconciling a component higher in the owner hierarchy usually (not\n // always -- see shouldComponentUpdate()) will reconcile children, reconcile\n // them before their children by sorting the array.\n dirtyComponents.sort(mountOrderComparator);\n\n // Any updates enqueued while reconciling must be performed after this entire\n // batch. Otherwise, if dirtyComponents is [A, B] where A has children B and\n // C, B could update twice in a single batch if C's render enqueues an update\n // to B (since B would have already updated, we should skip it, and the only\n // way we can know to do so is by checking the batch counter).\n updateBatchNumber++;\n\n for (var i = 0; i < len; i++) {\n // If a component is unmounted before pending changes apply, it will still\n // be here, but we assume that it has cleared its _pendingCallbacks and\n // that performUpdateIfNecessary is a noop.\n var component = dirtyComponents[i];\n\n // If performUpdateIfNecessary happens to enqueue any new updates, we\n // shouldn't execute the callbacks until the next render happens, so\n // stash the callbacks first\n var callbacks = component._pendingCallbacks;\n component._pendingCallbacks = null;\n\n var markerName;\n if (ReactFeatureFlags.logTopLevelRenders) {\n var namedComponent = component;\n // Duck type TopLevelWrapper. This is probably always true.\n if (component._currentElement.type.isReactTopLevelWrapper) {\n namedComponent = component._renderedComponent;\n }\n markerName = 'React update: ' + namedComponent.getName();\n console.time(markerName);\n }\n\n ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber);\n\n if (markerName) {\n console.timeEnd(markerName);\n }\n\n if (callbacks) {\n for (var j = 0; j < callbacks.length; j++) {\n transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance());\n }\n }\n }\n}\n\nvar flushBatchedUpdates = function () {\n // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents\n // array and perform any updates enqueued by mount-ready handlers (i.e.,\n // componentDidUpdate) but we need to check here too in order to catch\n // updates enqueued by setState callbacks and asap calls.\n while (dirtyComponents.length || asapEnqueued) {\n if (dirtyComponents.length) {\n var transaction = ReactUpdatesFlushTransaction.getPooled();\n transaction.perform(runBatchedUpdates, null, transaction);\n ReactUpdatesFlushTransaction.release(transaction);\n }\n\n if (asapEnqueued) {\n asapEnqueued = false;\n var queue = asapCallbackQueue;\n asapCallbackQueue = CallbackQueue.getPooled();\n queue.notifyAll();\n CallbackQueue.release(queue);\n }\n }\n};\n\n/**\n * Mark a component as needing a rerender, adding an optional callback to a\n * list of functions which will be executed once the rerender occurs.\n */\nfunction enqueueUpdate(component) {\n ensureInjected();\n\n // Various parts of our code (such as ReactCompositeComponent's\n // _renderValidatedComponent) assume that calls to render aren't nested;\n // verify that that's the case. (This is called by each top-level update\n // function, like setState, forceUpdate, etc.; creation and\n // destruction of top-level components is guarded in ReactMount.)\n\n if (!batchingStrategy.isBatchingUpdates) {\n batchingStrategy.batchedUpdates(enqueueUpdate, component);\n return;\n }\n\n dirtyComponents.push(component);\n if (component._updateBatchNumber == null) {\n component._updateBatchNumber = updateBatchNumber + 1;\n }\n}\n\n/**\n * Enqueue a callback to be run at the end of the current batching cycle. Throws\n * if no updates are currently being performed.\n */\nfunction asap(callback, context) {\n invariant(batchingStrategy.isBatchingUpdates, \"ReactUpdates.asap: Can't enqueue an asap callback in a context where\" + 'updates are not being batched.');\n asapCallbackQueue.enqueue(callback, context);\n asapEnqueued = true;\n}\n\nvar ReactUpdatesInjection = {\n injectReconcileTransaction: function (ReconcileTransaction) {\n !ReconcileTransaction ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : _prodInvariant('126') : void 0;\n ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;\n },\n\n injectBatchingStrategy: function (_batchingStrategy) {\n !_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : _prodInvariant('127') : void 0;\n !(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : _prodInvariant('128') : void 0;\n !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : _prodInvariant('129') : void 0;\n batchingStrategy = _batchingStrategy;\n }\n};\n\nvar ReactUpdates = {\n /**\n * React references `ReactReconcileTransaction` using this property in order\n * to allow dependency injection.\n *\n * @internal\n */\n ReactReconcileTransaction: null,\n\n batchedUpdates: batchedUpdates,\n enqueueUpdate: enqueueUpdate,\n flushBatchedUpdates: flushBatchedUpdates,\n injection: ReactUpdatesInjection,\n asap: asap\n};\n\nmodule.exports = ReactUpdates;","module.exports = { \"default\": require(\"core-js/library/fn/set\"), __esModule: true };","// Browser Request\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// UMD HEADER START \n(function (root, factory) {\n if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define([], factory);\n } else if (typeof exports === 'object') {\n // Node. Does not work with strict CommonJS, but\n // only CommonJS-like enviroments that support module.exports,\n // like Node.\n module.exports = factory();\n } else {\n // Browser globals (root is window)\n root.returnExports = factory();\n }\n}(this, function () {\n// UMD HEADER END\n\nvar XHR = XMLHttpRequest\nif (!XHR) throw new Error('missing XMLHttpRequest')\nrequest.log = {\n 'trace': noop, 'debug': noop, 'info': noop, 'warn': noop, 'error': noop\n}\n\nvar DEFAULT_TIMEOUT = 3 * 60 * 1000 // 3 minutes\n\n//\n// request\n//\n\nfunction request(options, callback) {\n // The entry-point to the API: prep the options object and pass the real work to run_xhr.\n if(typeof callback !== 'function')\n throw new Error('Bad callback given: ' + callback)\n\n if(!options)\n throw new Error('No options given')\n\n var options_onResponse = options.onResponse; // Save this for later.\n\n if(typeof options === 'string')\n options = {'uri':options};\n else\n options = JSON.parse(JSON.stringify(options)); // Use a duplicate for mutating.\n\n options.onResponse = options_onResponse // And put it back.\n\n if (options.verbose) request.log = getLogger();\n\n if(options.url) {\n options.uri = options.url;\n delete options.url;\n }\n\n if(!options.uri && options.uri !== \"\")\n throw new Error(\"options.uri is a required argument\");\n\n if(typeof options.uri != \"string\")\n throw new Error(\"options.uri must be a string\");\n\n var unsupported_options = ['proxy', '_redirectsFollowed', 'maxRedirects', 'followRedirect']\n for (var i = 0; i < unsupported_options.length; i++)\n if(options[ unsupported_options[i] ])\n throw new Error(\"options.\" + unsupported_options[i] + \" is not supported\")\n\n options.callback = callback\n options.method = options.method || 'GET';\n options.headers = options.headers || {};\n options.body = options.body || null\n options.timeout = options.timeout || request.DEFAULT_TIMEOUT\n\n if(options.headers.host)\n throw new Error(\"Options.headers.host is not supported\");\n\n if(options.json) {\n options.headers.accept = options.headers.accept || 'application/json'\n if(options.method !== 'GET')\n options.headers['content-type'] = 'application/json'\n\n if(typeof options.json !== 'boolean')\n options.body = JSON.stringify(options.json)\n else if(typeof options.body !== 'string')\n options.body = JSON.stringify(options.body)\n }\n \n //BEGIN QS Hack\n var serialize = function(obj) {\n var str = [];\n for(var p in obj)\n if (obj.hasOwnProperty(p)) {\n str.push(encodeURIComponent(p) + \"=\" + encodeURIComponent(obj[p]));\n }\n return str.join(\"&\");\n }\n \n if(options.qs){\n var qs = (typeof options.qs == 'string')? options.qs : serialize(options.qs);\n if(options.uri.indexOf('?') !== -1){ //no get params\n options.uri = options.uri+'&'+qs;\n }else{ //existing get params\n options.uri = options.uri+'?'+qs;\n }\n }\n //END QS Hack\n \n //BEGIN FORM Hack\n var multipart = function(obj) {\n //todo: support file type (useful?)\n var result = {};\n result.boundry = '-------------------------------'+Math.floor(Math.random()*1000000000);\n var lines = [];\n for(var p in obj){\n if (obj.hasOwnProperty(p)) {\n lines.push(\n '--'+result.boundry+\"\\n\"+\n 'Content-Disposition: form-data; name=\"'+p+'\"'+\"\\n\"+\n \"\\n\"+\n obj[p]+\"\\n\"\n );\n }\n }\n lines.push( '--'+result.boundry+'--' );\n result.body = lines.join('');\n result.length = result.body.length;\n result.type = 'multipart/form-data; boundary='+result.boundry;\n return result;\n }\n \n if(options.form){\n if(typeof options.form == 'string') throw('form name unsupported');\n if(options.method === 'POST'){\n var encoding = (options.encoding || 'application/x-www-form-urlencoded').toLowerCase();\n options.headers['content-type'] = encoding;\n switch(encoding){\n case 'application/x-www-form-urlencoded':\n options.body = serialize(options.form).replace(/%20/g, \"+\");\n break;\n case 'multipart/form-data':\n var multi = multipart(options.form);\n //options.headers['content-length'] = multi.length;\n options.body = multi.body;\n options.headers['content-type'] = multi.type;\n break;\n default : throw new Error('unsupported encoding:'+encoding);\n }\n }\n }\n //END FORM Hack\n\n // If onResponse is boolean true, call back immediately when the response is known,\n // not when the full request is complete.\n options.onResponse = options.onResponse || noop\n if(options.onResponse === true) {\n options.onResponse = callback\n options.callback = noop\n }\n\n // XXX Browsers do not like this.\n //if(options.body)\n // options.headers['content-length'] = options.body.length;\n\n // HTTP basic authentication\n if(!options.headers.authorization && options.auth)\n options.headers.authorization = 'Basic ' + b64_enc(options.auth.username + ':' + options.auth.password);\n\n return run_xhr(options)\n}\n\nvar req_seq = 0\nfunction run_xhr(options) {\n var xhr = new XHR\n , timed_out = false\n , is_cors = is_crossDomain(options.uri)\n , supports_cors = ('withCredentials' in xhr)\n\n req_seq += 1\n xhr.seq_id = req_seq\n xhr.id = req_seq + ': ' + options.method + ' ' + options.uri\n xhr._id = xhr.id // I know I will type \"_id\" from habit all the time.\n\n if(is_cors && !supports_cors) {\n var cors_err = new Error('Browser does not support cross-origin request: ' + options.uri)\n cors_err.cors = 'unsupported'\n return options.callback(cors_err, xhr)\n }\n\n xhr.timeoutTimer = setTimeout(too_late, options.timeout)\n function too_late() {\n timed_out = true\n var er = new Error('ETIMEDOUT')\n er.code = 'ETIMEDOUT'\n er.duration = options.timeout\n\n request.log.error('Timeout', { 'id':xhr._id, 'milliseconds':options.timeout })\n return options.callback(er, xhr)\n }\n\n // Some states can be skipped over, so remember what is still incomplete.\n var did = {'response':false, 'loading':false, 'end':false}\n\n xhr.onreadystatechange = on_state_change\n xhr.open(options.method, options.uri, true) // asynchronous\n if(is_cors)\n xhr.withCredentials = !! options.withCredentials\n xhr.send(options.body)\n return xhr\n\n function on_state_change(event) {\n if(timed_out)\n return request.log.debug('Ignoring timed out state change', {'state':xhr.readyState, 'id':xhr.id})\n\n request.log.debug('State change', {'state':xhr.readyState, 'id':xhr.id, 'timed_out':timed_out})\n\n if(xhr.readyState === XHR.OPENED) {\n request.log.debug('Request started', {'id':xhr.id})\n for (var key in options.headers)\n xhr.setRequestHeader(key, options.headers[key])\n }\n\n else if(xhr.readyState === XHR.HEADERS_RECEIVED)\n on_response()\n\n else if(xhr.readyState === XHR.LOADING) {\n on_response()\n on_loading()\n }\n\n else if(xhr.readyState === XHR.DONE) {\n on_response()\n on_loading()\n on_end()\n }\n }\n\n function on_response() {\n if(did.response)\n return\n\n did.response = true\n request.log.debug('Got response', {'id':xhr.id, 'status':xhr.status})\n clearTimeout(xhr.timeoutTimer)\n xhr.statusCode = xhr.status // Node request compatibility\n\n // Detect failed CORS requests.\n if(is_cors && xhr.statusCode == 0) {\n var cors_err = new Error('CORS request rejected: ' + options.uri)\n cors_err.cors = 'rejected'\n\n // Do not process this request further.\n did.loading = true\n did.end = true\n\n return options.callback(cors_err, xhr)\n }\n\n options.onResponse(null, xhr)\n }\n\n function on_loading() {\n if(did.loading)\n return\n\n did.loading = true\n request.log.debug('Response body loading', {'id':xhr.id})\n // TODO: Maybe simulate \"data\" events by watching xhr.responseText\n }\n\n function on_end() {\n if(did.end)\n return\n\n did.end = true\n request.log.debug('Request done', {'id':xhr.id})\n\n xhr.body = xhr.responseText\n if(options.json) {\n try { xhr.body = JSON.parse(xhr.responseText) }\n catch (er) { return options.callback(er, xhr) }\n }\n\n options.callback(null, xhr, xhr.body)\n }\n\n} // request\n\nrequest.withCredentials = false;\nrequest.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;\n\n//\n// defaults\n//\n\nrequest.defaults = function(options, requester) {\n var def = function (method) {\n var d = function (params, callback) {\n if(typeof params === 'string')\n params = {'uri': params};\n else {\n params = JSON.parse(JSON.stringify(params));\n }\n for (var i in options) {\n if (params[i] === undefined) params[i] = options[i]\n }\n return method(params, callback)\n }\n return d\n }\n var de = def(request)\n de.get = def(request.get)\n de.post = def(request.post)\n de.put = def(request.put)\n de.head = def(request.head)\n return de\n}\n\n//\n// HTTP method shortcuts\n//\n\nvar shortcuts = [ 'get', 'put', 'post', 'head' ];\nshortcuts.forEach(function(shortcut) {\n var method = shortcut.toUpperCase();\n var func = shortcut.toLowerCase();\n\n request[func] = function(opts) {\n if(typeof opts === 'string')\n opts = {'method':method, 'uri':opts};\n else {\n opts = JSON.parse(JSON.stringify(opts));\n opts.method = method;\n }\n\n var args = [opts].concat(Array.prototype.slice.apply(arguments, [1]));\n return request.apply(this, args);\n }\n})\n\n//\n// CouchDB shortcut\n//\n\nrequest.couch = function(options, callback) {\n if(typeof options === 'string')\n options = {'uri':options}\n\n // Just use the request API to do JSON.\n options.json = true\n if(options.body)\n options.json = options.body\n delete options.body\n\n callback = callback || noop\n\n var xhr = request(options, couch_handler)\n return xhr\n\n function couch_handler(er, resp, body) {\n if(er)\n return callback(er, resp, body)\n\n if((resp.statusCode < 200 || resp.statusCode > 299) && body.error) {\n // The body is a Couch JSON object indicating the error.\n er = new Error('CouchDB error: ' + (body.error.reason || body.error.error))\n for (var key in body)\n er[key] = body[key]\n return callback(er, resp, body);\n }\n\n return callback(er, resp, body);\n }\n}\n\n//\n// Utility\n//\n\nfunction noop() {}\n\nfunction getLogger() {\n var logger = {}\n , levels = ['trace', 'debug', 'info', 'warn', 'error']\n , level, i\n\n for(i = 0; i < levels.length; i++) {\n level = levels[i]\n\n logger[level] = noop\n if(typeof console !== 'undefined' && console && console[level])\n logger[level] = formatted(console, level)\n }\n\n return logger\n}\n\nfunction formatted(obj, method) {\n return formatted_logger\n\n function formatted_logger(str, context) {\n if(typeof context === 'object')\n str += ' ' + JSON.stringify(context)\n\n return obj[method].call(obj, str)\n }\n}\n\n// Return whether a URL is a cross-domain request.\nfunction is_crossDomain(url) {\n var rurl = /^([\\w\\+\\.\\-]+:)(?:\\/\\/([^\\/?#:]*)(?::(\\d+))?)?/\n\n // jQuery #8138, IE may throw an exception when accessing\n // a field from window.location if document.domain has been set\n var ajaxLocation\n try { ajaxLocation = location.href }\n catch (e) {\n // Use the href attribute of an A element since IE will modify it given document.location\n ajaxLocation = document.createElement( \"a\" );\n ajaxLocation.href = \"\";\n ajaxLocation = ajaxLocation.href;\n }\n\n var ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || []\n , parts = rurl.exec(url.toLowerCase() )\n\n var result = !!(\n parts &&\n ( parts[1] != ajaxLocParts[1]\n || parts[2] != ajaxLocParts[2]\n || (parts[3] || (parts[1] === \"http:\" ? 80 : 443)) != (ajaxLocParts[3] || (ajaxLocParts[1] === \"http:\" ? 80 : 443))\n )\n )\n\n //console.debug('is_crossDomain('+url+') -> ' + result)\n return result\n}\n\n// MIT License from http://phpjs.org/functions/base64_encode:358\nfunction b64_enc (data) {\n // Encodes string using MIME base64 algorithm\n var b64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc=\"\", tmp_arr = [];\n\n if (!data) {\n return data;\n }\n\n // assume utf8 data\n // data = this.utf8_encode(data+'');\n\n do { // pack three octets into four hexets\n o1 = data.charCodeAt(i++);\n o2 = data.charCodeAt(i++);\n o3 = data.charCodeAt(i++);\n\n bits = o1<<16 | o2<<8 | o3;\n\n h1 = bits>>18 & 0x3f;\n h2 = bits>>12 & 0x3f;\n h3 = bits>>6 & 0x3f;\n h4 = bits & 0x3f;\n\n // use hexets to index into b64, and append result to encoded string\n tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);\n } while (i < data.length);\n\n enc = tmp_arr.join('');\n\n switch (data.length % 3) {\n case 1:\n enc = enc.slice(0, -2) + '==';\n break;\n case 2:\n enc = enc.slice(0, -1) + '=';\n break;\n }\n\n return enc;\n}\n return request;\n//UMD FOOTER START\n}));\n//UMD FOOTER END\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nmodule.exports = root;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nvar _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');\n\nvar _slicedToArray3 = _interopRequireDefault(_slicedToArray2);\n\nvar _entries = require('babel-runtime/core-js/object/entries');\n\nvar _entries2 = _interopRequireDefault(_entries);\n\nvar _values = require('babel-runtime/core-js/object/values');\n\nvar _values2 = _interopRequireDefault(_values);\n\nvar _promise = require('babel-runtime/core-js/promise');\n\nvar _promise2 = _interopRequireDefault(_promise);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _MatrixClientPeg = require('../MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _SdkConfig = require('../SdkConfig');\n\nvar _SdkConfig2 = _interopRequireDefault(_SdkConfig);\n\nvar _dispatcher = require('../dispatcher');\n\nvar _dispatcher2 = _interopRequireDefault(_dispatcher);\n\nvar _url = require('url');\n\nvar url = _interopRequireWildcard(_url);\n\nvar _WidgetEchoStore = require('../stores/WidgetEchoStore');\n\nvar _WidgetEchoStore2 = _interopRequireDefault(_WidgetEchoStore);\n\nvar _SettingsStore = require('../settings/SettingsStore');\n\nvar _SettingsStore2 = _interopRequireDefault(_SettingsStore);\n\nvar _ActiveWidgetStore = require('../stores/ActiveWidgetStore');\n\nvar _ActiveWidgetStore2 = _interopRequireDefault(_ActiveWidgetStore);\n\nfunction _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// How long we wait for the state event echo to come back from the server\n// before waitFor[Room/User]Widget rejects its promise\nvar WIDGET_WAIT_TIME = 20000; /*\n Copyright 2017 Vector Creations Ltd\n Copyright 2018 New Vector Ltd\n Copyright 2019 Travis Ralston\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\n/**\n * Encodes a URI according to a set of template variables. Variables will be\n * passed through encodeURIComponent.\n * @param {string} pathTemplate The path with template variables e.g. '/foo/$bar'.\n * @param {Object} variables The key/value pairs to replace the template\n * variables with. E.g. { '$bar': 'baz' }.\n * @return {string} The result of replacing all template variables e.g. '/foo/baz'.\n */\nfunction encodeUri(pathTemplate, variables) {\n for (var key in variables) {\n if (!variables.hasOwnProperty(key)) {\n continue;\n }\n pathTemplate = pathTemplate.replace(key, encodeURIComponent(variables[key]));\n }\n return pathTemplate;\n}\n\nvar WidgetUtils = function () {\n function WidgetUtils() {\n (0, _classCallCheck3.default)(this, WidgetUtils);\n }\n\n (0, _createClass3.default)(WidgetUtils, null, [{\n key: 'canUserModifyWidgets',\n\n /* Returns true if user is able to send state events to modify widgets in this room\n * (Does not apply to non-room-based / user widgets)\n * @param roomId -- The ID of the room to check\n * @return Boolean -- true if the user can modify widgets in this room\n * @throws Error -- specifies the error reason\n */\n value: function canUserModifyWidgets(roomId) {\n if (!roomId) {\n console.warn('No room ID specified');\n return false;\n }\n\n var client = _MatrixClientPeg2.default.get();\n if (!client) {\n console.warn('User must be be logged in');\n return false;\n }\n\n var room = client.getRoom(roomId);\n if (!room) {\n console.warn('Room ID ' + roomId + ' is not recognised');\n return false;\n }\n\n var me = client.credentials.userId;\n if (!me) {\n console.warn('Failed to get user ID');\n return false;\n }\n\n if (room.getMyMembership() !== \"join\") {\n console.warn('User ' + me + ' is not in room ' + roomId);\n return false;\n }\n\n return room.currentState.maySendStateEvent('im.vector.modular.widgets', me);\n }\n\n /**\n * Returns true if specified url is a scalar URL, typically https://scalar.vector.im/api\n * @param {[type]} testUrlString URL to check\n * @return {Boolean} True if specified URL is a scalar URL\n */\n\n }, {\n key: 'isScalarUrl',\n value: function isScalarUrl(testUrlString) {\n if (!testUrlString) {\n console.error('Scalar URL check failed. No URL specified');\n return false;\n }\n\n var testUrl = url.parse(testUrlString);\n\n var scalarUrls = _SdkConfig2.default.get().integrations_widgets_urls;\n if (!scalarUrls || scalarUrls.length === 0) {\n scalarUrls = [_SdkConfig2.default.get().integrations_rest_url];\n }\n\n for (var i = 0; i < scalarUrls.length; i++) {\n var scalarUrl = url.parse(scalarUrls[i]);\n if (testUrl && scalarUrl) {\n if (testUrl.protocol === scalarUrl.protocol && testUrl.host === scalarUrl.host && testUrl.pathname.startsWith(scalarUrl.pathname)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Returns a promise that resolves when a widget with the given\n * ID has been added as a user widget (ie. the accountData event\n * arrives) or rejects after a timeout\n *\n * @param {string} widgetId The ID of the widget to wait for\n * @param {boolean} add True to wait for the widget to be added,\n * false to wait for it to be deleted.\n * @returns {Promise} that resolves when the widget is in the\n * requested state according to the `add` param\n */\n\n }, {\n key: 'waitForUserWidget',\n value: function waitForUserWidget(widgetId, add) {\n return new _promise2.default(function (resolve, reject) {\n // Tests an account data event, returning true if it's in the state\n // we're waiting for it to be in\n function eventInIntendedState(ev) {\n if (!ev || !ev.getContent()) return false;\n if (add) {\n return ev.getContent()[widgetId] !== undefined;\n } else {\n return ev.getContent()[widgetId] === undefined;\n }\n }\n\n var startingAccountDataEvent = _MatrixClientPeg2.default.get().getAccountData('m.widgets');\n if (eventInIntendedState(startingAccountDataEvent)) {\n resolve();\n return;\n }\n\n function onAccountData(ev) {\n var currentAccountDataEvent = _MatrixClientPeg2.default.get().getAccountData('m.widgets');\n if (eventInIntendedState(currentAccountDataEvent)) {\n _MatrixClientPeg2.default.get().removeListener('accountData', onAccountData);\n clearTimeout(timerId);\n resolve();\n }\n }\n var timerId = setTimeout(function () {\n _MatrixClientPeg2.default.get().removeListener('accountData', onAccountData);\n reject(new Error(\"Timed out waiting for widget ID \" + widgetId + \" to appear\"));\n }, WIDGET_WAIT_TIME);\n _MatrixClientPeg2.default.get().on('accountData', onAccountData);\n });\n }\n\n /**\n * Returns a promise that resolves when a widget with the given\n * ID has been added as a room widget in the given room (ie. the\n * room state event arrives) or rejects after a timeout\n *\n * @param {string} widgetId The ID of the widget to wait for\n * @param {string} roomId The ID of the room to wait for the widget in\n * @param {boolean} add True to wait for the widget to be added,\n * false to wait for it to be deleted.\n * @returns {Promise} that resolves when the widget is in the\n * requested state according to the `add` param\n */\n\n }, {\n key: 'waitForRoomWidget',\n value: function waitForRoomWidget(widgetId, roomId, add) {\n return new _promise2.default(function (resolve, reject) {\n // Tests a list of state events, returning true if it's in the state\n // we're waiting for it to be in\n function eventsInIntendedState(evList) {\n var widgetPresent = evList.some(function (ev) {\n return ev.getContent() && ev.getContent()['id'] === widgetId;\n });\n if (add) {\n return widgetPresent;\n } else {\n return !widgetPresent;\n }\n }\n\n var room = _MatrixClientPeg2.default.get().getRoom(roomId);\n var startingWidgetEvents = room.currentState.getStateEvents('im.vector.modular.widgets');\n if (eventsInIntendedState(startingWidgetEvents)) {\n resolve();\n return;\n }\n\n function onRoomStateEvents(ev) {\n if (ev.getRoomId() !== roomId) return;\n\n var currentWidgetEvents = room.currentState.getStateEvents('im.vector.modular.widgets');\n\n if (eventsInIntendedState(currentWidgetEvents)) {\n _MatrixClientPeg2.default.get().removeListener('RoomState.events', onRoomStateEvents);\n clearTimeout(timerId);\n resolve();\n }\n }\n var timerId = setTimeout(function () {\n _MatrixClientPeg2.default.get().removeListener('RoomState.events', onRoomStateEvents);\n reject(new Error(\"Timed out waiting for widget ID \" + widgetId + \" to appear\"));\n }, WIDGET_WAIT_TIME);\n _MatrixClientPeg2.default.get().on('RoomState.events', onRoomStateEvents);\n });\n }\n }, {\n key: 'setUserWidget',\n value: function setUserWidget(widgetId, widgetType, widgetUrl, widgetName, widgetData) {\n var content = {\n type: widgetType,\n url: widgetUrl,\n name: widgetName,\n data: widgetData\n };\n\n var client = _MatrixClientPeg2.default.get();\n var userWidgets = WidgetUtils.getUserWidgets();\n\n // Delete existing widget with ID\n try {\n delete userWidgets[widgetId];\n } catch (e) {\n console.error('$widgetId is non-configurable');\n }\n\n var addingWidget = Boolean(widgetUrl);\n\n // Add new widget / update\n if (addingWidget) {\n userWidgets[widgetId] = {\n content: content,\n sender: client.getUserId(),\n state_key: widgetId,\n type: 'm.widget',\n id: widgetId\n };\n }\n\n // This starts listening for when the echo comes back from the server\n // since the widget won't appear added until this happens. If we don't\n // wait for this, the action will complete but if the user is fast enough,\n // the widget still won't actually be there.\n return client.setAccountData('m.widgets', userWidgets).then(function () {\n return WidgetUtils.waitForUserWidget(widgetId, addingWidget);\n }).then(function () {\n _dispatcher2.default.dispatch({ action: \"user_widget_updated\" });\n });\n }\n }, {\n key: 'setRoomWidget',\n value: function setRoomWidget(roomId, widgetId, widgetType, widgetUrl, widgetName, widgetData) {\n var content = void 0;\n\n var addingWidget = Boolean(widgetUrl);\n\n if (addingWidget) {\n content = {\n type: widgetType,\n url: widgetUrl,\n name: widgetName,\n data: widgetData\n };\n } else {\n content = {};\n }\n\n _WidgetEchoStore2.default.setRoomWidgetEcho(roomId, widgetId, content);\n\n var client = _MatrixClientPeg2.default.get();\n // TODO - Room widgets need to be moved to 'm.widget' state events\n // https://docs.google.com/document/d/1uPF7XWY_dXTKVKV7jZQ2KmsI19wn9-kFRgQ1tFQP7wQ/edit?usp=sharing\n return client.sendStateEvent(roomId, \"im.vector.modular.widgets\", content, widgetId).then(function () {\n return WidgetUtils.waitForRoomWidget(widgetId, roomId, addingWidget);\n }).finally(function () {\n _WidgetEchoStore2.default.removeRoomWidgetEcho(roomId, widgetId);\n });\n }\n\n /**\n * Get room specific widgets\n * @param {object} room The room to get widgets force\n * @return {[object]} Array containing current / active room widgets\n */\n\n }, {\n key: 'getRoomWidgets',\n value: function getRoomWidgets(room) {\n var appsStateEvents = room.currentState.getStateEvents('im.vector.modular.widgets');\n if (!appsStateEvents) {\n return [];\n }\n\n return appsStateEvents.filter(function (ev) {\n return ev.getContent().type && ev.getContent().url;\n });\n }\n\n /**\n * Get user specific widgets (not linked to a specific room)\n * @return {object} Event content object containing current / active user widgets\n */\n\n }, {\n key: 'getUserWidgets',\n value: function getUserWidgets() {\n var client = _MatrixClientPeg2.default.get();\n if (!client) {\n throw new Error('User not logged in');\n }\n var userWidgets = client.getAccountData('m.widgets');\n if (userWidgets && userWidgets.getContent()) {\n return userWidgets.getContent();\n }\n return {};\n }\n\n /**\n * Get user specific widgets (not linked to a specific room) as an array\n * @return {[object]} Array containing current / active user widgets\n */\n\n }, {\n key: 'getUserWidgetsArray',\n value: function getUserWidgetsArray() {\n return (0, _values2.default)(WidgetUtils.getUserWidgets());\n }\n\n /**\n * Get active stickerpicker widgets (stickerpickers are user widgets by nature)\n * @return {[object]} Array containing current / active stickerpicker widgets\n */\n\n }, {\n key: 'getStickerpickerWidgets',\n value: function getStickerpickerWidgets() {\n var widgets = WidgetUtils.getUserWidgetsArray();\n return widgets.filter(function (widget) {\n return widget.content && widget.content.type === \"m.stickerpicker\";\n });\n }\n\n /**\n * Remove all stickerpicker widgets (stickerpickers are user widgets by nature)\n * @return {Promise} Resolves on account data updated\n */\n\n }, {\n key: 'removeStickerpickerWidgets',\n value: function removeStickerpickerWidgets() {\n var client = _MatrixClientPeg2.default.get();\n if (!client) {\n throw new Error('User not logged in');\n }\n var userWidgets = client.getAccountData('m.widgets').getContent() || {};\n (0, _entries2.default)(userWidgets).forEach(function (_ref) {\n var _ref2 = (0, _slicedToArray3.default)(_ref, 2),\n key = _ref2[0],\n widget = _ref2[1];\n\n if (widget.content && widget.content.type === 'm.stickerpicker') {\n delete userWidgets[key];\n }\n });\n return client.setAccountData('m.widgets', userWidgets);\n }\n }, {\n key: 'makeAppConfig',\n value: function makeAppConfig(appId, app, sender, roomId) {\n var myUserId = _MatrixClientPeg2.default.get().credentials.userId;\n var user = _MatrixClientPeg2.default.get().getUser(myUserId);\n var params = {\n '$matrix_user_id': myUserId,\n '$matrix_room_id': roomId,\n '$matrix_display_name': user ? user.displayName : myUserId,\n '$matrix_avatar_url': user ? _MatrixClientPeg2.default.get().mxcUrlToHttp(user.avatarUrl) : '',\n\n // TODO: Namespace themes through some standard\n '$theme': _SettingsStore2.default.getValue(\"theme\")\n };\n\n app.id = appId;\n app.name = app.name || app.type;\n\n if (app.data) {\n (0, _keys2.default)(app.data).forEach(function (key) {\n params['$' + key] = app.data[key];\n });\n\n app.waitForIframeLoad = app.data.waitForIframeLoad === 'false' ? false : true;\n }\n\n app.url = encodeUri(app.url, params);\n app.creatorUserId = sender && sender.userId ? sender.userId : null;\n\n return app;\n }\n }, {\n key: 'getCapWhitelistForAppTypeInRoomId',\n value: function getCapWhitelistForAppTypeInRoomId(appType, roomId) {\n var enableScreenshots = _SettingsStore2.default.getValue(\"enableWidgetScreenshots\", roomId);\n\n var capWhitelist = enableScreenshots ? [\"m.capability.screenshot\"] : [];\n\n // Obviously anyone that can add a widget can claim it's a jitsi widget,\n // so this doesn't really offer much over the set of domains we load\n // widgets from at all, but it probably makes sense for sanity.\n if (appType == 'jitsi') capWhitelist.push(\"m.always_on_screen\");\n\n return capWhitelist;\n }\n }, {\n key: 'getWidgetSecurityKey',\n value: function getWidgetSecurityKey(widgetId, widgetUrl, isUserWidget) {\n var widgetLocation = _ActiveWidgetStore2.default.getRoomId(widgetId);\n\n if (isUserWidget) {\n var userWidget = WidgetUtils.getUserWidgetsArray().find(function (w) {\n return w.id === widgetId && w.content && w.content.url === widgetUrl;\n });\n\n if (!userWidget) {\n throw new Error(\"No matching user widget to form security key\");\n }\n\n widgetLocation = userWidget.sender;\n }\n\n if (!widgetLocation) {\n throw new Error(\"Failed to locate where the widget resides\");\n }\n\n return encodeURIComponent(widgetLocation + '::' + widgetUrl);\n }\n }]);\n return WidgetUtils;\n}();\n\nexports.default = WidgetUtils;\nmodule.exports = exports['default'];\n//# sourceMappingURL=WidgetUtils.js.map","/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017, 2018 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _assign = require('babel-runtime/core-js/object/assign');\n\nvar _assign2 = _interopRequireDefault(_assign);\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nexports.containsEmoji = containsEmoji;\nexports.unicodeToShortcode = unicodeToShortcode;\nexports.shortcodeToUnicode = shortcodeToUnicode;\nexports.processHtmlForSending = processHtmlForSending;\nexports.sanitizedHtmlNode = sanitizedHtmlNode;\nexports.isUrlPermitted = isUrlPermitted;\nexports.bodyToHtml = bodyToHtml;\nexports.linkifyString = linkifyString;\nexports.linkifyElement = linkifyElement;\nexports.linkifyAndSanitizeHtml = linkifyAndSanitizeHtml;\n\nvar _ReplyThread = require('./components/views/elements/ReplyThread');\n\nvar _ReplyThread2 = _interopRequireDefault(_ReplyThread);\n\nvar _react = require('react');\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _sanitizeHtml = require('sanitize-html');\n\nvar _sanitizeHtml2 = _interopRequireDefault(_sanitizeHtml);\n\nvar _highlight = require('highlight.js');\n\nvar _highlight2 = _interopRequireDefault(_highlight);\n\nvar _linkifyjs = require('linkifyjs');\n\nvar linkify = _interopRequireWildcard(_linkifyjs);\n\nvar _linkifyMatrix = require('./linkify-matrix');\n\nvar _linkifyMatrix2 = _interopRequireDefault(_linkifyMatrix);\n\nvar _element = require('linkifyjs/element');\n\nvar _element2 = _interopRequireDefault(_element);\n\nvar _string = require('linkifyjs/string');\n\nvar _string2 = _interopRequireDefault(_string);\n\nvar _escape = require('lodash/escape');\n\nvar _escape2 = _interopRequireDefault(_escape);\n\nvar _classnames = require('classnames');\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar _MatrixClientPeg = require('./MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _url = require('url');\n\nvar _url2 = _interopRequireDefault(_url);\n\nvar _compact = require('emojibase-data/en/compact.json');\n\nvar _compact2 = _interopRequireDefault(_compact);\n\nvar _emojibaseRegex = require('emojibase-regex');\n\nvar _emojibaseRegex2 = _interopRequireDefault(_emojibaseRegex);\n\nfunction _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n(0, _linkifyMatrix2.default)(linkify);\n\n// Anything outside the basic multilingual plane will be a surrogate pair\nvar SURROGATE_PAIR_PATTERN = /([\\ud800-\\udbff])([\\udc00-\\udfff])/;\n// And there a bunch more symbol characters that emojibase has within the\n// BMP, so this includes the ranges from 'letterlike symbols' to\n// 'miscellaneous symbols and arrows' which should catch all of them\n// (with plenty of false positives, but that's OK)\nvar SYMBOL_PATTERN = /([\\u2100-\\u2bff])/;\n\n// Regex pattern for Zero-Width joiner unicode characters\nvar ZWJ_REGEX = new RegExp('\\u200D|\\u2003', \"g\");\n\n// Regex pattern for whitespace characters\nvar WHITESPACE_REGEX = new RegExp(\"\\\\s\", \"g\");\n\nvar BIGEMOJI_REGEX = new RegExp('^(' + _emojibaseRegex2.default.source + ')+$', 'i');\n\nvar COLOR_REGEX = /^#[0-9a-fA-F]{6}$/;\n\nvar PERMITTED_URL_SCHEMES = ['http', 'https', 'ftp', 'mailto', 'magnet'];\n\n/*\n * Return true if the given string contains emoji\n * Uses a much, much simpler regex than emojibase's so will give false\n * positives, but useful for fast-path testing strings to see if they\n * need emojification.\n * unicodeToImage uses this function.\n */\nfunction containsEmoji(str) {\n return SURROGATE_PAIR_PATTERN.test(str) || SYMBOL_PATTERN.test(str);\n}\n\n/**\n * Returns the shortcode for an emoji character.\n *\n * @param {String} char The emoji character\n * @return {String} The shortcode (such as :thumbup:)\n */\nfunction unicodeToShortcode(char) {\n var data = _compact2.default.find(function (e) {\n return e.unicode === char;\n });\n return data && data.shortcodes ? ':' + data.shortcodes[0] + ':' : '';\n}\n\n/**\n * Returns the unicode character for an emoji shortcode\n *\n * @param {String} shortcode The shortcode (such as :thumbup:)\n * @return {String} The emoji character; null if none exists\n */\nfunction shortcodeToUnicode(shortcode) {\n shortcode = shortcode.slice(1, shortcode.length - 1);\n var data = _compact2.default.find(function (e) {\n return e.shortcodes && e.shortcodes.includes(shortcode);\n });\n return data ? data.unicode : null;\n}\n\nfunction processHtmlForSending(html) {\n var contentDiv = document.createElement('div');\n contentDiv.innerHTML = html;\n\n if (contentDiv.children.length === 0) {\n return contentDiv.innerHTML;\n }\n\n var contentHTML = \"\";\n for (var i = 0; i < contentDiv.children.length; i++) {\n var element = contentDiv.children[i];\n if (element.tagName.toLowerCase() === 'p') {\n contentHTML += element.innerHTML;\n // Don't add a
for the last \n if (i !== contentDiv.children.length - 1) {\n contentHTML += '
';\n }\n } else {\n var temp = document.createElement('div');\n temp.appendChild(element.cloneNode(true));\n contentHTML += temp.innerHTML;\n }\n }\n\n return contentHTML;\n}\n\n/*\n * Given an untrusted HTML string, return a React node with an sanitized version\n * of that HTML.\n */\nfunction sanitizedHtmlNode(insaneHtml) {\n var saneHtml = (0, _sanitizeHtml2.default)(insaneHtml, sanitizeHtmlParams);\n\n return _react2.default.createElement('div', { dangerouslySetInnerHTML: { __html: saneHtml }, dir: 'auto' });\n}\n\n/**\n * Tests if a URL from an untrusted source may be safely put into the DOM\n * The biggest threat here is javascript: URIs.\n * Note that the HTML sanitiser library has its own internal logic for\n * doing this, to which we pass the same list of schemes. This is used in\n * other places we need to sanitise URLs.\n * @return true if permitted, otherwise false\n */\nfunction isUrlPermitted(inputUrl) {\n try {\n var parsed = _url2.default.parse(inputUrl);\n if (!parsed.protocol) return false;\n // URL parser protocol includes the trailing colon\n return PERMITTED_URL_SCHEMES.includes(parsed.protocol.slice(0, -1));\n } catch (e) {\n return false;\n }\n}\n\nvar transformTags = { // custom to matrix\n // add blank targets to all hyperlinks except vector URLs\n 'a': function a(tagName, attribs) {\n if (attribs.href) {\n attribs.target = '_blank'; // by default\n\n var m = void 0;\n // FIXME: horrible duplication with linkify-matrix\n m = attribs.href.match(_linkifyMatrix2.default.VECTOR_URL_PATTERN);\n if (m) {\n attribs.href = m[1];\n delete attribs.target;\n } else {\n m = attribs.href.match(_linkifyMatrix2.default.MATRIXTO_URL_PATTERN);\n if (m) {\n var entity = m[1];\n switch (entity[0]) {\n case '@':\n attribs.href = '#/user/' + entity;\n break;\n case '+':\n attribs.href = '#/group/' + entity;\n break;\n case '#':\n case '!':\n attribs.href = '#/room/' + entity;\n break;\n }\n delete attribs.target;\n }\n }\n }\n attribs.rel = 'noopener'; // https://mathiasbynens.github.io/rel-noopener/\n return { tagName: tagName, attribs: attribs };\n },\n 'img': function img(tagName, attribs) {\n // Strip out imgs that aren't `mxc` here instead of using allowedSchemesByTag\n // because transformTags is used _before_ we filter by allowedSchemesByTag and\n // we don't want to allow images with `https?` `src`s.\n if (!attribs.src || !attribs.src.startsWith('mxc://')) {\n return { tagName: tagName, attribs: {} };\n }\n attribs.src = _MatrixClientPeg2.default.get().mxcUrlToHttp(attribs.src, attribs.width || 800, attribs.height || 600);\n return { tagName: tagName, attribs: attribs };\n },\n 'code': function code(tagName, attribs) {\n if (typeof attribs.class !== 'undefined') {\n // Filter out all classes other than ones starting with language- for syntax highlighting.\n var classes = attribs.class.split(/\\s/).filter(function (cl) {\n return cl.startsWith('language-');\n });\n attribs.class = classes.join(' ');\n }\n return { tagName: tagName, attribs: attribs };\n },\n '*': function _(tagName, attribs) {\n // Delete any style previously assigned, style is an allowedTag for font and span\n // because attributes are stripped after transforming\n delete attribs.style;\n\n // Sanitise and transform data-mx-color and data-mx-bg-color to their CSS\n // equivalents\n var customCSSMapper = {\n 'data-mx-color': 'color',\n 'data-mx-bg-color': 'background-color'\n // $customAttributeKey: $cssAttributeKey\n };\n\n var style = \"\";\n (0, _keys2.default)(customCSSMapper).forEach(function (customAttributeKey) {\n var cssAttributeKey = customCSSMapper[customAttributeKey];\n var customAttributeValue = attribs[customAttributeKey];\n if (customAttributeValue && typeof customAttributeValue === 'string' && COLOR_REGEX.test(customAttributeValue)) {\n style += cssAttributeKey + \":\" + customAttributeValue + \";\";\n delete attribs[customAttributeKey];\n }\n });\n\n if (style) {\n attribs.style = style;\n }\n\n return { tagName: tagName, attribs: attribs };\n }\n};\n\nvar sanitizeHtmlParams = {\n allowedTags: ['font', // custom to matrix for IRC-style font coloring\n 'del', // for markdown\n 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'sup', 'sub', 'nl', 'li', 'b', 'i', 'u', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre', 'span', 'img'],\n allowedAttributes: {\n // custom ones first:\n font: ['color', 'data-mx-bg-color', 'data-mx-color', 'style'], // custom to matrix\n span: ['data-mx-bg-color', 'data-mx-color', 'style'], // custom to matrix\n a: ['href', 'name', 'target', 'rel'], // remote target: custom to matrix\n img: ['src', 'width', 'height', 'alt', 'title'],\n ol: ['start'],\n code: ['class'] // We don't actually allow all classes, we filter them in transformTags\n },\n // Lots of these won't come up by default because we don't allow them\n selfClosing: ['img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta'],\n // URL schemes we permit\n allowedSchemes: PERMITTED_URL_SCHEMES,\n\n allowProtocolRelative: false,\n transformTags: transformTags\n};\n\n// this is the same as the above except with less rewriting\nvar composerSanitizeHtmlParams = (0, _assign2.default)({}, sanitizeHtmlParams);\ncomposerSanitizeHtmlParams.transformTags = {\n 'code': transformTags['code'],\n '*': transformTags['*']\n};\n\nvar BaseHighlighter = function () {\n function BaseHighlighter(highlightClass, highlightLink) {\n (0, _classCallCheck3.default)(this, BaseHighlighter);\n\n this.highlightClass = highlightClass;\n this.highlightLink = highlightLink;\n }\n\n /**\n * apply the highlights to a section of text\n *\n * @param {string} safeSnippet The snippet of text to apply the highlights\n * to.\n * @param {string[]} safeHighlights A list of substrings to highlight,\n * sorted by descending length.\n *\n * returns a list of results (strings for HtmlHighligher, react nodes for\n * TextHighlighter).\n */\n\n\n (0, _createClass3.default)(BaseHighlighter, [{\n key: 'applyHighlights',\n value: function applyHighlights(safeSnippet, safeHighlights) {\n var lastOffset = 0;\n var offset = void 0;\n var nodes = [];\n\n var safeHighlight = safeHighlights[0];\n while ((offset = safeSnippet.toLowerCase().indexOf(safeHighlight.toLowerCase(), lastOffset)) >= 0) {\n // handle preamble\n if (offset > lastOffset) {\n var subSnippet = safeSnippet.substring(lastOffset, offset);\n nodes = nodes.concat(this._applySubHighlights(subSnippet, safeHighlights));\n }\n\n // do highlight. use the original string rather than safeHighlight\n // to preserve the original casing.\n var endOffset = offset + safeHighlight.length;\n nodes.push(this._processSnippet(safeSnippet.substring(offset, endOffset), true));\n\n lastOffset = endOffset;\n }\n\n // handle postamble\n if (lastOffset !== safeSnippet.length) {\n subSnippet = safeSnippet.substring(lastOffset, undefined);\n nodes = nodes.concat(this._applySubHighlights(subSnippet, safeHighlights));\n }\n return nodes;\n }\n }, {\n key: '_applySubHighlights',\n value: function _applySubHighlights(safeSnippet, safeHighlights) {\n if (safeHighlights[1]) {\n // recurse into this range to check for the next set of highlight matches\n return this.applyHighlights(safeSnippet, safeHighlights.slice(1));\n } else {\n // no more highlights to be found, just return the unhighlighted string\n return [this._processSnippet(safeSnippet, false)];\n }\n }\n }]);\n return BaseHighlighter;\n}();\n\nvar HtmlHighlighter = function (_BaseHighlighter) {\n (0, _inherits3.default)(HtmlHighlighter, _BaseHighlighter);\n\n function HtmlHighlighter() {\n (0, _classCallCheck3.default)(this, HtmlHighlighter);\n return (0, _possibleConstructorReturn3.default)(this, (HtmlHighlighter.__proto__ || (0, _getPrototypeOf2.default)(HtmlHighlighter)).apply(this, arguments));\n }\n\n (0, _createClass3.default)(HtmlHighlighter, [{\n key: '_processSnippet',\n\n /* highlight the given snippet if required\n *\n * snippet: content of the span; must have been sanitised\n * highlight: true to highlight as a search match\n *\n * returns an HTML string\n */\n value: function _processSnippet(snippet, highlight) {\n if (!highlight) {\n // nothing required here\n return snippet;\n }\n\n var span = \"\" + snippet + \"\";\n\n if (this.highlightLink) {\n span = \"\" + span + \"\";\n }\n return span;\n }\n }]);\n return HtmlHighlighter;\n}(BaseHighlighter);\n\nvar TextHighlighter = function (_BaseHighlighter2) {\n (0, _inherits3.default)(TextHighlighter, _BaseHighlighter2);\n\n function TextHighlighter(highlightClass, highlightLink) {\n (0, _classCallCheck3.default)(this, TextHighlighter);\n\n var _this2 = (0, _possibleConstructorReturn3.default)(this, (TextHighlighter.__proto__ || (0, _getPrototypeOf2.default)(TextHighlighter)).call(this, highlightClass, highlightLink));\n\n _this2._key = 0;\n return _this2;\n }\n\n /* create a node to hold the given content\n *\n * snippet: content of the span\n * highlight: true to highlight as a search match\n *\n * returns a React node\n */\n\n\n (0, _createClass3.default)(TextHighlighter, [{\n key: '_processSnippet',\n value: function _processSnippet(snippet, highlight) {\n var key = this._key++;\n\n var node = _react2.default.createElement(\n 'span',\n { key: key, className: highlight ? this.highlightClass : null },\n snippet\n );\n\n if (highlight && this.highlightLink) {\n node = _react2.default.createElement(\n 'a',\n { key: key, href: this.highlightLink },\n node\n );\n }\n\n return node;\n }\n }]);\n return TextHighlighter;\n}(BaseHighlighter);\n\n/* turn a matrix event body into html\n *\n * content: 'content' of the MatrixEvent\n *\n * highlights: optional list of words to highlight, ordered by longest word first\n *\n * opts.highlightLink: optional href to add to highlighted words\n * opts.disableBigEmoji: optional argument to disable the big emoji class.\n * opts.stripReplyFallback: optional argument specifying the event is a reply and so fallback needs removing\n * opts.returnString: return an HTML string rather than JSX elements\n * opts.forComposerQuote: optional param to lessen the url rewriting done by sanitization, for quoting into composer\n */\n\n\nfunction bodyToHtml(content, highlights) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n var isHtmlMessage = content.format === \"org.matrix.custom.html\" && content.formatted_body;\n var bodyHasEmoji = false;\n\n var sanitizeParams = sanitizeHtmlParams;\n if (opts.forComposerQuote) {\n sanitizeParams = composerSanitizeHtmlParams;\n }\n\n var strippedBody = void 0;\n var safeBody = void 0;\n var isDisplayedWithHtml = void 0;\n // XXX: We sanitize the HTML whilst also highlighting its text nodes, to avoid accidentally trying\n // to highlight HTML tags themselves. However, this does mean that we don't highlight textnodes which\n // are interrupted by HTML tags (not that we did before) - e.g. foobar won't get highlighted\n // by an attempt to search for 'foobar'. Then again, the search query probably wouldn't work either\n try {\n if (highlights && highlights.length > 0) {\n var highlighter = new HtmlHighlighter(\"mx_EventTile_searchHighlight\", opts.highlightLink);\n var safeHighlights = highlights.map(function (highlight) {\n return (0, _sanitizeHtml2.default)(highlight, sanitizeParams);\n });\n // XXX: hacky bodge to temporarily apply a textFilter to the sanitizeParams structure.\n sanitizeParams.textFilter = function (safeText) {\n return highlighter.applyHighlights(safeText, safeHighlights).join('');\n };\n }\n\n var formattedBody = content.formatted_body;\n if (opts.stripReplyFallback && formattedBody) formattedBody = _ReplyThread2.default.stripHTMLReply(formattedBody);\n strippedBody = opts.stripReplyFallback ? _ReplyThread2.default.stripPlainReply(content.body) : content.body;\n\n bodyHasEmoji = containsEmoji(isHtmlMessage ? formattedBody : content.body);\n\n // Only generate safeBody if the message was sent as org.matrix.custom.html\n if (isHtmlMessage) {\n isDisplayedWithHtml = true;\n safeBody = (0, _sanitizeHtml2.default)(formattedBody, sanitizeParams);\n }\n } finally {\n delete sanitizeParams.textFilter;\n }\n\n if (opts.returnString) {\n return isDisplayedWithHtml ? safeBody : strippedBody;\n }\n\n var emojiBody = false;\n if (!opts.disableBigEmoji && bodyHasEmoji) {\n var contentBodyTrimmed = strippedBody !== undefined ? strippedBody.trim() : '';\n\n // Ignore spaces in body text. Emojis with spaces in between should\n // still be counted as purely emoji messages.\n contentBodyTrimmed = contentBodyTrimmed.replace(WHITESPACE_REGEX, '');\n\n // Remove zero width joiner characters from emoji messages. This ensures\n // that emojis that are made up of multiple unicode characters are still\n // presented as large.\n contentBodyTrimmed = contentBodyTrimmed.replace(ZWJ_REGEX, '');\n\n var match = BIGEMOJI_REGEX.exec(contentBodyTrimmed);\n emojiBody = match && match[0] && match[0].length === contentBodyTrimmed.length && (\n // Prevent user pills expanding for users with only emoji in\n // their username\n content.formatted_body == undefined || !content.formatted_body.includes(\"https://matrix.to/\"));\n }\n\n var className = (0, _classnames2.default)({\n 'mx_EventTile_body': true,\n 'mx_EventTile_bigEmoji': emojiBody,\n 'markdown-body': isHtmlMessage && !emojiBody\n });\n\n return isDisplayedWithHtml ? _react2.default.createElement('span', { key: 'body', className: className, dangerouslySetInnerHTML: { __html: safeBody }, dir: 'auto' }) : _react2.default.createElement(\n 'span',\n { key: 'body', className: className, dir: 'auto' },\n strippedBody\n );\n}\n\n/**\n * Linkifies the given string. This is a wrapper around 'linkifyjs/string'.\n *\n * @param {string} str\n * @returns {string}\n */\nfunction linkifyString(str) {\n return (0, _string2.default)(str);\n}\n\n/**\n * Linkifies the given DOM element. This is a wrapper around 'linkifyjs/element'.\n *\n * @param {object} element DOM element to linkify\n * @param {object} [options] Options for linkifyElement. Default: linkifyMatrix.options\n * @returns {object}\n */\nfunction linkifyElement(element) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _linkifyMatrix2.default.options;\n\n return (0, _element2.default)(element, options);\n}\n\n/**\n * Linkify the given string and sanitize the HTML afterwards.\n *\n * @param {string} dirtyHtml The HTML string to sanitize and linkify\n * @returns {string}\n */\nfunction linkifyAndSanitizeHtml(dirtyHtml) {\n return (0, _sanitizeHtml2.default)(linkifyString(dirtyHtml), sanitizeHtmlParams);\n}\n//# sourceMappingURL=HtmlUtils.js.map","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nmodule.exports = isArray;\n","module.exports = __webpack_public_path__ + \"img/cancel.4b9715b.svg\";","// 7.1.1 ToPrimitive(input [, PreferredType])\nvar isObject = require('./_is-object');\n// instead of the ES6 spec version, we didn't implement @@toPrimitive case\n// and the second argument - flag - preferred type is a string\nmodule.exports = function (it, S) {\n if (!isObject(it)) return it;\n var fn, val;\n if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;\n if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;\n if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;\n throw TypeError(\"Can't convert object to primitive value\");\n};\n","// 7.2.1 RequireObjectCoercible(argument)\nmodule.exports = function (it) {\n if (it == undefined) throw TypeError(\"Can't call method on \" + it);\n return it;\n};\n","// most Object methods by ES6 should accept primitives\nvar $export = require('./_export');\nvar core = require('./_core');\nvar fails = require('./_fails');\nmodule.exports = function (KEY, exec) {\n var fn = (core.Object || {})[KEY] || Object[KEY];\n var exp = {};\n exp[KEY] = exec(fn);\n $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);\n};\n","// 0 -> Array#forEach\n// 1 -> Array#map\n// 2 -> Array#filter\n// 3 -> Array#some\n// 4 -> Array#every\n// 5 -> Array#find\n// 6 -> Array#findIndex\nvar ctx = require('./_ctx');\nvar IObject = require('./_iobject');\nvar toObject = require('./_to-object');\nvar toLength = require('./_to-length');\nvar asc = require('./_array-species-create');\nmodule.exports = function (TYPE, $create) {\n var IS_MAP = TYPE == 1;\n var IS_FILTER = TYPE == 2;\n var IS_SOME = TYPE == 3;\n var IS_EVERY = TYPE == 4;\n var IS_FIND_INDEX = TYPE == 6;\n var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;\n var create = $create || asc;\n return function ($this, callbackfn, that) {\n var O = toObject($this);\n var self = IObject(O);\n var f = ctx(callbackfn, that, 3);\n var length = toLength(self.length);\n var index = 0;\n var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;\n var val, res;\n for (;length > index; index++) if (NO_HOLES || index in self) {\n val = self[index];\n res = f(val, index, O);\n if (TYPE) {\n if (IS_MAP) result[index] = res; // map\n else if (res) switch (TYPE) {\n case 3: return true; // some\n case 5: return val; // find\n case 6: return index; // findIndex\n case 2: result.push(val); // filter\n } else if (IS_EVERY) return false; // every\n }\n }\n return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;\n };\n};\n","// 7.1.4 ToInteger\nvar ceil = Math.ceil;\nvar floor = Math.floor;\nmodule.exports = function (it) {\n return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);\n};\n","// 7.2.1 RequireObjectCoercible(argument)\nmodule.exports = function (it) {\n if (it == undefined) throw TypeError(\"Can't call method on \" + it);\n return it;\n};\n","require('./es6.array.iterator');\nvar global = require('./_global');\nvar hide = require('./_hide');\nvar Iterators = require('./_iterators');\nvar TO_STRING_TAG = require('./_wks')('toStringTag');\n\nvar DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' +\n 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' +\n 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' +\n 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' +\n 'TextTrackList,TouchList').split(',');\n\nfor (var i = 0; i < DOMIterables.length; i++) {\n var NAME = DOMIterables[i];\n var Collection = global[NAME];\n var proto = Collection && Collection.prototype;\n if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);\n Iterators[NAME] = Iterators.Array;\n}\n","/*\nCopyright 2015, 2016 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\"use strict\";\n\n/**\n * This is an internal module. See {@link MatrixEvent} and {@link RoomEvent} for\n * the public classes.\n * @module models/event\n */\n\nvar _regenerator = require('babel-runtime/regenerator');\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _bluebird = require('bluebird');\n\nvar _bluebird2 = _interopRequireDefault(_bluebird);\n\nvar _events = require('events');\n\nvar _utils = require('../utils.js');\n\nvar _utils2 = _interopRequireDefault(_utils);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Enum for event statuses.\n * @readonly\n * @enum {string}\n */\nmodule.exports.EventStatus = {\n /** The event was not sent and will no longer be retried. */\n NOT_SENT: \"not_sent\",\n\n /** The message is being encrypted */\n ENCRYPTING: \"encrypting\",\n\n /** The event is in the process of being sent. */\n SENDING: \"sending\",\n /** The event is in a queue waiting to be sent. */\n QUEUED: \"queued\",\n /** The event has been sent to the server, but we have not yet received the\n * echo. */\n SENT: \"sent\",\n\n /** The event was cancelled before it was successfully sent. */\n CANCELLED: \"cancelled\"\n};\n\nvar interns = {};\nfunction intern(str) {\n if (!interns[str]) {\n interns[str] = str;\n }\n return interns[str];\n}\n\n/**\n * Construct a Matrix Event object\n * @constructor\n *\n * @param {Object} event The raw event to be wrapped in this DAO\n *\n * @prop {Object} event The raw (possibly encrypted) event. Do not access\n * this property directly unless you absolutely have to. Prefer the getter\n * methods defined on this class. Using the getter methods shields your app\n * from changes to event JSON between Matrix versions.\n *\n * @prop {RoomMember} sender The room member who sent this event, or null e.g.\n * this is a presence event. This is only guaranteed to be set for events that\n * appear in a timeline, ie. do not guarantee that it will be set on state\n * events.\n * @prop {RoomMember} target The room member who is the target of this event, e.g.\n * the invitee, the person being banned, etc.\n * @prop {EventStatus} status The sending status of the event.\n * @prop {Error} error most recent error associated with sending the event, if any\n * @prop {boolean} forwardLooking True if this event is 'forward looking', meaning\n * that getDirectionalContent() will return event.content and not event.prev_content.\n * Default: true. This property is experimental and may change.\n */\nmodule.exports.MatrixEvent = function MatrixEvent(event) {\n // intern the values of matrix events to force share strings and reduce the\n // amount of needless string duplication. This can save moderate amounts of\n // memory (~10% on a 350MB heap).\n // 'membership' at the event level (rather than the content level) is a legacy\n // field that Riot never otherwise looks at, but it will still take up a lot\n // of space if we don't intern it.\n [\"state_key\", \"type\", \"sender\", \"room_id\", \"membership\"].forEach(function (prop) {\n if (!event[prop]) {\n return;\n }\n event[prop] = intern(event[prop]);\n });\n\n [\"membership\", \"avatar_url\", \"displayname\"].forEach(function (prop) {\n if (!event.content || !event.content[prop]) {\n return;\n }\n event.content[prop] = intern(event.content[prop]);\n });\n\n [\"rel_type\"].forEach(function (prop) {\n if (!event.content || !event.content[\"m.relates_to\"] || !event.content[\"m.relates_to\"][prop]) {\n return;\n }\n event.content[\"m.relates_to\"][prop] = intern(event.content[\"m.relates_to\"][prop]);\n });\n\n this.event = event || {};\n\n this.sender = null;\n this.target = null;\n this.status = null;\n this.error = null;\n this.forwardLooking = true;\n this._pushActions = null;\n this._replacingEvent = null;\n\n this._clearEvent = {};\n\n /* curve25519 key which we believe belongs to the sender of the event. See\n * getSenderKey()\n */\n this._senderCurve25519Key = null;\n\n /* ed25519 key which the sender of this event (for olm) or the creator of\n * the megolm session (for megolm) claims to own. See getClaimedEd25519Key()\n */\n this._claimedEd25519Key = null;\n\n /* curve25519 keys of devices involved in telling us about the\n * _senderCurve25519Key and _claimedEd25519Key.\n * See getForwardingCurve25519KeyChain().\n */\n this._forwardingCurve25519KeyChain = [];\n\n /* if we have a process decrypting this event, a Promise which resolves\n * when it is finished. Normally null.\n */\n this._decryptionPromise = null;\n\n /* flag to indicate if we should retry decrypting this event after the\n * first attempt (eg, we have received new data which means that a second\n * attempt may succeed)\n */\n this._retryDecryption = false;\n};\n_utils2.default.inherits(module.exports.MatrixEvent, _events.EventEmitter);\n\n_utils2.default.extend(module.exports.MatrixEvent.prototype, {\n\n /**\n * Get the event_id for this event.\n * @return {string} The event ID, e.g. $143350589368169JsLZx:localhost\n *
\n */\n getId: function getId() {\n return this.event.event_id;\n },\n\n /**\n * Get the user_id for this event.\n * @return {string} The user ID, e.g. @alice:matrix.org
\n */\n getSender: function getSender() {\n return this.event.sender || this.event.user_id; // v2 / v1\n },\n\n /**\n * Get the (decrypted, if necessary) type of event.\n *\n * @return {string} The event type, e.g. m.room.message
\n */\n getType: function getType() {\n return this._clearEvent.type || this.event.type;\n },\n\n /**\n * Get the (possibly encrypted) type of the event that will be sent to the\n * homeserver.\n *\n * @return {string} The event type.\n */\n getWireType: function getWireType() {\n return this.event.type;\n },\n\n /**\n * Get the room_id for this event. This will return undefined
\n * for m.presence
events.\n * @return {string} The room ID, e.g. !cURbafjkfsMDVwdRDQ:matrix.org\n *
\n */\n getRoomId: function getRoomId() {\n return this.event.room_id;\n },\n\n /**\n * Get the timestamp of this event.\n * @return {Number} The event timestamp, e.g. 1433502692297
\n */\n getTs: function getTs() {\n return this.event.origin_server_ts;\n },\n\n /**\n * Get the timestamp of this event, as a Date object.\n * @return {Date} The event date, e.g. new Date(1433502692297)
\n */\n getDate: function getDate() {\n return this.event.origin_server_ts ? new Date(this.event.origin_server_ts) : null;\n },\n\n /**\n * Get the (decrypted, if necessary) event content JSON, even if the event\n * was replaced by another event.\n *\n * @return {Object} The event content JSON, or an empty object.\n */\n getOriginalContent: function getOriginalContent() {\n return this._clearEvent.content || this.event.content || {};\n },\n\n /**\n * Get the (decrypted, if necessary) event content JSON,\n * or the content from the replacing event, if any.\n * See `makeReplaced`.\n *\n * @return {Object} The event content JSON, or an empty object.\n */\n getContent: function getContent() {\n if (this._replacingEvent) {\n return this._replacingEvent.getContent()[\"m.new_content\"] || {};\n } else {\n return this.getOriginalContent();\n }\n },\n\n /**\n * Get the (possibly encrypted) event content JSON that will be sent to the\n * homeserver.\n *\n * @return {Object} The event content JSON, or an empty object.\n */\n getWireContent: function getWireContent() {\n return this.event.content || {};\n },\n\n /**\n * Get the previous event content JSON. This will only return something for\n * state events which exist in the timeline.\n * @return {Object} The previous event content JSON, or an empty object.\n */\n getPrevContent: function getPrevContent() {\n // v2 then v1 then default\n return this.getUnsigned().prev_content || this.event.prev_content || {};\n },\n\n /**\n * Get either 'content' or 'prev_content' depending on if this event is\n * 'forward-looking' or not. This can be modified via event.forwardLooking.\n * In practice, this means we get the chronologically earlier content value\n * for this event (this method should surely be called getEarlierContent)\n * This method is experimental and may change.\n * @return {Object} event.content if this event is forward-looking, else\n * event.prev_content.\n */\n getDirectionalContent: function getDirectionalContent() {\n return this.forwardLooking ? this.getContent() : this.getPrevContent();\n },\n\n /**\n * Get the age of this event. This represents the age of the event when the\n * event arrived at the device, and not the age of the event when this\n * function was called.\n * @return {Number} The age of this event in milliseconds.\n */\n getAge: function getAge() {\n return this.getUnsigned().age || this.event.age; // v2 / v1\n },\n\n /**\n * Get the event state_key if it has one. This will return undefined\n *
for message events.\n * @return {string} The event's state_key
.\n */\n getStateKey: function getStateKey() {\n return this.event.state_key;\n },\n\n /**\n * Check if this event is a state event.\n * @return {boolean} True if this is a state event.\n */\n isState: function isState() {\n return this.event.state_key !== undefined;\n },\n\n /**\n * Replace the content of this event with encrypted versions.\n * (This is used when sending an event; it should not be used by applications).\n *\n * @internal\n *\n * @param {string} crypto_type type of the encrypted event - typically\n * \"m.room.encrypted\"\n *\n * @param {object} crypto_content raw 'content' for the encrypted event.\n *\n * @param {string} senderCurve25519Key curve25519 key to record for the\n * sender of this event.\n * See {@link module:models/event.MatrixEvent#getSenderKey}.\n *\n * @param {string} claimedEd25519Key claimed ed25519 key to record for the\n * sender if this event.\n * See {@link module:models/event.MatrixEvent#getClaimedEd25519Key}\n */\n makeEncrypted: function makeEncrypted(crypto_type, crypto_content, senderCurve25519Key, claimedEd25519Key) {\n // keep the plain-text data for 'view source'\n this._clearEvent = {\n type: this.event.type,\n content: this.event.content\n };\n this.event.type = crypto_type;\n this.event.content = crypto_content;\n this._senderCurve25519Key = senderCurve25519Key;\n this._claimedEd25519Key = claimedEd25519Key;\n },\n\n /**\n * Check if this event is currently being decrypted.\n *\n * @return {boolean} True if this event is currently being decrypted, else false.\n */\n isBeingDecrypted: function isBeingDecrypted() {\n return this._decryptionPromise != null;\n },\n\n /**\n * Check if this event is an encrypted event which we failed to decrypt\n *\n * (This implies that we might retry decryption at some point in the future)\n *\n * @return {boolean} True if this event is an encrypted event which we\n * couldn't decrypt.\n */\n isDecryptionFailure: function isDecryptionFailure() {\n return this._clearEvent && this._clearEvent.content && this._clearEvent.content.msgtype === \"m.bad.encrypted\";\n },\n\n /**\n * Start the process of trying to decrypt this event.\n *\n * (This is used within the SDK: it isn't intended for use by applications)\n *\n * @internal\n *\n * @param {module:crypto} crypto crypto module\n *\n * @returns {Promise} promise which resolves (to undefined) when the decryption\n * attempt is completed.\n */\n attemptDecryption: function () {\n var _ref = (0, _bluebird.method)(function (crypto) {\n // start with a couple of sanity checks.\n if (!this.isEncrypted()) {\n throw new Error(\"Attempt to decrypt event which isn't encrypted\");\n }\n\n if (this._clearEvent && this._clearEvent.content && this._clearEvent.content.msgtype !== \"m.bad.encrypted\") {\n // we may want to just ignore this? let's start with rejecting it.\n throw new Error(\"Attempt to decrypt event which has already been encrypted\");\n }\n\n // if we already have a decryption attempt in progress, then it may\n // fail because it was using outdated info. We now have reason to\n // succeed where it failed before, but we don't want to have multiple\n // attempts going at the same time, so just set a flag that says we have\n // new info.\n //\n if (this._decryptionPromise) {\n console.log('Event ' + this.getId() + ' already being decrypted; queueing a retry');\n this._retryDecryption = true;\n return this._decryptionPromise;\n }\n\n this._decryptionPromise = this._decryptionLoop(crypto);\n return this._decryptionPromise;\n });\n\n function attemptDecryption(_x) {\n return _ref.apply(this, arguments);\n }\n\n return attemptDecryption;\n }(),\n\n /**\n * Cancel any room key request for this event and resend another.\n *\n * @param {module:crypto} crypto crypto module\n * @param {string} userId the user who received this event\n *\n * @returns {Promise} a promise that resolves when the request is queued\n */\n cancelAndResendKeyRequest: function cancelAndResendKeyRequest(crypto, userId) {\n var wireContent = this.getWireContent();\n return crypto.requestRoomKey({\n algorithm: wireContent.algorithm,\n room_id: this.getRoomId(),\n session_id: wireContent.session_id,\n sender_key: wireContent.sender_key\n }, this.getKeyRequestRecipients(userId), true);\n },\n\n /**\n * Calculate the recipients for keyshare requests.\n *\n * @param {string} userId the user who received this event.\n *\n * @returns {Array} array of recipients\n */\n getKeyRequestRecipients: function getKeyRequestRecipients(userId) {\n // send the request to all of our own devices, and the\n // original sending device if it wasn't us.\n var wireContent = this.getWireContent();\n var recipients = [{\n userId: userId, deviceId: '*'\n }];\n var sender = this.getSender();\n if (sender !== userId) {\n recipients.push({\n userId: sender, deviceId: wireContent.device_id\n });\n }\n return recipients;\n },\n\n _decryptionLoop: function () {\n var _ref2 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee(crypto) {\n var res, err;\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n _context.next = 2;\n return (0, _bluebird.resolve)(_bluebird2.default.resolve());\n\n case 2:\n if (!true) {\n _context.next = 37;\n break;\n }\n\n this._retryDecryption = false;\n\n res = void 0;\n err = void 0;\n _context.prev = 6;\n\n if (crypto) {\n _context.next = 11;\n break;\n }\n\n res = this._badEncryptedMessage(\"Encryption not enabled\");\n _context.next = 14;\n break;\n\n case 11:\n _context.next = 13;\n return (0, _bluebird.resolve)(crypto.decryptEvent(this));\n\n case 13:\n res = _context.sent;\n\n case 14:\n _context.next = 29;\n break;\n\n case 16:\n _context.prev = 16;\n _context.t0 = _context['catch'](6);\n\n if (!(_context.t0.name !== \"DecryptionError\")) {\n _context.next = 23;\n break;\n }\n\n // not a decryption error: log the whole exception as an error\n // (and don't bother with a retry)\n console.error('Error decrypting event (id=' + this.getId() + '): ' + (_context.t0.stack || _context.t0));\n this._decryptionPromise = null;\n this._retryDecryption = false;\n return _context.abrupt('return');\n\n case 23:\n\n err = _context.t0;\n\n // see if we have a retry queued.\n //\n // NB: make sure to keep this check in the same tick of the\n // event loop as `_decryptionPromise = null` below - otherwise we\n // risk a race:\n //\n // * A: we check _retryDecryption here and see that it is\n // false\n // * B: we get a second call to attemptDecryption, which sees\n // that _decryptionPromise is set so sets\n // _retryDecryption\n // * A: we continue below, clear _decryptionPromise, and\n // never do the retry.\n //\n\n if (!this._retryDecryption) {\n _context.next = 27;\n break;\n }\n\n // decryption error, but we have a retry queued.\n console.log('Got error decrypting event (id=' + this.getId() + ': ' + (_context.t0 + '), but retrying'));\n return _context.abrupt('continue', 2);\n\n case 27:\n\n // decryption error, no retries queued. Warn about the error and\n // set it to m.bad.encrypted.\n console.warn('Error decrypting event (id=' + this.getId() + '): ' + _context.t0.detailedString);\n\n res = this._badEncryptedMessage(_context.t0.message);\n\n case 29:\n\n // at this point, we've either successfully decrypted the event, or have given up\n // (and set res to a 'badEncryptedMessage'). Either way, we can now set the\n // cleartext of the event and raise Event.decrypted.\n //\n // make sure we clear '_decryptionPromise' before sending the 'Event.decrypted' event,\n // otherwise the app will be confused to see `isBeingDecrypted` still set when\n // there isn't an `Event.decrypted` on the way.\n //\n // see also notes on _retryDecryption above.\n //\n this._decryptionPromise = null;\n this._retryDecryption = false;\n this._setClearData(res);\n\n // Before we emit the event, clear the push actions so that they can be recalculated\n // by relevant code. We do this because the clear event has now changed, making it\n // so that existing rules can be re-run over the applicable properties. Stuff like\n // highlighting when the user's name is mentioned rely on this happening. We also want\n // to set the push actions before emitting so that any notification listeners don't\n // pick up the wrong contents.\n this.setPushActions(null);\n\n this.emit(\"Event.decrypted\", this, err);\n\n return _context.abrupt('return');\n\n case 37:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, this, [[6, 16]]);\n }));\n\n function _decryptionLoop(_x2) {\n return _ref2.apply(this, arguments);\n }\n\n return _decryptionLoop;\n }(),\n\n _badEncryptedMessage: function _badEncryptedMessage(reason) {\n return {\n clearEvent: {\n type: \"m.room.message\",\n content: {\n msgtype: \"m.bad.encrypted\",\n body: \"** Unable to decrypt: \" + reason + \" **\"\n }\n }\n };\n },\n\n /**\n * Update the cleartext data on this event.\n *\n * (This is used after decrypting an event; it should not be used by applications).\n *\n * @internal\n *\n * @fires module:models/event.MatrixEvent#\"Event.decrypted\"\n *\n * @param {module:crypto~EventDecryptionResult} decryptionResult\n * the decryption result, including the plaintext and some key info\n */\n _setClearData: function _setClearData(decryptionResult) {\n this._clearEvent = decryptionResult.clearEvent;\n this._senderCurve25519Key = decryptionResult.senderCurve25519Key || null;\n this._claimedEd25519Key = decryptionResult.claimedEd25519Key || null;\n this._forwardingCurve25519KeyChain = decryptionResult.forwardingCurve25519KeyChain || [];\n },\n\n /**\n * Gets the cleartext content for this event. If the event is not encrypted,\n * or encryption has not been completed, this will return null.\n *\n * @returns {Object} The cleartext (decrypted) content for the event\n */\n getClearContent: function getClearContent() {\n var ev = this._clearEvent;\n return ev && ev.content ? ev.content : null;\n },\n\n /**\n * Check if the event is encrypted.\n * @return {boolean} True if this event is encrypted.\n */\n isEncrypted: function isEncrypted() {\n return this.event.type === \"m.room.encrypted\";\n },\n\n /**\n * The curve25519 key for the device that we think sent this event\n *\n * For an Olm-encrypted event, this is inferred directly from the DH\n * exchange at the start of the session: the curve25519 key is involved in\n * the DH exchange, so only a device which holds the private part of that\n * key can establish such a session.\n *\n * For a megolm-encrypted event, it is inferred from the Olm message which\n * established the megolm session\n *\n * @return {string}\n */\n getSenderKey: function getSenderKey() {\n return this._senderCurve25519Key;\n },\n\n /**\n * The additional keys the sender of this encrypted event claims to possess.\n *\n * Just a wrapper for #getClaimedEd25519Key (q.v.)\n *\n * @return {Object}\n */\n getKeysClaimed: function getKeysClaimed() {\n return {\n ed25519: this._claimedEd25519Key\n };\n },\n\n /**\n * Get the ed25519 the sender of this event claims to own.\n *\n * For Olm messages, this claim is encoded directly in the plaintext of the\n * event itself. For megolm messages, it is implied by the m.room_key event\n * which established the megolm session.\n *\n * Until we download the device list of the sender, it's just a claim: the\n * device list gives a proof that the owner of the curve25519 key used for\n * this event (and returned by #getSenderKey) also owns the ed25519 key by\n * signing the public curve25519 key with the ed25519 key.\n *\n * In general, applications should not use this method directly, but should\n * instead use MatrixClient.getEventSenderDeviceInfo.\n *\n * @return {string}\n */\n getClaimedEd25519Key: function getClaimedEd25519Key() {\n return this._claimedEd25519Key;\n },\n\n /**\n * Get the curve25519 keys of the devices which were involved in telling us\n * about the claimedEd25519Key and sender curve25519 key.\n *\n * Normally this will be empty, but in the case of a forwarded megolm\n * session, the sender keys are sent to us by another device (the forwarding\n * device), which we need to trust to do this. In that case, the result will\n * be a list consisting of one entry.\n *\n * If the device that sent us the key (A) got it from another device which\n * it wasn't prepared to vouch for (B), the result will be [A, B]. And so on.\n *\n * @return {string[]} base64-encoded curve25519 keys, from oldest to newest.\n */\n getForwardingCurve25519KeyChain: function getForwardingCurve25519KeyChain() {\n return this._forwardingCurve25519KeyChain;\n },\n\n getUnsigned: function getUnsigned() {\n return this.event.unsigned || {};\n },\n\n /**\n * Update the content of an event in the same way it would be by the server\n * if it were redacted before it was sent to us\n *\n * @param {module:models/event.MatrixEvent} redaction_event\n * event causing the redaction\n */\n makeRedacted: function makeRedacted(redaction_event) {\n // quick sanity-check\n if (!redaction_event.event) {\n throw new Error(\"invalid redaction_event in makeRedacted\");\n }\n\n this.emit(\"Event.beforeRedaction\", this, redaction_event);\n\n this._replacingEvent = null;\n // we attempt to replicate what we would see from the server if\n // the event had been redacted before we saw it.\n //\n // The server removes (most of) the content of the event, and adds a\n // \"redacted_because\" key to the unsigned section containing the\n // redacted event.\n if (!this.event.unsigned) {\n this.event.unsigned = {};\n }\n this.event.unsigned.redacted_because = redaction_event.event;\n\n var key = void 0;\n for (key in this.event) {\n if (!this.event.hasOwnProperty(key)) {\n continue;\n }\n if (!_REDACT_KEEP_KEY_MAP[key]) {\n delete this.event[key];\n }\n }\n\n var keeps = _REDACT_KEEP_CONTENT_MAP[this.getType()] || {};\n var content = this.getContent();\n for (key in content) {\n if (!content.hasOwnProperty(key)) {\n continue;\n }\n if (!keeps[key]) {\n delete content[key];\n }\n }\n },\n\n /**\n * Check if this event has been redacted\n *\n * @return {boolean} True if this event has been redacted\n */\n isRedacted: function isRedacted() {\n return Boolean(this.getUnsigned().redacted_because);\n },\n\n /**\n * Get the push actions, if known, for this event\n *\n * @return {?Object} push actions\n */\n getPushActions: function getPushActions() {\n return this._pushActions;\n },\n\n /**\n * Set the push actions for this event.\n *\n * @param {Object} pushActions push actions\n */\n setPushActions: function setPushActions(pushActions) {\n this._pushActions = pushActions;\n },\n\n /**\n * Replace the `event` property and recalculate any properties based on it.\n * @param {Object} event the object to assign to the `event` property\n */\n handleRemoteEcho: function handleRemoteEcho(event) {\n this.event = event;\n // successfully sent.\n this.setStatus(null);\n },\n\n /**\n * Whether the event is in any phase of sending, send failure, waiting for\n * remote echo, etc.\n *\n * @return {boolean}\n */\n isSending: function isSending() {\n return !!this.status;\n },\n\n\n /**\n * Update the event's sending status and emit an event as well.\n *\n * @param {String} status The new status\n */\n setStatus: function setStatus(status) {\n this.status = status;\n this.emit(\"Event.status\", this, status);\n },\n\n\n /**\n * Get whether the event is a relation event, and of a given type if\n * `relType` is passed in.\n *\n * @param {string?} relType if given, checks that the relation is of the\n * given type\n * @return {boolean}\n */\n isRelation: function isRelation() {\n var relType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;\n\n // Relation info is lifted out of the encrypted content when sent to\n // encrypted rooms, so we have to check `getWireContent` for this.\n var content = this.getWireContent();\n var relation = content && content[\"m.relates_to\"];\n return relation && relation.rel_type && relation.event_id && (relType && relation.rel_type === relType || !relType);\n },\n\n\n /**\n * Get relation info for the event, if any.\n *\n * @return {Object}\n */\n getRelation: function getRelation() {\n if (!this.isRelation()) {\n return null;\n }\n return this.getWireContent()[\"m.relates_to\"];\n },\n\n\n /**\n * Set an event that replaces the content of this event, through an m.replace relation.\n *\n * @param {MatrixEvent?} newEvent the event with the replacing content, if any.\n */\n makeReplaced: function makeReplaced(newEvent) {\n if (this.isRedacted()) {\n return;\n }\n if (this._replacingEvent !== newEvent) {\n this._replacingEvent = newEvent;\n this.emit(\"Event.replaced\", this);\n }\n },\n\n\n /**\n * Returns the status of the event, or the replacing event in case `makeReplace` has been called.\n *\n * @return {EventStatus}\n */\n replacementOrOwnStatus: function replacementOrOwnStatus() {\n if (this._replacingEvent) {\n return this._replacingEvent.status;\n } else {\n return this.status;\n }\n },\n\n\n /**\n * Returns the event ID of the event replacing the content of this event, if any.\n *\n * @return {string?}\n */\n replacingEventId: function replacingEventId() {\n return this._replacingEvent && this._replacingEvent.getId();\n },\n\n\n /**\n * Returns the event replacing the content of this event, if any.\n *\n * @return {MatrixEvent?}\n */\n replacingEvent: function replacingEvent() {\n return this._replacingEvent;\n },\n\n\n /**\n * Summarise the event as JSON for debugging. If encrypted, include both the\n * decrypted and encrypted view of the event. This is named `toJSON` for use\n * with `JSON.stringify` which checks objects for functions named `toJSON`\n * and will call them to customise the output if they are defined.\n *\n * @return {Object}\n */\n toJSON: function toJSON() {\n var event = {\n type: this.getType(),\n sender: this.getSender(),\n content: this.getContent(),\n event_id: this.getId(),\n origin_server_ts: this.getTs(),\n unsigned: this.getUnsigned(),\n room_id: this.getRoomId()\n };\n\n if (!this.isEncrypted()) {\n return event;\n }\n\n return {\n decrypted: event,\n encrypted: this.event\n };\n }\n});\n\n/* _REDACT_KEEP_KEY_MAP gives the keys we keep when an event is redacted\n *\n * This is specified here:\n * http://matrix.org/speculator/spec/HEAD/client_server/unstable.html#redactions\n *\n * Also:\n * - We keep 'unsigned' since that is created by the local server\n * - We keep user_id for backwards-compat with v1\n */\nvar _REDACT_KEEP_KEY_MAP = ['event_id', 'type', 'room_id', 'user_id', 'sender', 'state_key', 'prev_state', 'content', 'unsigned', 'origin_server_ts'].reduce(function (ret, val) {\n ret[val] = 1;return ret;\n}, {});\n\n// a map from event type to the .content keys we keep when an event is redacted\nvar _REDACT_KEEP_CONTENT_MAP = {\n 'm.room.member': { 'membership': 1 },\n 'm.room.create': { 'creator': 1 },\n 'm.room.join_rules': { 'join_rule': 1 },\n 'm.room.power_levels': { 'ban': 1, 'events': 1, 'events_default': 1,\n 'kick': 1, 'redact': 1, 'state_default': 1,\n 'users': 1, 'users_default': 1\n },\n 'm.room.aliases': { 'aliases': 1 }\n};\n\n/**\n * Fires when an event is decrypted\n *\n * @event module:models/event.MatrixEvent#\"Event.decrypted\"\n *\n * @param {module:models/event.MatrixEvent} event\n * The matrix event which has been decrypted\n * @param {module:crypto/algorithms/base.DecryptionError?} err\n * The error that occured during decryption, or `undefined` if no\n * error occured.\n */\n//# sourceMappingURL=event.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nvar _getIterator2 = require('babel-runtime/core-js/get-iterator');\n\nvar _getIterator3 = _interopRequireDefault(_getIterator2);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _MatrixClientPeg = require('../MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _uniq2 = require('lodash/uniq');\n\nvar _uniq3 = _interopRequireDefault(_uniq2);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Class that takes a Matrix Client and flips the m.direct map\n * so the operation of mapping a room ID to which user it's a DM\n * with can be performed efficiently.\n *\n * With 'start', this can also keep itself up to date over time.\n */\n/*\nCopyright 2016 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar DMRoomMap = function () {\n function DMRoomMap(matrixClient) {\n (0, _classCallCheck3.default)(this, DMRoomMap);\n\n this.matrixClient = matrixClient;\n this.roomToUser = null;\n // see _onAccountData\n this._hasSentOutPatchDirectAccountDataPatch = false;\n\n // XXX: Force-bind the event handler method because it\n // doesn't call it with our object as the 'this'\n // (use a static property arrow function for this when we can)\n this._onAccountData = this._onAccountData.bind(this);\n\n var mDirectEvent = matrixClient.getAccountData('m.direct');\n this.mDirectEvent = mDirectEvent ? mDirectEvent.getContent() : {};\n this.userToRooms = null;\n }\n\n /**\n * Makes and returns a new shared instance that can then be accessed\n * with shared(). This returned instance is not automatically started.\n */\n\n\n (0, _createClass3.default)(DMRoomMap, [{\n key: 'start',\n value: function start() {\n this._populateRoomToUser();\n this.matrixClient.on(\"accountData\", this._onAccountData);\n }\n }, {\n key: 'stop',\n value: function stop() {\n this.matrixClient.removeListener(\"accountData\", this._onAccountData);\n }\n }, {\n key: '_onAccountData',\n value: function _onAccountData(ev) {\n if (ev.getType() == 'm.direct') {\n this.mDirectEvent = this.matrixClient.getAccountData('m.direct').getContent() || {};\n this.userToRooms = null;\n this.roomToUser = null;\n }\n }\n /**\n * some client bug somewhere is causing some DMs to be marked\n * with ourself, not the other user. Fix it by guessing the other user and\n * modifying userToRooms\n */\n\n }, {\n key: '_patchUpSelfDMs',\n value: function _patchUpSelfDMs(userToRooms) {\n var _this = this;\n\n var myUserId = this.matrixClient.getUserId();\n var selfRoomIds = userToRooms[myUserId];\n if (selfRoomIds) {\n // any self-chats that should not be self-chats?\n var guessedUserIdsThatChanged = selfRoomIds.map(function (roomId) {\n var room = _this.matrixClient.getRoom(roomId);\n if (room) {\n var userId = room.guessDMUserId();\n if (userId && userId !== myUserId) {\n return { userId: userId, roomId: roomId };\n }\n }\n }).filter(function (ids) {\n return !!ids;\n }); //filter out\n // these are actually all legit self-chats\n // bail out\n if (!guessedUserIdsThatChanged.length) {\n return false;\n }\n userToRooms[myUserId] = selfRoomIds.filter(function (roomId) {\n return !guessedUserIdsThatChanged.some(function (ids) {\n return ids.roomId === roomId;\n });\n });\n guessedUserIdsThatChanged.forEach(function (_ref) {\n var userId = _ref.userId,\n roomId = _ref.roomId;\n\n var roomIds = userToRooms[userId];\n if (!roomIds) {\n userToRooms[userId] = [roomId];\n } else {\n roomIds.push(roomId);\n userToRooms[userId] = (0, _uniq3.default)(roomIds);\n }\n });\n return true;\n }\n }\n }, {\n key: 'getDMRoomsForUserId',\n value: function getDMRoomsForUserId(userId) {\n // Here, we return the empty list if there are no rooms,\n // since the number of conversations you have with this user is zero.\n return this._getUserToRooms()[userId] || [];\n }\n }, {\n key: 'getUserIdForRoomId',\n value: function getUserIdForRoomId(roomId) {\n if (this.roomToUser == null) {\n // we lazily populate roomToUser so you can use\n // this class just to call getDMRoomsForUserId\n // which doesn't do very much, but is a fairly\n // convenient wrapper and there's no point\n // iterating through the map if getUserIdForRoomId()\n // is never called.\n this._populateRoomToUser();\n }\n // Here, we return undefined if the room is not in the map:\n // the room ID you gave is not a DM room for any user.\n if (this.roomToUser[roomId] === undefined) {\n // no entry? if the room is an invite, look for the is_direct hint.\n var room = this.matrixClient.getRoom(roomId);\n if (room) {\n return room.getDMInviter();\n }\n }\n return this.roomToUser[roomId];\n }\n }, {\n key: '_getUserToRooms',\n value: function _getUserToRooms() {\n if (!this.userToRooms) {\n var userToRooms = this.mDirectEvent;\n var myUserId = this.matrixClient.getUserId();\n var selfDMs = userToRooms[myUserId];\n if (selfDMs && selfDMs.length) {\n var neededPatching = this._patchUpSelfDMs(userToRooms);\n // to avoid multiple devices fighting to correct\n // the account data, only try to send the corrected\n // version once.\n console.warn('Invalid m.direct account data detected ' + '(self-chats that shouldn\\'t be), patching it up.');\n if (neededPatching && !this._hasSentOutPatchDirectAccountDataPatch) {\n this._hasSentOutPatchDirectAccountDataPatch = true;\n this.matrixClient.setAccountData('m.direct', userToRooms);\n }\n }\n this.userToRooms = userToRooms;\n }\n return this.userToRooms;\n }\n }, {\n key: '_populateRoomToUser',\n value: function _populateRoomToUser() {\n this.roomToUser = {};\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = (0, _getIterator3.default)((0, _keys2.default)(this._getUserToRooms())), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var user = _step.value;\n var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n for (var _iterator2 = (0, _getIterator3.default)(this.userToRooms[user]), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n var roomId = _step2.value;\n\n this.roomToUser[roomId] = user;\n }\n } catch (err) {\n _didIteratorError2 = true;\n _iteratorError2 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion2 && _iterator2.return) {\n _iterator2.return();\n }\n } finally {\n if (_didIteratorError2) {\n throw _iteratorError2;\n }\n }\n }\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n }\n }], [{\n key: 'makeShared',\n value: function makeShared() {\n DMRoomMap._sharedInstance = new DMRoomMap(_MatrixClientPeg2.default.get());\n return DMRoomMap._sharedInstance;\n }\n\n /**\n * Returns a shared instance of the class\n * that uses the singleton matrix client\n * The shared instance must be started before use.\n */\n\n }, {\n key: 'shared',\n value: function shared() {\n return DMRoomMap._sharedInstance;\n }\n }]);\n return DMRoomMap;\n}();\n\nexports.default = DMRoomMap;\nmodule.exports = exports['default'];\n//# sourceMappingURL=DMRoomMap.js.map","'use strict';\nif (require('./_descriptors')) {\n var LIBRARY = require('./_library');\n var global = require('./_global');\n var fails = require('./_fails');\n var $export = require('./_export');\n var $typed = require('./_typed');\n var $buffer = require('./_typed-buffer');\n var ctx = require('./_ctx');\n var anInstance = require('./_an-instance');\n var propertyDesc = require('./_property-desc');\n var hide = require('./_hide');\n var redefineAll = require('./_redefine-all');\n var toInteger = require('./_to-integer');\n var toLength = require('./_to-length');\n var toIndex = require('./_to-index');\n var toAbsoluteIndex = require('./_to-absolute-index');\n var toPrimitive = require('./_to-primitive');\n var has = require('./_has');\n var classof = require('./_classof');\n var isObject = require('./_is-object');\n var toObject = require('./_to-object');\n var isArrayIter = require('./_is-array-iter');\n var create = require('./_object-create');\n var getPrototypeOf = require('./_object-gpo');\n var gOPN = require('./_object-gopn').f;\n var getIterFn = require('./core.get-iterator-method');\n var uid = require('./_uid');\n var wks = require('./_wks');\n var createArrayMethod = require('./_array-methods');\n var createArrayIncludes = require('./_array-includes');\n var speciesConstructor = require('./_species-constructor');\n var ArrayIterators = require('./es6.array.iterator');\n var Iterators = require('./_iterators');\n var $iterDetect = require('./_iter-detect');\n var setSpecies = require('./_set-species');\n var arrayFill = require('./_array-fill');\n var arrayCopyWithin = require('./_array-copy-within');\n var $DP = require('./_object-dp');\n var $GOPD = require('./_object-gopd');\n var dP = $DP.f;\n var gOPD = $GOPD.f;\n var RangeError = global.RangeError;\n var TypeError = global.TypeError;\n var Uint8Array = global.Uint8Array;\n var ARRAY_BUFFER = 'ArrayBuffer';\n var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER;\n var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT';\n var PROTOTYPE = 'prototype';\n var ArrayProto = Array[PROTOTYPE];\n var $ArrayBuffer = $buffer.ArrayBuffer;\n var $DataView = $buffer.DataView;\n var arrayForEach = createArrayMethod(0);\n var arrayFilter = createArrayMethod(2);\n var arraySome = createArrayMethod(3);\n var arrayEvery = createArrayMethod(4);\n var arrayFind = createArrayMethod(5);\n var arrayFindIndex = createArrayMethod(6);\n var arrayIncludes = createArrayIncludes(true);\n var arrayIndexOf = createArrayIncludes(false);\n var arrayValues = ArrayIterators.values;\n var arrayKeys = ArrayIterators.keys;\n var arrayEntries = ArrayIterators.entries;\n var arrayLastIndexOf = ArrayProto.lastIndexOf;\n var arrayReduce = ArrayProto.reduce;\n var arrayReduceRight = ArrayProto.reduceRight;\n var arrayJoin = ArrayProto.join;\n var arraySort = ArrayProto.sort;\n var arraySlice = ArrayProto.slice;\n var arrayToString = ArrayProto.toString;\n var arrayToLocaleString = ArrayProto.toLocaleString;\n var ITERATOR = wks('iterator');\n var TAG = wks('toStringTag');\n var TYPED_CONSTRUCTOR = uid('typed_constructor');\n var DEF_CONSTRUCTOR = uid('def_constructor');\n var ALL_CONSTRUCTORS = $typed.CONSTR;\n var TYPED_ARRAY = $typed.TYPED;\n var VIEW = $typed.VIEW;\n var WRONG_LENGTH = 'Wrong length!';\n\n var $map = createArrayMethod(1, function (O, length) {\n return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length);\n });\n\n var LITTLE_ENDIAN = fails(function () {\n // eslint-disable-next-line no-undef\n return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;\n });\n\n var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () {\n new Uint8Array(1).set({});\n });\n\n var toOffset = function (it, BYTES) {\n var offset = toInteger(it);\n if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!');\n return offset;\n };\n\n var validate = function (it) {\n if (isObject(it) && TYPED_ARRAY in it) return it;\n throw TypeError(it + ' is not a typed array!');\n };\n\n var allocate = function (C, length) {\n if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) {\n throw TypeError('It is not a typed array constructor!');\n } return new C(length);\n };\n\n var speciesFromList = function (O, list) {\n return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list);\n };\n\n var fromList = function (C, list) {\n var index = 0;\n var length = list.length;\n var result = allocate(C, length);\n while (length > index) result[index] = list[index++];\n return result;\n };\n\n var addGetter = function (it, key, internal) {\n dP(it, key, { get: function () { return this._d[internal]; } });\n };\n\n var $from = function from(source /* , mapfn, thisArg */) {\n var O = toObject(source);\n var aLen = arguments.length;\n var mapfn = aLen > 1 ? arguments[1] : undefined;\n var mapping = mapfn !== undefined;\n var iterFn = getIterFn(O);\n var i, length, values, result, step, iterator;\n if (iterFn != undefined && !isArrayIter(iterFn)) {\n for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) {\n values.push(step.value);\n } O = values;\n }\n if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2);\n for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) {\n result[i] = mapping ? mapfn(O[i], i) : O[i];\n }\n return result;\n };\n\n var $of = function of(/* ...items */) {\n var index = 0;\n var length = arguments.length;\n var result = allocate(this, length);\n while (length > index) result[index] = arguments[index++];\n return result;\n };\n\n // iOS Safari 6.x fails here\n var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); });\n\n var $toLocaleString = function toLocaleString() {\n return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments);\n };\n\n var proto = {\n copyWithin: function copyWithin(target, start /* , end */) {\n return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined);\n },\n every: function every(callbackfn /* , thisArg */) {\n return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n },\n fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars\n return arrayFill.apply(validate(this), arguments);\n },\n filter: function filter(callbackfn /* , thisArg */) {\n return speciesFromList(this, arrayFilter(validate(this), callbackfn,\n arguments.length > 1 ? arguments[1] : undefined));\n },\n find: function find(predicate /* , thisArg */) {\n return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);\n },\n findIndex: function findIndex(predicate /* , thisArg */) {\n return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);\n },\n forEach: function forEach(callbackfn /* , thisArg */) {\n arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n },\n indexOf: function indexOf(searchElement /* , fromIndex */) {\n return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);\n },\n includes: function includes(searchElement /* , fromIndex */) {\n return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);\n },\n join: function join(separator) { // eslint-disable-line no-unused-vars\n return arrayJoin.apply(validate(this), arguments);\n },\n lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars\n return arrayLastIndexOf.apply(validate(this), arguments);\n },\n map: function map(mapfn /* , thisArg */) {\n return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined);\n },\n reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars\n return arrayReduce.apply(validate(this), arguments);\n },\n reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars\n return arrayReduceRight.apply(validate(this), arguments);\n },\n reverse: function reverse() {\n var that = this;\n var length = validate(that).length;\n var middle = Math.floor(length / 2);\n var index = 0;\n var value;\n while (index < middle) {\n value = that[index];\n that[index++] = that[--length];\n that[length] = value;\n } return that;\n },\n some: function some(callbackfn /* , thisArg */) {\n return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n },\n sort: function sort(comparefn) {\n return arraySort.call(validate(this), comparefn);\n },\n subarray: function subarray(begin, end) {\n var O = validate(this);\n var length = O.length;\n var $begin = toAbsoluteIndex(begin, length);\n return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))(\n O.buffer,\n O.byteOffset + $begin * O.BYTES_PER_ELEMENT,\n toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin)\n );\n }\n };\n\n var $slice = function slice(start, end) {\n return speciesFromList(this, arraySlice.call(validate(this), start, end));\n };\n\n var $set = function set(arrayLike /* , offset */) {\n validate(this);\n var offset = toOffset(arguments[1], 1);\n var length = this.length;\n var src = toObject(arrayLike);\n var len = toLength(src.length);\n var index = 0;\n if (len + offset > length) throw RangeError(WRONG_LENGTH);\n while (index < len) this[offset + index] = src[index++];\n };\n\n var $iterators = {\n entries: function entries() {\n return arrayEntries.call(validate(this));\n },\n keys: function keys() {\n return arrayKeys.call(validate(this));\n },\n values: function values() {\n return arrayValues.call(validate(this));\n }\n };\n\n var isTAIndex = function (target, key) {\n return isObject(target)\n && target[TYPED_ARRAY]\n && typeof key != 'symbol'\n && key in target\n && String(+key) == String(key);\n };\n var $getDesc = function getOwnPropertyDescriptor(target, key) {\n return isTAIndex(target, key = toPrimitive(key, true))\n ? propertyDesc(2, target[key])\n : gOPD(target, key);\n };\n var $setDesc = function defineProperty(target, key, desc) {\n if (isTAIndex(target, key = toPrimitive(key, true))\n && isObject(desc)\n && has(desc, 'value')\n && !has(desc, 'get')\n && !has(desc, 'set')\n // TODO: add validation descriptor w/o calling accessors\n && !desc.configurable\n && (!has(desc, 'writable') || desc.writable)\n && (!has(desc, 'enumerable') || desc.enumerable)\n ) {\n target[key] = desc.value;\n return target;\n } return dP(target, key, desc);\n };\n\n if (!ALL_CONSTRUCTORS) {\n $GOPD.f = $getDesc;\n $DP.f = $setDesc;\n }\n\n $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', {\n getOwnPropertyDescriptor: $getDesc,\n defineProperty: $setDesc\n });\n\n if (fails(function () { arrayToString.call({}); })) {\n arrayToString = arrayToLocaleString = function toString() {\n return arrayJoin.call(this);\n };\n }\n\n var $TypedArrayPrototype$ = redefineAll({}, proto);\n redefineAll($TypedArrayPrototype$, $iterators);\n hide($TypedArrayPrototype$, ITERATOR, $iterators.values);\n redefineAll($TypedArrayPrototype$, {\n slice: $slice,\n set: $set,\n constructor: function () { /* noop */ },\n toString: arrayToString,\n toLocaleString: $toLocaleString\n });\n addGetter($TypedArrayPrototype$, 'buffer', 'b');\n addGetter($TypedArrayPrototype$, 'byteOffset', 'o');\n addGetter($TypedArrayPrototype$, 'byteLength', 'l');\n addGetter($TypedArrayPrototype$, 'length', 'e');\n dP($TypedArrayPrototype$, TAG, {\n get: function () { return this[TYPED_ARRAY]; }\n });\n\n // eslint-disable-next-line max-statements\n module.exports = function (KEY, BYTES, wrapper, CLAMPED) {\n CLAMPED = !!CLAMPED;\n var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array';\n var GETTER = 'get' + KEY;\n var SETTER = 'set' + KEY;\n var TypedArray = global[NAME];\n var Base = TypedArray || {};\n var TAC = TypedArray && getPrototypeOf(TypedArray);\n var FORCED = !TypedArray || !$typed.ABV;\n var O = {};\n var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];\n var getter = function (that, index) {\n var data = that._d;\n return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN);\n };\n var setter = function (that, index, value) {\n var data = that._d;\n if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;\n data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN);\n };\n var addElement = function (that, index) {\n dP(that, index, {\n get: function () {\n return getter(this, index);\n },\n set: function (value) {\n return setter(this, index, value);\n },\n enumerable: true\n });\n };\n if (FORCED) {\n TypedArray = wrapper(function (that, data, $offset, $length) {\n anInstance(that, TypedArray, NAME, '_d');\n var index = 0;\n var offset = 0;\n var buffer, byteLength, length, klass;\n if (!isObject(data)) {\n length = toIndex(data);\n byteLength = length * BYTES;\n buffer = new $ArrayBuffer(byteLength);\n } else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) {\n buffer = data;\n offset = toOffset($offset, BYTES);\n var $len = data.byteLength;\n if ($length === undefined) {\n if ($len % BYTES) throw RangeError(WRONG_LENGTH);\n byteLength = $len - offset;\n if (byteLength < 0) throw RangeError(WRONG_LENGTH);\n } else {\n byteLength = toLength($length) * BYTES;\n if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH);\n }\n length = byteLength / BYTES;\n } else if (TYPED_ARRAY in data) {\n return fromList(TypedArray, data);\n } else {\n return $from.call(TypedArray, data);\n }\n hide(that, '_d', {\n b: buffer,\n o: offset,\n l: byteLength,\n e: length,\n v: new $DataView(buffer)\n });\n while (index < length) addElement(that, index++);\n });\n TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$);\n hide(TypedArrayPrototype, 'constructor', TypedArray);\n } else if (!fails(function () {\n TypedArray(1);\n }) || !fails(function () {\n new TypedArray(-1); // eslint-disable-line no-new\n }) || !$iterDetect(function (iter) {\n new TypedArray(); // eslint-disable-line no-new\n new TypedArray(null); // eslint-disable-line no-new\n new TypedArray(1.5); // eslint-disable-line no-new\n new TypedArray(iter); // eslint-disable-line no-new\n }, true)) {\n TypedArray = wrapper(function (that, data, $offset, $length) {\n anInstance(that, TypedArray, NAME);\n var klass;\n // `ws` module bug, temporarily remove validation length for Uint8Array\n // https://github.com/websockets/ws/pull/645\n if (!isObject(data)) return new Base(toIndex(data));\n if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) {\n return $length !== undefined\n ? new Base(data, toOffset($offset, BYTES), $length)\n : $offset !== undefined\n ? new Base(data, toOffset($offset, BYTES))\n : new Base(data);\n }\n if (TYPED_ARRAY in data) return fromList(TypedArray, data);\n return $from.call(TypedArray, data);\n });\n arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) {\n if (!(key in TypedArray)) hide(TypedArray, key, Base[key]);\n });\n TypedArray[PROTOTYPE] = TypedArrayPrototype;\n if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray;\n }\n var $nativeIterator = TypedArrayPrototype[ITERATOR];\n var CORRECT_ITER_NAME = !!$nativeIterator\n && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined);\n var $iterator = $iterators.values;\n hide(TypedArray, TYPED_CONSTRUCTOR, true);\n hide(TypedArrayPrototype, TYPED_ARRAY, NAME);\n hide(TypedArrayPrototype, VIEW, true);\n hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray);\n\n if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) {\n dP(TypedArrayPrototype, TAG, {\n get: function () { return NAME; }\n });\n }\n\n O[NAME] = TypedArray;\n\n $export($export.G + $export.W + $export.F * (TypedArray != Base), O);\n\n $export($export.S, NAME, {\n BYTES_PER_ELEMENT: BYTES\n });\n\n $export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, {\n from: $from,\n of: $of\n });\n\n if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);\n\n $export($export.P, NAME, proto);\n\n setSpecies(NAME);\n\n $export($export.P + $export.F * FORCED_SET, NAME, { set: $set });\n\n $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators);\n\n if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString;\n\n $export($export.P + $export.F * fails(function () {\n new TypedArray(1).slice();\n }), NAME, { slice: $slice });\n\n $export($export.P + $export.F * (fails(function () {\n return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString();\n }) || !fails(function () {\n TypedArrayPrototype.toLocaleString.call([1, 2]);\n })), NAME, { toLocaleString: $toLocaleString });\n\n Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator;\n if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator);\n };\n} else module.exports = function () { /* empty */ };\n","var Map = require('./es6.map');\nvar $export = require('./_export');\nvar shared = require('./_shared')('metadata');\nvar store = shared.store || (shared.store = new (require('./es6.weak-map'))());\n\nvar getOrCreateMetadataMap = function (target, targetKey, create) {\n var targetMetadata = store.get(target);\n if (!targetMetadata) {\n if (!create) return undefined;\n store.set(target, targetMetadata = new Map());\n }\n var keyMetadata = targetMetadata.get(targetKey);\n if (!keyMetadata) {\n if (!create) return undefined;\n targetMetadata.set(targetKey, keyMetadata = new Map());\n } return keyMetadata;\n};\nvar ordinaryHasOwnMetadata = function (MetadataKey, O, P) {\n var metadataMap = getOrCreateMetadataMap(O, P, false);\n return metadataMap === undefined ? false : metadataMap.has(MetadataKey);\n};\nvar ordinaryGetOwnMetadata = function (MetadataKey, O, P) {\n var metadataMap = getOrCreateMetadataMap(O, P, false);\n return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey);\n};\nvar ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) {\n getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);\n};\nvar ordinaryOwnMetadataKeys = function (target, targetKey) {\n var metadataMap = getOrCreateMetadataMap(target, targetKey, false);\n var keys = [];\n if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); });\n return keys;\n};\nvar toMetaKey = function (it) {\n return it === undefined || typeof it == 'symbol' ? it : String(it);\n};\nvar exp = function (O) {\n $export($export.S, 'Reflect', O);\n};\n\nmodule.exports = {\n store: store,\n map: getOrCreateMetadataMap,\n has: ordinaryHasOwnMetadata,\n get: ordinaryGetOwnMetadata,\n set: ordinaryDefineOwnMetadata,\n keys: ordinaryOwnMetadataKeys,\n key: toMetaKey,\n exp: exp\n};\n","// 7.1.1 ToPrimitive(input [, PreferredType])\nvar isObject = require('./_is-object');\n// instead of the ES6 spec version, we didn't implement @@toPrimitive case\n// and the second argument - flag - preferred type is a string\nmodule.exports = function (it, S) {\n if (!isObject(it)) return it;\n var fn, val;\n if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;\n if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;\n if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;\n throw TypeError(\"Can't convert object to primitive value\");\n};\n","// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])\nvar anObject = require('./_an-object');\nvar dPs = require('./_object-dps');\nvar enumBugKeys = require('./_enum-bug-keys');\nvar IE_PROTO = require('./_shared-key')('IE_PROTO');\nvar Empty = function () { /* empty */ };\nvar PROTOTYPE = 'prototype';\n\n// Create object with fake `null` prototype: use iframe Object with cleared prototype\nvar createDict = function () {\n // Thrash, waste and sodomy: IE GC bug\n var iframe = require('./_dom-create')('iframe');\n var i = enumBugKeys.length;\n var lt = '<';\n var gt = '>';\n var iframeDocument;\n iframe.style.display = 'none';\n require('./_html').appendChild(iframe);\n iframe.src = 'javascript:'; // eslint-disable-line no-script-url\n // createDict = iframe.contentWindow.Object;\n // html.removeChild(iframe);\n iframeDocument = iframe.contentWindow.document;\n iframeDocument.open();\n iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);\n iframeDocument.close();\n createDict = iframeDocument.F;\n while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];\n return createDict();\n};\n\nmodule.exports = Object.create || function create(O, Properties) {\n var result;\n if (O !== null) {\n Empty[PROTOTYPE] = anObject(O);\n result = new Empty();\n Empty[PROTOTYPE] = null;\n // add \"__proto__\" for Object.getPrototypeOf polyfill\n result[IE_PROTO] = O;\n } else result = createDict();\n return Properties === undefined ? result : dPs(result, Properties);\n};\n","// 7.1.15 ToLength\nvar toInteger = require('./_to-integer');\nvar min = Math.min;\nmodule.exports = function (it) {\n return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991\n};\n","var shared = require('./_shared')('keys');\nvar uid = require('./_uid');\nmodule.exports = function (key) {\n return shared[key] || (shared[key] = uid(key));\n};\n","var core = require('./_core');\nvar global = require('./_global');\nvar SHARED = '__core-js_shared__';\nvar store = global[SHARED] || (global[SHARED] = {});\n\n(module.exports = function (key, value) {\n return store[key] || (store[key] = value !== undefined ? value : {});\n})('versions', []).push({\n version: core.version,\n mode: require('./_library') ? 'pure' : 'global',\n copyright: '© 2019 Denis Pushkarev (zloirock.ru)'\n});\n","// IE 8- don't enum bug keys\nmodule.exports = (\n 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'\n).split(',');\n","var def = require('./_object-dp').f;\nvar has = require('./_has');\nvar TAG = require('./_wks')('toStringTag');\n\nmodule.exports = function (it, tag, stat) {\n if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });\n};\n","exports.f = {}.propertyIsEnumerable;\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * \n */\n\n'use strict';\n\n/**\n * Keeps track of the current owner.\n *\n * The current owner is the component who should own any components that are\n * currently being constructed.\n */\nvar ReactCurrentOwner = {\n /**\n * @internal\n * @type {ReactComponent}\n */\n current: null\n};\n\nmodule.exports = ReactCurrentOwner;","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\n'use strict';\n\nvar _assign = require('object-assign');\n\nvar PooledClass = require('./PooledClass');\n\nvar emptyFunction = require('fbjs/lib/emptyFunction');\nvar warning = require('fbjs/lib/warning');\n\nvar didWarnForAddedNewProperty = false;\nvar isProxySupported = typeof Proxy === 'function';\n\nvar shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances'];\n\n/**\n * @interface Event\n * @see http://www.w3.org/TR/DOM-Level-3-Events/\n */\nvar EventInterface = {\n type: null,\n target: null,\n // currentTarget is set when dispatching; no use in copying it here\n currentTarget: emptyFunction.thatReturnsNull,\n eventPhase: null,\n bubbles: null,\n cancelable: null,\n timeStamp: function (event) {\n return event.timeStamp || Date.now();\n },\n defaultPrevented: null,\n isTrusted: null\n};\n\n/**\n * Synthetic events are dispatched by event plugins, typically in response to a\n * top-level event delegation handler.\n *\n * These systems should generally use pooling to reduce the frequency of garbage\n * collection. The system should check `isPersistent` to determine whether the\n * event should be released into the pool after being dispatched. Users that\n * need a persisted event should invoke `persist`.\n *\n * Synthetic events (and subclasses) implement the DOM Level 3 Events API by\n * normalizing browser quirks. Subclasses do not necessarily have to implement a\n * DOM interface; custom application-specific events can also subclass this.\n *\n * @param {object} dispatchConfig Configuration used to dispatch this event.\n * @param {*} targetInst Marker identifying the event target.\n * @param {object} nativeEvent Native browser event.\n * @param {DOMEventTarget} nativeEventTarget Target node.\n */\nfunction SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {\n if (process.env.NODE_ENV !== 'production') {\n // these have a getter/setter for warnings\n delete this.nativeEvent;\n delete this.preventDefault;\n delete this.stopPropagation;\n }\n\n this.dispatchConfig = dispatchConfig;\n this._targetInst = targetInst;\n this.nativeEvent = nativeEvent;\n\n var Interface = this.constructor.Interface;\n for (var propName in Interface) {\n if (!Interface.hasOwnProperty(propName)) {\n continue;\n }\n if (process.env.NODE_ENV !== 'production') {\n delete this[propName]; // this has a getter/setter for warnings\n }\n var normalize = Interface[propName];\n if (normalize) {\n this[propName] = normalize(nativeEvent);\n } else {\n if (propName === 'target') {\n this.target = nativeEventTarget;\n } else {\n this[propName] = nativeEvent[propName];\n }\n }\n }\n\n var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;\n if (defaultPrevented) {\n this.isDefaultPrevented = emptyFunction.thatReturnsTrue;\n } else {\n this.isDefaultPrevented = emptyFunction.thatReturnsFalse;\n }\n this.isPropagationStopped = emptyFunction.thatReturnsFalse;\n return this;\n}\n\n_assign(SyntheticEvent.prototype, {\n preventDefault: function () {\n this.defaultPrevented = true;\n var event = this.nativeEvent;\n if (!event) {\n return;\n }\n\n if (event.preventDefault) {\n event.preventDefault();\n // eslint-disable-next-line valid-typeof\n } else if (typeof event.returnValue !== 'unknown') {\n event.returnValue = false;\n }\n this.isDefaultPrevented = emptyFunction.thatReturnsTrue;\n },\n\n stopPropagation: function () {\n var event = this.nativeEvent;\n if (!event) {\n return;\n }\n\n if (event.stopPropagation) {\n event.stopPropagation();\n // eslint-disable-next-line valid-typeof\n } else if (typeof event.cancelBubble !== 'unknown') {\n // The ChangeEventPlugin registers a \"propertychange\" event for\n // IE. This event does not support bubbling or cancelling, and\n // any references to cancelBubble throw \"Member not found\". A\n // typeof check of \"unknown\" circumvents this issue (and is also\n // IE specific).\n event.cancelBubble = true;\n }\n\n this.isPropagationStopped = emptyFunction.thatReturnsTrue;\n },\n\n /**\n * We release all dispatched `SyntheticEvent`s after each event loop, adding\n * them back into the pool. This allows a way to hold onto a reference that\n * won't be added back into the pool.\n */\n persist: function () {\n this.isPersistent = emptyFunction.thatReturnsTrue;\n },\n\n /**\n * Checks if this event should be released back into the pool.\n *\n * @return {boolean} True if this should not be released, false otherwise.\n */\n isPersistent: emptyFunction.thatReturnsFalse,\n\n /**\n * `PooledClass` looks for `destructor` on each instance it releases.\n */\n destructor: function () {\n var Interface = this.constructor.Interface;\n for (var propName in Interface) {\n if (process.env.NODE_ENV !== 'production') {\n Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));\n } else {\n this[propName] = null;\n }\n }\n for (var i = 0; i < shouldBeReleasedProperties.length; i++) {\n this[shouldBeReleasedProperties[i]] = null;\n }\n if (process.env.NODE_ENV !== 'production') {\n Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));\n Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction));\n Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction));\n }\n }\n});\n\nSyntheticEvent.Interface = EventInterface;\n\n/**\n * Helper to reduce boilerplate when creating subclasses.\n *\n * @param {function} Class\n * @param {?object} Interface\n */\nSyntheticEvent.augmentClass = function (Class, Interface) {\n var Super = this;\n\n var E = function () {};\n E.prototype = Super.prototype;\n var prototype = new E();\n\n _assign(prototype, Class.prototype);\n Class.prototype = prototype;\n Class.prototype.constructor = Class;\n\n Class.Interface = _assign({}, Super.Interface, Interface);\n Class.augmentClass = Super.augmentClass;\n\n PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler);\n};\n\n/** Proxying after everything set on SyntheticEvent\n * to resolve Proxy issue on some WebKit browsers\n * in which some Event properties are set to undefined (GH#10010)\n */\nif (process.env.NODE_ENV !== 'production') {\n if (isProxySupported) {\n /*eslint-disable no-func-assign */\n SyntheticEvent = new Proxy(SyntheticEvent, {\n construct: function (target, args) {\n return this.apply(target, Object.create(target.prototype), args);\n },\n apply: function (constructor, that, args) {\n return new Proxy(constructor.apply(that, args), {\n set: function (target, prop, value) {\n if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) {\n process.env.NODE_ENV !== 'production' ? warning(didWarnForAddedNewProperty || target.isPersistent(), \"This synthetic event is reused for performance reasons. If you're \" + \"seeing this, you're adding a new property in the synthetic event object. \" + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0;\n didWarnForAddedNewProperty = true;\n }\n target[prop] = value;\n return true;\n }\n });\n }\n });\n /*eslint-enable no-func-assign */\n }\n}\n\nPooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler);\n\nmodule.exports = SyntheticEvent;\n\n/**\n * Helper to nullify syntheticEvent instance properties when destructing\n *\n * @param {object} SyntheticEvent\n * @param {String} propName\n * @return {object} defineProperty object\n */\nfunction getPooledWarningPropertyDefinition(propName, getVal) {\n var isFunction = typeof getVal === 'function';\n return {\n configurable: true,\n set: set,\n get: get\n };\n\n function set(val) {\n var action = isFunction ? 'setting the method' : 'setting the property';\n warn(action, 'This is effectively a no-op');\n return val;\n }\n\n function get() {\n var action = isFunction ? 'accessing the method' : 'accessing the property';\n var result = isFunction ? 'This is a no-op function' : 'This is set to null';\n warn(action, result);\n return getVal;\n }\n\n function warn(action, result) {\n var warningCondition = false;\n process.env.NODE_ENV !== 'production' ? warning(warningCondition, \"This synthetic event is reused for performance reasons. If you're seeing this, \" + \"you're %s `%s` on a released/nullified synthetic event. %s. \" + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0;\n }\n}","'use strict';\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nvar _regenerator = require('babel-runtime/regenerator');\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _bluebird = require('bluebird');\n\nvar _startCallApp = function () {\n var _ref = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee(roomId, type) {\n var scalarClient, haveScalar, ErrorDialog, room, currentRoomWidgets, _ErrorDialog3, currentJitsiWidgets, _ErrorDialog4, widgetSessionId, confId, queryString, widgetUrl, widgetData, widgetId;\n\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n // check for a working intgrations manager. Technically we could put\n // the state event in anyway, but the resulting widget would then not\n // work for us. Better that the user knows before everyone else in the\n // room sees it.\n scalarClient = new _ScalarAuthClient2.default();\n haveScalar = false;\n _context.prev = 2;\n _context.next = 5;\n return (0, _bluebird.resolve)(scalarClient.connect());\n\n case 5:\n haveScalar = scalarClient.hasCredentials();\n _context.next = 10;\n break;\n\n case 8:\n _context.prev = 8;\n _context.t0 = _context['catch'](2);\n\n case 10:\n if (haveScalar) {\n _context.next = 14;\n break;\n }\n\n ErrorDialog = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n\n\n _Modal2.default.createTrackedDialog('Could not connect to the integration server', '', ErrorDialog, {\n title: (0, _languageHandler._t)('Could not connect to the integration server'),\n description: (0, _languageHandler._t)('A conference call could not be started because the integrations server is not available')\n });\n return _context.abrupt('return');\n\n case 14:\n\n _dispatcher2.default.dispatch({\n action: 'appsDrawer',\n show: true\n });\n\n room = _MatrixClientPeg2.default.get().getRoom(roomId);\n currentRoomWidgets = _WidgetUtils2.default.getRoomWidgets(room);\n\n if (!_WidgetEchoStore2.default.roomHasPendingWidgetsOfType(roomId, currentRoomWidgets, 'jitsi')) {\n _context.next = 21;\n break;\n }\n\n _ErrorDialog3 = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n\n\n _Modal2.default.createTrackedDialog('Call already in progress', '', _ErrorDialog3, {\n title: (0, _languageHandler._t)('Call in Progress'),\n description: (0, _languageHandler._t)('A call is currently being placed!')\n });\n return _context.abrupt('return');\n\n case 21:\n currentJitsiWidgets = currentRoomWidgets.filter(function (ev) {\n return ev.getContent().type === 'jitsi';\n });\n\n if (!(currentJitsiWidgets.length > 0)) {\n _context.next = 27;\n break;\n }\n\n console.warn(\"Refusing to start conference call widget in \" + roomId + \" a conference call widget is already present\");\n _ErrorDialog4 = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n\n\n _Modal2.default.createTrackedDialog('Already have Jitsi Widget', '', _ErrorDialog4, {\n title: (0, _languageHandler._t)('Call in Progress'),\n description: (0, _languageHandler._t)('A call is already in progress!')\n });\n return _context.abrupt('return');\n\n case 27:\n\n // This inherits its poor naming from the field of the same name that goes into\n // the event. It's just a random string to make the Jitsi URLs unique.\n widgetSessionId = Math.random().toString(36).substring(2);\n confId = room.roomId.replace(/[^A-Za-z0-9]/g, '') + widgetSessionId;\n // NB. we can't just encodeURICompoent all of these because the $ signs need to be there\n // (but currently the only thing that needs encoding is the confId)\n\n queryString = ['confId=' + encodeURIComponent(confId), 'isAudioConf=' + (type === 'voice' ? 'true' : 'false'), 'displayName=$matrix_display_name', 'avatarUrl=$matrix_avatar_url', 'email=$matrix_user_id'].join('&');\n widgetUrl = void 0;\n\n if (_SdkConfig2.default.get().integrations_jitsi_widget_url) {\n // Try this config key. This probably isn't ideal as a way of discovering this\n // URL, but this will at least allow the integration manager to not be hardcoded.\n widgetUrl = _SdkConfig2.default.get().integrations_jitsi_widget_url + '?' + queryString;\n } else {\n widgetUrl = _SdkConfig2.default.get().integrations_rest_url + '/widgets/jitsi.html?' + queryString;\n }\n\n widgetData = { widgetSessionId: widgetSessionId };\n widgetId = 'jitsi_' + _MatrixClientPeg2.default.get().credentials.userId + '_' + Date.now();\n\n\n _WidgetUtils2.default.setRoomWidget(roomId, widgetId, 'jitsi', widgetUrl, 'Jitsi', widgetData).then(function () {\n console.log('Jitsi widget added');\n }).catch(function (e) {\n if (e.errcode === 'M_FORBIDDEN') {\n var _ErrorDialog5 = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n\n _Modal2.default.createTrackedDialog('Call Failed', '', _ErrorDialog5, {\n title: (0, _languageHandler._t)('Permission Required'),\n description: (0, _languageHandler._t)(\"You do not have permission to start a conference call in this room\")\n });\n }\n console.error(e);\n });\n\n case 35:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, this, [[2, 8]]);\n }));\n\n return function _startCallApp(_x, _x2) {\n return _ref.apply(this, arguments);\n };\n}();\n\n// FIXME: Nasty way of making sure we only register\n// with the dispatcher once\n\n\nvar _MatrixClientPeg = require('./MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _PlatformPeg = require('./PlatformPeg');\n\nvar _PlatformPeg2 = _interopRequireDefault(_PlatformPeg);\n\nvar _Modal = require('./Modal');\n\nvar _Modal2 = _interopRequireDefault(_Modal);\n\nvar _index = require('./index');\n\nvar _index2 = _interopRequireDefault(_index);\n\nvar _languageHandler = require('./languageHandler');\n\nvar _matrixJsSdk = require('matrix-js-sdk');\n\nvar _matrixJsSdk2 = _interopRequireDefault(_matrixJsSdk);\n\nvar _dispatcher = require('./dispatcher');\n\nvar _dispatcher2 = _interopRequireDefault(_dispatcher);\n\nvar _SdkConfig = require('./SdkConfig');\n\nvar _SdkConfig2 = _interopRequireDefault(_SdkConfig);\n\nvar _cryptodevices = require('./cryptodevices');\n\nvar _WidgetUtils = require('./utils/WidgetUtils');\n\nvar _WidgetUtils2 = _interopRequireDefault(_WidgetUtils);\n\nvar _WidgetEchoStore = require('./stores/WidgetEchoStore');\n\nvar _WidgetEchoStore2 = _interopRequireDefault(_WidgetEchoStore);\n\nvar _ScalarAuthClient = require('./ScalarAuthClient');\n\nvar _ScalarAuthClient2 = _interopRequireDefault(_ScalarAuthClient);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017, 2018 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\n * Manages a list of all the currently active calls.\n *\n * This handler dispatches when voip calls are added/updated/removed from this list:\n * {\n * action: 'call_state'\n * room_id: \n * }\n *\n * To know the state of the call, this handler exposes a getter to\n * obtain the call for a room:\n * var call = CallHandler.getCall(roomId)\n * var state = call.call_state; // ringing|ringback|connected|ended|busy|stop_ringback|stop_ringing\n *\n * This handler listens for and handles the following actions:\n * {\n * action: 'place_call',\n * type: 'voice|video',\n * room_id: \n * }\n *\n * {\n * action: 'incoming_call'\n * call: MatrixCall\n * }\n *\n * {\n * action: 'hangup'\n * room_id: \n * }\n *\n * {\n * action: 'answer'\n * room_id: \n * }\n */\n\nglobal.mxCalls = {\n //room_id: MatrixCall\n};\nvar calls = global.mxCalls;\nvar ConferenceHandler = null;\n\nvar audioPromises = {};\n\nfunction play(audioId) {\n // TODO: Attach an invisible element for this instead\n // which listens?\n var audio = document.getElementById(audioId);\n if (audio) {\n if (audioPromises[audioId]) {\n audioPromises[audioId] = audioPromises[audioId].then(function () {\n audio.load();\n return audio.play();\n });\n } else {\n audioPromises[audioId] = audio.play();\n }\n }\n}\n\nfunction pause(audioId) {\n // TODO: Attach an invisible element for this instead\n // which listens?\n var audio = document.getElementById(audioId);\n if (audio) {\n if (audioPromises[audioId]) {\n audioPromises[audioId] = audioPromises[audioId].then(function () {\n return audio.pause();\n });\n } else {\n // pause doesn't actually return a promise, but might as well do this for symmetry with play();\n audioPromises[audioId] = audio.pause();\n }\n }\n}\n\nfunction _reAttemptCall(call) {\n if (call.direction === 'outbound') {\n _dispatcher2.default.dispatch({\n action: 'place_call',\n room_id: call.roomId,\n type: call.type\n });\n } else {\n call.answer();\n }\n}\n\nfunction _setCallListeners(call) {\n call.on(\"error\", function (err) {\n console.error(\"Call error: %s\", err);\n console.error(err.stack);\n if (err.code === 'unknown_devices') {\n var QuestionDialog = _index2.default.getComponent(\"dialogs.QuestionDialog\");\n\n _Modal2.default.createTrackedDialog('Call Failed', '', QuestionDialog, {\n title: (0, _languageHandler._t)('Call Failed'),\n description: (0, _languageHandler._t)(\"There are unknown devices in this room: \" + \"if you proceed without verifying them, it will be \" + \"possible for someone to eavesdrop on your call.\"),\n button: (0, _languageHandler._t)('Review Devices'),\n onFinished: function onFinished(confirmed) {\n if (confirmed) {\n var room = _MatrixClientPeg2.default.get().getRoom(call.roomId);\n (0, _cryptodevices.showUnknownDeviceDialogForCalls)(_MatrixClientPeg2.default.get(), room, function () {\n _reAttemptCall(call);\n }, call.direction === 'outbound' ? (0, _languageHandler._t)(\"Call Anyway\") : (0, _languageHandler._t)(\"Answer Anyway\"), call.direction === 'outbound' ? (0, _languageHandler._t)(\"Call\") : (0, _languageHandler._t)(\"Answer\"));\n }\n }\n });\n } else {\n var ErrorDialog = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n\n _Modal2.default.createTrackedDialog('Call Failed', '', ErrorDialog, {\n title: (0, _languageHandler._t)('Call Failed'),\n description: err.message\n });\n }\n });\n call.on(\"hangup\", function () {\n _setCallState(undefined, call.roomId, \"ended\");\n });\n // map web rtc states to dummy UI state\n // ringing|ringback|connected|ended|busy|stop_ringback|stop_ringing\n call.on(\"state\", function (newState, oldState) {\n if (newState === \"ringing\") {\n _setCallState(call, call.roomId, \"ringing\");\n pause(\"ringbackAudio\");\n } else if (newState === \"invite_sent\") {\n _setCallState(call, call.roomId, \"ringback\");\n play(\"ringbackAudio\");\n } else if (newState === \"ended\" && oldState === \"connected\") {\n _setCallState(undefined, call.roomId, \"ended\");\n pause(\"ringbackAudio\");\n play(\"callendAudio\");\n } else if (newState === \"ended\" && oldState === \"invite_sent\" && (call.hangupParty === \"remote\" || call.hangupParty === \"local\" && call.hangupReason === \"invite_timeout\")) {\n _setCallState(call, call.roomId, \"busy\");\n pause(\"ringbackAudio\");\n play(\"busyAudio\");\n var ErrorDialog = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n _Modal2.default.createTrackedDialog('Call Handler', 'Call Timeout', ErrorDialog, {\n title: (0, _languageHandler._t)('Call Timeout'),\n description: (0, _languageHandler._t)('The remote side failed to pick up') + '.'\n });\n } else if (oldState === \"invite_sent\") {\n _setCallState(call, call.roomId, \"stop_ringback\");\n pause(\"ringbackAudio\");\n } else if (oldState === \"ringing\") {\n _setCallState(call, call.roomId, \"stop_ringing\");\n pause(\"ringbackAudio\");\n } else if (newState === \"connected\") {\n _setCallState(call, call.roomId, \"connected\");\n pause(\"ringbackAudio\");\n }\n });\n}\n\nfunction _setCallState(call, roomId, status) {\n console.log(\"Call state in %s changed to %s (%s)\", roomId, status, call ? call.call_state : \"-\");\n calls[roomId] = call;\n\n if (status === \"ringing\") {\n play(\"ringAudio\");\n } else if (call && call.call_state === \"ringing\") {\n pause(\"ringAudio\");\n }\n\n if (call) {\n call.call_state = status;\n }\n _dispatcher2.default.dispatch({\n action: 'call_state',\n room_id: roomId,\n state: status\n });\n}\n\nfunction _onAction(payload) {\n function placeCall(newCall) {\n _setCallListeners(newCall);\n if (payload.type === 'voice') {\n newCall.placeVoiceCall();\n } else if (payload.type === 'video') {\n newCall.placeVideoCall(payload.remote_element, payload.local_element);\n } else if (payload.type === 'screensharing') {\n var screenCapErrorString = _PlatformPeg2.default.get().screenCaptureErrorString();\n if (screenCapErrorString) {\n _setCallState(undefined, newCall.roomId, \"ended\");\n console.log(\"Can't capture screen: \" + screenCapErrorString);\n var ErrorDialog = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n _Modal2.default.createTrackedDialog('Call Handler', 'Unable to capture screen', ErrorDialog, {\n title: (0, _languageHandler._t)('Unable to capture screen'),\n description: screenCapErrorString\n });\n return;\n }\n newCall.placeScreenSharingCall(payload.remote_element, payload.local_element);\n } else {\n console.error(\"Unknown conf call type: %s\", payload.type);\n }\n }\n\n switch (payload.action) {\n case 'place_call':\n {\n if (module.exports.getAnyActiveCall()) {\n var ErrorDialog = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n _Modal2.default.createTrackedDialog('Call Handler', 'Existing Call', ErrorDialog, {\n title: (0, _languageHandler._t)('Existing Call'),\n description: (0, _languageHandler._t)('You are already in a call.')\n });\n return; // don't allow >1 call to be placed.\n }\n\n // if the runtime env doesn't do VoIP, whine.\n if (!_MatrixClientPeg2.default.get().supportsVoip()) {\n var _ErrorDialog = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n _Modal2.default.createTrackedDialog('Call Handler', 'VoIP is unsupported', _ErrorDialog, {\n title: (0, _languageHandler._t)('VoIP is unsupported'),\n description: (0, _languageHandler._t)('You cannot place VoIP calls in this browser.')\n });\n return;\n }\n\n var room = _MatrixClientPeg2.default.get().getRoom(payload.room_id);\n if (!room) {\n console.error(\"Room %s does not exist.\", payload.room_id);\n return;\n }\n\n var members = room.getJoinedMembers();\n if (members.length <= 1) {\n var _ErrorDialog2 = _index2.default.getComponent(\"dialogs.ErrorDialog\");\n _Modal2.default.createTrackedDialog('Call Handler', 'Cannot place call with self', _ErrorDialog2, {\n description: (0, _languageHandler._t)('You cannot place a call with yourself.')\n });\n return;\n } else if (members.length === 2) {\n console.log(\"Place %s call in %s\", payload.type, payload.room_id);\n var call = _matrixJsSdk2.default.createNewMatrixCall(_MatrixClientPeg2.default.get(), payload.room_id);\n placeCall(call);\n } else {\n // > 2\n _dispatcher2.default.dispatch({\n action: \"place_conference_call\",\n room_id: payload.room_id,\n type: payload.type,\n remote_element: payload.remote_element,\n local_element: payload.local_element\n });\n }\n }\n break;\n case 'place_conference_call':\n console.log(\"Place conference call in %s\", payload.room_id);\n _startCallApp(payload.room_id, payload.type);\n break;\n case 'incoming_call':\n {\n if (module.exports.getAnyActiveCall()) {\n // ignore multiple incoming calls. in future, we may want a line-1/line-2 setup.\n // we avoid rejecting with \"busy\" in case the user wants to answer it on a different device.\n // in future we could signal a \"local busy\" as a warning to the caller.\n // see https://github.com/vector-im/vector-web/issues/1964\n return;\n }\n\n // if the runtime env doesn't do VoIP, stop here.\n if (!_MatrixClientPeg2.default.get().supportsVoip()) {\n return;\n }\n\n var _call = payload.call;\n _setCallListeners(_call);\n _setCallState(_call, _call.roomId, \"ringing\");\n }\n break;\n case 'hangup':\n if (!calls[payload.room_id]) {\n return; // no call to hangup\n }\n calls[payload.room_id].hangup();\n _setCallState(null, payload.room_id, \"ended\");\n break;\n case 'answer':\n if (!calls[payload.room_id]) {\n return; // no call to answer\n }\n calls[payload.room_id].answer();\n _setCallState(calls[payload.room_id], payload.room_id, \"connected\");\n _dispatcher2.default.dispatch({\n action: \"view_room\",\n room_id: payload.room_id\n });\n break;\n }\n}\n\nif (!global.mxCallHandler) {\n _dispatcher2.default.register(_onAction);\n}\n\nvar callHandler = {\n getCallForRoom: function getCallForRoom(roomId) {\n var call = module.exports.getCall(roomId);\n if (call) return call;\n\n if (ConferenceHandler) {\n call = ConferenceHandler.getConferenceCallForRoom(roomId);\n }\n if (call) return call;\n\n return null;\n },\n\n getCall: function getCall(roomId) {\n return calls[roomId] || null;\n },\n\n getAnyActiveCall: function getAnyActiveCall() {\n var roomsWithCalls = (0, _keys2.default)(calls);\n for (var i = 0; i < roomsWithCalls.length; i++) {\n if (calls[roomsWithCalls[i]] && calls[roomsWithCalls[i]].call_state !== \"ended\") {\n return calls[roomsWithCalls[i]];\n }\n }\n return null;\n },\n\n /**\n * The conference handler is a module that deals with implementation-specific\n * multi-party calling implementations. Riot passes in its own which creates\n * a one-to-one call with a freeswitch conference bridge. As of July 2018,\n * the de-facto way of conference calling is a Jitsi widget, so this is\n * deprecated. It reamins here for two reasons:\n * 1. So Riot still supports joining existing freeswitch conference calls\n * (but doesn't support creating them). After a transition period, we can\n * remove support for joining them too.\n * 2. To hide the one-to-one rooms that old-style conferencing creates. This\n * is much harder to remove: probably either we make Riot leave & forget these\n * rooms after we remove support for joining freeswitch conferences, or we\n * accept that random rooms with cryptic users will suddently appear for\n * anyone who's ever used conference calling, or we are stuck with this\n * code forever.\n *\n * @param {object} confHandler The conference handler object\n */\n setConferenceHandler: function setConferenceHandler(confHandler) {\n ConferenceHandler = confHandler;\n },\n\n getConferenceHandler: function getConferenceHandler() {\n return ConferenceHandler;\n }\n};\n// Only things in here which actually need to be global are the\n// calls list (done separately) and making sure we only register\n// with the dispatcher once (which uses this mechanism but checks\n// separately). This could be tidied up.\nif (global.mxCallHandler === undefined) {\n global.mxCallHandler = callHandler;\n}\n\nmodule.exports = global.mxCallHandler;\n//# sourceMappingURL=CallHandler.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _extends2 = require('babel-runtime/helpers/extends');\n\nvar _extends3 = _interopRequireDefault(_extends2);\n\nvar _setImmediate2 = require('babel-runtime/core-js/set-immediate');\n\nvar _setImmediate3 = _interopRequireDefault(_setImmediate2);\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nexports.createMenu = createMenu;\n\nvar _react = require('react');\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _reactDom = require('react-dom');\n\nvar _reactDom2 = _interopRequireDefault(_reactDom);\n\nvar _propTypes = require('prop-types');\n\nvar _propTypes2 = _interopRequireDefault(_propTypes);\n\nvar _classnames = require('classnames');\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// Shamelessly ripped off Modal.js. There's probably a better way\n// of doing reusable widgets like dialog boxes & menus where we go and\n// pass in a custom control as the actual body.\n\n/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2018 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar ContextualMenuContainerId = \"mx_ContextualMenu_Container\";\n\nfunction getOrCreateContainer() {\n var container = document.getElementById(ContextualMenuContainerId);\n\n if (!container) {\n container = document.createElement(\"div\");\n container.id = ContextualMenuContainerId;\n document.body.appendChild(container);\n }\n\n return container;\n}\n\nvar ContextualMenu = function (_React$Component) {\n (0, _inherits3.default)(ContextualMenu, _React$Component);\n\n function ContextualMenu() {\n (0, _classCallCheck3.default)(this, ContextualMenu);\n\n var _this = (0, _possibleConstructorReturn3.default)(this, (ContextualMenu.__proto__ || (0, _getPrototypeOf2.default)(ContextualMenu)).call(this));\n\n _this.state = {\n contextMenuRect: null\n };\n\n _this.onContextMenu = _this.onContextMenu.bind(_this);\n _this.collectContextMenuRect = _this.collectContextMenuRect.bind(_this);\n return _this;\n }\n\n (0, _createClass3.default)(ContextualMenu, [{\n key: 'collectContextMenuRect',\n value: function collectContextMenuRect(element) {\n // We don't need to clean up when unmounting, so ignore\n if (!element) return;\n\n this.setState({\n contextMenuRect: element.getBoundingClientRect()\n });\n }\n }, {\n key: 'onContextMenu',\n value: function onContextMenu(e) {\n if (this.props.closeMenu) {\n this.props.closeMenu();\n\n e.preventDefault();\n var x = e.clientX;\n var y = e.clientY;\n\n // XXX: This isn't pretty but the only way to allow opening a different context menu on right click whilst\n // a context menu and its click-guard are up without completely rewriting how the context menus work.\n (0, _setImmediate3.default)(function () {\n var clickEvent = document.createEvent('MouseEvents');\n clickEvent.initMouseEvent('contextmenu', true, true, window, 0, 0, 0, x, y, false, false, false, false, 0, null);\n document.elementFromPoint(x, y).dispatchEvent(clickEvent);\n });\n }\n }\n }, {\n key: 'render',\n value: function render() {\n var position = {};\n var chevronFace = null;\n var props = this.props;\n\n if (props.top) {\n position.top = props.top;\n } else {\n position.bottom = props.bottom;\n }\n\n if (props.left) {\n position.left = props.left;\n chevronFace = 'left';\n } else {\n position.right = props.right;\n chevronFace = 'right';\n }\n\n var contextMenuRect = this.state.contextMenuRect || null;\n var padding = 10;\n\n var chevronOffset = {};\n if (props.chevronFace) {\n chevronFace = props.chevronFace;\n }\n var hasChevron = chevronFace && chevronFace !== \"none\";\n\n if (chevronFace === 'top' || chevronFace === 'bottom') {\n chevronOffset.left = props.chevronOffset;\n } else {\n var target = position.top;\n\n // By default, no adjustment is made\n var adjusted = target;\n\n // If we know the dimensions of the context menu, adjust its position\n // such that it does not leave the (padded) window.\n if (contextMenuRect) {\n adjusted = Math.min(position.top, document.body.clientHeight - contextMenuRect.height - padding);\n }\n\n position.top = adjusted;\n chevronOffset.top = Math.max(props.chevronOffset, props.chevronOffset + target - adjusted);\n }\n\n // To override the default chevron colour, if it's been set\n var chevronCSS = \"\";\n if (props.menuColour) {\n chevronCSS = '\\n .mx_ContextualMenu_chevron_left:after {\\n border-right-color: ' + props.menuColour + ';\\n }\\n .mx_ContextualMenu_chevron_right:after {\\n border-left-color: ' + props.menuColour + ';\\n }\\n .mx_ContextualMenu_chevron_top:after {\\n border-left-color: ' + props.menuColour + ';\\n }\\n .mx_ContextualMenu_chevron_bottom:after {\\n border-left-color: ' + props.menuColour + ';\\n }\\n ';\n }\n\n var chevron = hasChevron ? _react2.default.createElement('div', { style: chevronOffset, className: \"mx_ContextualMenu_chevron_\" + chevronFace }) : undefined;\n var className = 'mx_ContextualMenu_wrapper';\n\n var menuClasses = (0, _classnames2.default)({\n 'mx_ContextualMenu': true,\n 'mx_ContextualMenu_noChevron': chevronFace === 'none',\n 'mx_ContextualMenu_left': chevronFace === 'left',\n 'mx_ContextualMenu_right': chevronFace === 'right',\n 'mx_ContextualMenu_top': chevronFace === 'top',\n 'mx_ContextualMenu_bottom': chevronFace === 'bottom'\n });\n\n var menuStyle = {};\n if (props.menuWidth) {\n menuStyle.width = props.menuWidth;\n }\n\n if (props.menuHeight) {\n menuStyle.height = props.menuHeight;\n }\n\n if (props.menuColour) {\n menuStyle[\"backgroundColor\"] = props.menuColour;\n }\n\n if (!isNaN(Number(props.menuPaddingTop))) {\n menuStyle[\"paddingTop\"] = props.menuPaddingTop;\n }\n if (!isNaN(Number(props.menuPaddingLeft))) {\n menuStyle[\"paddingLeft\"] = props.menuPaddingLeft;\n }\n if (!isNaN(Number(props.menuPaddingBottom))) {\n menuStyle[\"paddingBottom\"] = props.menuPaddingBottom;\n }\n if (!isNaN(Number(props.menuPaddingRight))) {\n menuStyle[\"paddingRight\"] = props.menuPaddingRight;\n }\n\n var wrapperStyle = {};\n if (!isNaN(Number(props.zIndex))) {\n menuStyle[\"zIndex\"] = props.zIndex + 1;\n wrapperStyle[\"zIndex\"] = props.zIndex;\n }\n\n var ElementClass = props.elementClass;\n\n // FIXME: If a menu uses getDefaultProps it clobbers the onFinished\n // property set here so you can't close the menu from a button click!\n return _react2.default.createElement(\n 'div',\n { className: className, style: (0, _extends3.default)({}, position, wrapperStyle) },\n _react2.default.createElement(\n 'div',\n { className: menuClasses, style: menuStyle, ref: this.collectContextMenuRect },\n chevron,\n _react2.default.createElement(ElementClass, (0, _extends3.default)({}, props, { onFinished: props.closeMenu, onResize: props.windowResize }))\n ),\n props.hasBackground && _react2.default.createElement('div', { className: 'mx_ContextualMenu_background', style: wrapperStyle,\n onClick: props.closeMenu, onContextMenu: this.onContextMenu }),\n _react2.default.createElement(\n 'style',\n null,\n chevronCSS\n )\n );\n }\n }]);\n return ContextualMenu;\n}(_react2.default.Component);\n\nexports.default = ContextualMenu;\nfunction createMenu(ElementClass, props) {\n var hasBackground = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n\n var closeMenu = function closeMenu() {\n _reactDom2.default.unmountComponentAtNode(getOrCreateContainer());\n\n if (props && props.onFinished) {\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n props.onFinished.apply(null, args);\n }\n };\n\n // We only reference closeMenu once per call to createMenu\n var menu = _react2.default.createElement(ContextualMenu, (0, _extends3.default)({\n hasBackground: hasBackground\n }, props, {\n elementClass: ElementClass,\n closeMenu: closeMenu // eslint-disable-line react/jsx-no-bind\n , windowResize: closeMenu // eslint-disable-line react/jsx-no-bind\n }));\n\n _reactDom2.default.render(menu, getOrCreateContainer());\n\n return { close: closeMenu };\n}\n//# sourceMappingURL=ContextualMenu.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.formatDate = formatDate;\nexports.formatFullDateNoTime = formatFullDateNoTime;\nexports.formatFullDate = formatFullDate;\nexports.formatFullTime = formatFullTime;\nexports.formatTime = formatTime;\nexports.wantsDateSeparator = wantsDateSeparator;\n\nvar _languageHandler = require('./languageHandler');\n\nfunction getDaysArray() {\n return [(0, _languageHandler._t)('Sun'), (0, _languageHandler._t)('Mon'), (0, _languageHandler._t)('Tue'), (0, _languageHandler._t)('Wed'), (0, _languageHandler._t)('Thu'), (0, _languageHandler._t)('Fri'), (0, _languageHandler._t)('Sat')];\n} /*\n Copyright 2015, 2016 OpenMarket Ltd\n Copyright 2017 Vector Creations Ltd\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nfunction getMonthsArray() {\n return [(0, _languageHandler._t)('Jan'), (0, _languageHandler._t)('Feb'), (0, _languageHandler._t)('Mar'), (0, _languageHandler._t)('Apr'), (0, _languageHandler._t)('May'), (0, _languageHandler._t)('Jun'), (0, _languageHandler._t)('Jul'), (0, _languageHandler._t)('Aug'), (0, _languageHandler._t)('Sep'), (0, _languageHandler._t)('Oct'), (0, _languageHandler._t)('Nov'), (0, _languageHandler._t)('Dec')];\n}\n\nfunction pad(n) {\n return (n < 10 ? '0' : '') + n;\n}\n\nfunction twelveHourTime(date) {\n var showSeconds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n var hours = date.getHours() % 12;\n var minutes = pad(date.getMinutes());\n var ampm = date.getHours() >= 12 ? (0, _languageHandler._t)('PM') : (0, _languageHandler._t)('AM');\n hours = hours ? hours : 12; // convert 0 -> 12\n if (showSeconds) {\n var seconds = pad(date.getSeconds());\n return hours + ':' + minutes + ':' + seconds + ampm;\n }\n return hours + ':' + minutes + ampm;\n}\n\nfunction formatDate(date) {\n var showTwelveHour = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n var now = new Date();\n var days = getDaysArray();\n var months = getMonthsArray();\n if (date.toDateString() === now.toDateString()) {\n return formatTime(date, showTwelveHour);\n } else if (now.getTime() - date.getTime() < 6 * 24 * 60 * 60 * 1000) {\n // TODO: use standard date localize function provided in counterpart\n return (0, _languageHandler._t)('%(weekDayName)s %(time)s', {\n weekDayName: days[date.getDay()],\n time: formatTime(date, showTwelveHour)\n });\n } else if (now.getFullYear() === date.getFullYear()) {\n // TODO: use standard date localize function provided in counterpart\n return (0, _languageHandler._t)('%(weekDayName)s, %(monthName)s %(day)s %(time)s', {\n weekDayName: days[date.getDay()],\n monthName: months[date.getMonth()],\n day: date.getDate(),\n time: formatTime(date, showTwelveHour)\n });\n }\n return formatFullDate(date, showTwelveHour);\n}\n\nfunction formatFullDateNoTime(date) {\n var days = getDaysArray();\n var months = getMonthsArray();\n return (0, _languageHandler._t)('%(weekDayName)s, %(monthName)s %(day)s %(fullYear)s', {\n weekDayName: days[date.getDay()],\n monthName: months[date.getMonth()],\n day: date.getDate(),\n fullYear: date.getFullYear()\n });\n}\n\nfunction formatFullDate(date) {\n var showTwelveHour = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n var days = getDaysArray();\n var months = getMonthsArray();\n return (0, _languageHandler._t)('%(weekDayName)s, %(monthName)s %(day)s %(fullYear)s %(time)s', {\n weekDayName: days[date.getDay()],\n monthName: months[date.getMonth()],\n day: date.getDate(),\n fullYear: date.getFullYear(),\n time: formatFullTime(date, showTwelveHour)\n });\n}\n\nfunction formatFullTime(date) {\n var showTwelveHour = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n if (showTwelveHour) {\n return twelveHourTime(date, true);\n }\n return pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds());\n}\n\nfunction formatTime(date) {\n var showTwelveHour = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n if (showTwelveHour) {\n return twelveHourTime(date);\n }\n return pad(date.getHours()) + ':' + pad(date.getMinutes());\n}\n\nvar MILLIS_IN_DAY = 86400000;\nfunction wantsDateSeparator(prevEventDate, nextEventDate) {\n if (!nextEventDate || !prevEventDate) {\n return false;\n }\n // Return early for events that are > 24h apart\n if (Math.abs(prevEventDate.getTime() - nextEventDate.getTime()) > MILLIS_IN_DAY) {\n return true;\n }\n\n // Compare weekdays\n return prevEventDate.getDay() !== nextEventDate.getDay();\n}\n//# sourceMappingURL=DateUtils.js.map","\"use strict\";\n\nexports.__esModule = true;\n\nexports.default = function (obj, keys) {\n var target = {};\n\n for (var i in obj) {\n if (keys.indexOf(i) >= 0) continue;\n if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;\n target[i] = obj[i];\n }\n\n return target;\n};","\"use strict\";\n\nfunction _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\n/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\n/**\n * Colors.\n */\n\nexports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n// eslint-disable-next-line complexity\n\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n return true;\n } // Internet Explorer and Edge do not support colors.\n\n\n if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n return false;\n } // Is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\n\n return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773\n typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker\n typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/);\n}\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\n\nfunction formatArgs(args) {\n args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);\n\n if (!this.useColors) {\n return;\n }\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit'); // The final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function (match) {\n if (match === '%%') {\n return;\n }\n\n index++;\n\n if (match === '%c') {\n // We only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n args.splice(lastC, 0, c);\n}\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\n\nfunction log() {\n var _console;\n\n // This hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return (typeof console === \"undefined\" ? \"undefined\" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);\n}\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\n\nfunction save(namespaces) {\n try {\n if (namespaces) {\n exports.storage.setItem('debug', namespaces);\n } else {\n exports.storage.removeItem('debug');\n }\n } catch (error) {// Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\n\nfunction load() {\n var r;\n\n try {\n r = exports.storage.getItem('debug');\n } catch (error) {} // Swallow\n // XXX (@Qix-) should we be logging these?\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\n\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\n\nfunction localstorage() {\n try {\n // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n // The Browser also has localStorage in the global context.\n return localStorage;\n } catch (error) {// Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\nmodule.exports = require('./common')(exports);\nvar formatters = module.exports.formatters;\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n try {\n return JSON.stringify(v);\n } catch (error) {\n return '[UnexpectedJSONParseError]: ' + error.message;\n }\n};\n\n","module.exports = false;\n","var META = require('./_uid')('meta');\nvar isObject = require('./_is-object');\nvar has = require('./_has');\nvar setDesc = require('./_object-dp').f;\nvar id = 0;\nvar isExtensible = Object.isExtensible || function () {\n return true;\n};\nvar FREEZE = !require('./_fails')(function () {\n return isExtensible(Object.preventExtensions({}));\n});\nvar setMeta = function (it) {\n setDesc(it, META, { value: {\n i: 'O' + ++id, // object ID\n w: {} // weak collections IDs\n } });\n};\nvar fastKey = function (it, create) {\n // return primitive with prefix\n if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;\n if (!has(it, META)) {\n // can't set metadata to uncaught frozen object\n if (!isExtensible(it)) return 'F';\n // not necessary to add metadata\n if (!create) return 'E';\n // add missing metadata\n setMeta(it);\n // return object ID\n } return it[META].i;\n};\nvar getWeak = function (it, create) {\n if (!has(it, META)) {\n // can't set metadata to uncaught frozen object\n if (!isExtensible(it)) return true;\n // not necessary to add metadata\n if (!create) return false;\n // add missing metadata\n setMeta(it);\n // return hash weak collections IDs\n } return it[META].w;\n};\n// add metadata on freeze-family methods calling\nvar onFreeze = function (it) {\n if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);\n return it;\n};\nvar meta = module.exports = {\n KEY: META,\n NEED: false,\n fastKey: fastKey,\n getWeak: getWeak,\n onFreeze: onFreeze\n};\n","// 22.1.3.31 Array.prototype[@@unscopables]\nvar UNSCOPABLES = require('./_wks')('unscopables');\nvar ArrayProto = Array.prototype;\nif (ArrayProto[UNSCOPABLES] == undefined) require('./_hide')(ArrayProto, UNSCOPABLES, {});\nmodule.exports = function (key) {\n ArrayProto[UNSCOPABLES][key] = true;\n};\n","var isObject = require('./_is-object');\nvar document = require('./_global').document;\n// typeof document.createElement is 'object' in old IE\nvar is = isObject(document) && isObject(document.createElement);\nmodule.exports = function (it) {\n return is ? document.createElement(it) : {};\n};\n","var META = require('./_uid')('meta');\nvar isObject = require('./_is-object');\nvar has = require('./_has');\nvar setDesc = require('./_object-dp').f;\nvar id = 0;\nvar isExtensible = Object.isExtensible || function () {\n return true;\n};\nvar FREEZE = !require('./_fails')(function () {\n return isExtensible(Object.preventExtensions({}));\n});\nvar setMeta = function (it) {\n setDesc(it, META, { value: {\n i: 'O' + ++id, // object ID\n w: {} // weak collections IDs\n } });\n};\nvar fastKey = function (it, create) {\n // return primitive with prefix\n if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;\n if (!has(it, META)) {\n // can't set metadata to uncaught frozen object\n if (!isExtensible(it)) return 'F';\n // not necessary to add metadata\n if (!create) return 'E';\n // add missing metadata\n setMeta(it);\n // return object ID\n } return it[META].i;\n};\nvar getWeak = function (it, create) {\n if (!has(it, META)) {\n // can't set metadata to uncaught frozen object\n if (!isExtensible(it)) return true;\n // not necessary to add metadata\n if (!create) return false;\n // add missing metadata\n setMeta(it);\n // return hash weak collections IDs\n } return it[META].w;\n};\n// add metadata on freeze-family methods calling\nvar onFreeze = function (it) {\n if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);\n return it;\n};\nvar meta = module.exports = {\n KEY: META,\n NEED: false,\n fastKey: fastKey,\n getWeak: getWeak,\n onFreeze: onFreeze\n};\n","module.exports = function(module) {\n\tif (!module.webpackPolyfill) {\n\t\tmodule.deprecate = function() {};\n\t\tmodule.paths = [];\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n","\"use strict\";\n\nexports.__esModule = true;\n\nvar _getPrototypeOf = require(\"../core-js/object/get-prototype-of\");\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _getOwnPropertyDescriptor = require(\"../core-js/object/get-own-property-descriptor\");\n\nvar _getOwnPropertyDescriptor2 = _interopRequireDefault(_getOwnPropertyDescriptor);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nexports.default = function get(object, property, receiver) {\n if (object === null) object = Function.prototype;\n var desc = (0, _getOwnPropertyDescriptor2.default)(object, property);\n\n if (desc === undefined) {\n var parent = (0, _getPrototypeOf2.default)(object);\n\n if (parent === null) {\n return undefined;\n } else {\n return get(parent, property, receiver);\n }\n } else if (\"value\" in desc) {\n return desc.value;\n } else {\n var getter = desc.get;\n\n if (getter === undefined) {\n return undefined;\n }\n\n return getter.call(receiver);\n }\n};","/**\n * Copyright 2013-2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n * @providesModule invariant\n */\n\n\"use strict\";\n\n/**\n * Use invariant() to assert state which your program assumes to be true.\n *\n * Provide sprintf-style format (only %s is supported) and arguments\n * to provide information about what broke and what you were\n * expecting.\n *\n * The invariant message will be stripped in production, but the invariant\n * will remain to ensure logic does not differ in production.\n */\n\nvar invariant = function (condition, format, a, b, c, d, e, f) {\n if (process.env.NODE_ENV !== 'production') {\n if (format === undefined) {\n throw new Error('invariant requires an error message argument');\n }\n }\n\n if (!condition) {\n var error;\n if (format === undefined) {\n error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');\n } else {\n var args = [a, b, c, d, e, f];\n var argIndex = 0;\n error = new Error('Invariant Violation: ' + format.replace(/%s/g, function () {\n return args[argIndex++];\n }));\n }\n\n error.framesToPop = 1; // we don't care about invariant's own frame\n throw error;\n }\n};\n\nmodule.exports = invariant;","'use strict';\n\nvar _getIterator2 = require('babel-runtime/core-js/get-iterator');\n\nvar _getIterator3 = _interopRequireDefault(_getIterator2);\n\nvar _MatrixClientPeg = require('./MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _PlatformPeg = require('./PlatformPeg');\n\nvar _PlatformPeg2 = _interopRequireDefault(_PlatformPeg);\n\nvar _TextForEvent = require('./TextForEvent');\n\nvar _TextForEvent2 = _interopRequireDefault(_TextForEvent);\n\nvar _Analytics = require('./Analytics');\n\nvar _Analytics2 = _interopRequireDefault(_Analytics);\n\nvar _Avatar = require('./Avatar');\n\nvar _Avatar2 = _interopRequireDefault(_Avatar);\n\nvar _dispatcher = require('./dispatcher');\n\nvar _dispatcher2 = _interopRequireDefault(_dispatcher);\n\nvar _index = require('./index');\n\nvar _index2 = _interopRequireDefault(_index);\n\nvar _languageHandler = require('./languageHandler');\n\nvar _Modal = require('./Modal');\n\nvar _Modal2 = _interopRequireDefault(_Modal);\n\nvar _SettingsStore = require('./settings/SettingsStore');\n\nvar _SettingsStore2 = _interopRequireDefault(_SettingsStore);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\n * Dispatches:\n * {\n * action: \"notifier_enabled\",\n * value: boolean\n * }\n */\n\n/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar MAX_PENDING_ENCRYPTED = 20;\n\nvar Notifier = {\n notifsByRoom: {},\n\n // A list of event IDs that we've received but need to wait until\n // they're decrypted until we decide whether to notify for them\n // or not\n pendingEncryptedEventIds: [],\n\n notificationMessageForEvent: function notificationMessageForEvent(ev) {\n return _TextForEvent2.default.textForEvent(ev);\n },\n\n _displayPopupNotification: function _displayPopupNotification(ev, room) {\n var plaf = _PlatformPeg2.default.get();\n if (!plaf) {\n return;\n }\n if (!plaf.supportsNotifications() || !plaf.maySendNotifications()) {\n return;\n }\n if (global.document.hasFocus()) {\n return;\n }\n\n var msg = this.notificationMessageForEvent(ev);\n if (!msg) return;\n\n var title = void 0;\n if (!ev.sender || room.name === ev.sender.name) {\n title = room.name;\n // notificationMessageForEvent includes sender,\n // but we already have the sender here\n if (ev.getContent().body) msg = ev.getContent().body;\n } else if (ev.getType() === 'm.room.member') {\n // context is all in the message here, we don't need\n // to display sender info\n title = room.name;\n } else if (ev.sender) {\n title = ev.sender.name + \" (\" + room.name + \")\";\n // notificationMessageForEvent includes sender,\n // but we've just out sender in the title\n if (ev.getContent().body) msg = ev.getContent().body;\n }\n\n if (!this.isBodyEnabled()) {\n msg = '';\n }\n\n var avatarUrl = ev.sender ? _Avatar2.default.avatarUrlForMember(ev.sender, 40, 40, 'crop') : null;\n var notif = plaf.displayNotification(title, msg, avatarUrl, room);\n\n // if displayNotification returns non-null, the platform supports\n // clearing notifications later, so keep track of this.\n if (notif) {\n if (this.notifsByRoom[ev.getRoomId()] === undefined) this.notifsByRoom[ev.getRoomId()] = [];\n this.notifsByRoom[ev.getRoomId()].push(notif);\n }\n },\n\n _playAudioNotification: function _playAudioNotification(ev, room) {\n var e = document.getElementById(\"messageAudio\");\n if (e) {\n e.play();\n }\n },\n\n start: function start() {\n this.boundOnEvent = this.onEvent.bind(this);\n this.boundOnSyncStateChange = this.onSyncStateChange.bind(this);\n this.boundOnRoomReceipt = this.onRoomReceipt.bind(this);\n this.boundOnEventDecrypted = this.onEventDecrypted.bind(this);\n _MatrixClientPeg2.default.get().on('event', this.boundOnEvent);\n _MatrixClientPeg2.default.get().on('Room.receipt', this.boundOnRoomReceipt);\n _MatrixClientPeg2.default.get().on('Event.decrypted', this.boundOnEventDecrypted);\n _MatrixClientPeg2.default.get().on(\"sync\", this.boundOnSyncStateChange);\n this.toolbarHidden = false;\n this.isSyncing = false;\n },\n\n stop: function stop() {\n if (_MatrixClientPeg2.default.get() && this.boundOnRoomTimeline) {\n _MatrixClientPeg2.default.get().removeListener('Event', this.boundOnEvent);\n _MatrixClientPeg2.default.get().removeListener('Room.receipt', this.boundOnRoomReceipt);\n _MatrixClientPeg2.default.get().removeListener('Event.decrypted', this.boundOnEventDecrypted);\n _MatrixClientPeg2.default.get().removeListener('sync', this.boundOnSyncStateChange);\n }\n this.isSyncing = false;\n },\n\n supportsDesktopNotifications: function supportsDesktopNotifications() {\n var plaf = _PlatformPeg2.default.get();\n return plaf && plaf.supportsNotifications();\n },\n\n setEnabled: function setEnabled(enable, callback) {\n var plaf = _PlatformPeg2.default.get();\n if (!plaf) return;\n\n // Dev note: We don't set the \"notificationsEnabled\" setting to true here because it is a\n // calculated value. It is determined based upon whether or not the master rule is enabled\n // and other flags. Setting it here would cause a circular reference.\n\n _Analytics2.default.trackEvent('Notifier', 'Set Enabled', enable);\n\n // make sure that we persist the current setting audio_enabled setting\n // before changing anything\n if (_SettingsStore2.default.isLevelSupported(_SettingsStore.SettingLevel.DEVICE)) {\n _SettingsStore2.default.setValue(\"audioNotificationsEnabled\", null, _SettingsStore.SettingLevel.DEVICE, this.isEnabled());\n }\n\n if (enable) {\n // Attempt to get permission from user\n plaf.requestNotificationPermission().done(function (result) {\n if (result !== 'granted') {\n // The permission request was dismissed or denied\n // TODO: Support alternative branding in messaging\n var description = result === 'denied' ? (0, _languageHandler._t)('Riot does not have permission to send you notifications - please check your browser settings') : (0, _languageHandler._t)('Riot was not given permission to send notifications - please try again');\n var ErrorDialog = _index2.default.getComponent('dialogs.ErrorDialog');\n _Modal2.default.createTrackedDialog('Unable to enable Notifications', result, ErrorDialog, {\n title: (0, _languageHandler._t)('Unable to enable Notifications'),\n description: description\n });\n return;\n }\n\n if (callback) callback();\n _dispatcher2.default.dispatch({\n action: \"notifier_enabled\",\n value: true\n });\n });\n } else {\n _dispatcher2.default.dispatch({\n action: \"notifier_enabled\",\n value: false\n });\n }\n // set the notifications_hidden flag, as the user has knowingly interacted\n // with the setting we shouldn't nag them any further\n this.setToolbarHidden(true);\n },\n\n isEnabled: function isEnabled() {\n return this.isPossible() && _SettingsStore2.default.getValue(\"notificationsEnabled\");\n },\n\n isPossible: function isPossible() {\n var plaf = _PlatformPeg2.default.get();\n if (!plaf) return false;\n if (!plaf.supportsNotifications()) return false;\n if (!plaf.maySendNotifications()) return false;\n\n return true; // possible, but not necessarily enabled\n },\n\n isBodyEnabled: function isBodyEnabled() {\n return this.isEnabled() && _SettingsStore2.default.getValue(\"notificationBodyEnabled\");\n },\n\n isAudioEnabled: function isAudioEnabled() {\n return this.isEnabled() && _SettingsStore2.default.getValue(\"audioNotificationsEnabled\");\n },\n\n setToolbarHidden: function setToolbarHidden(hidden) {\n var persistent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n\n this.toolbarHidden = hidden;\n\n _Analytics2.default.trackEvent('Notifier', 'Set Toolbar Hidden', hidden);\n\n // XXX: why are we dispatching this here?\n // this is nothing to do with notifier_enabled\n _dispatcher2.default.dispatch({\n action: \"notifier_enabled\",\n value: this.isEnabled()\n });\n\n // update the info to localStorage for persistent settings\n if (persistent && global.localStorage) {\n global.localStorage.setItem(\"notifications_hidden\", hidden);\n }\n },\n\n shouldShowToolbar: function shouldShowToolbar() {\n var client = _MatrixClientPeg2.default.get();\n if (!client) {\n return false;\n }\n var isGuest = client.isGuest();\n return !isGuest && this.supportsDesktopNotifications() && !this.isEnabled() && !this._isToolbarHidden();\n },\n\n _isToolbarHidden: function _isToolbarHidden() {\n // Check localStorage for any such meta data\n if (global.localStorage) {\n return global.localStorage.getItem(\"notifications_hidden\") === \"true\";\n }\n\n return this.toolbarHidden;\n },\n\n onSyncStateChange: function onSyncStateChange(state) {\n if (state === \"SYNCING\") {\n this.isSyncing = true;\n } else if (state === \"STOPPED\" || state === \"ERROR\") {\n this.isSyncing = false;\n }\n },\n\n onEvent: function onEvent(ev) {\n if (!this.isSyncing) return; // don't alert for any messages initially\n if (ev.sender && ev.sender.userId === _MatrixClientPeg2.default.get().credentials.userId) return;\n\n // If it's an encrypted event and the type is still 'm.room.encrypted',\n // it hasn't yet been decrypted, so wait until it is.\n if (ev.isBeingDecrypted() || ev.isDecryptionFailure()) {\n this.pendingEncryptedEventIds.push(ev.getId());\n // don't let the list fill up indefinitely\n while (this.pendingEncryptedEventIds.length > MAX_PENDING_ENCRYPTED) {\n this.pendingEncryptedEventIds.shift();\n }\n return;\n }\n\n this._evaluateEvent(ev);\n },\n\n onEventDecrypted: function onEventDecrypted(ev) {\n // 'decrypted' means the decryption process has finished: it may have failed,\n // in which case it might decrypt soon if the keys arrive\n if (ev.isDecryptionFailure()) return;\n\n var idx = this.pendingEncryptedEventIds.indexOf(ev.getId());\n if (idx === -1) return;\n\n this.pendingEncryptedEventIds.splice(idx, 1);\n this._evaluateEvent(ev);\n },\n\n onRoomReceipt: function onRoomReceipt(ev, room) {\n if (room.getUnreadNotificationCount() === 0) {\n // ideally we would clear each notification when it was read,\n // but we have no way, given a read receipt, to know whether\n // the receipt comes before or after an event, so we can't\n // do this. Instead, clear all notifications for a room once\n // there are no notifs left in that room., which is not quite\n // as good but it's something.\n var plaf = _PlatformPeg2.default.get();\n if (!plaf) return;\n if (this.notifsByRoom[room.roomId] === undefined) return;\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = (0, _getIterator3.default)(this.notifsByRoom[room.roomId]), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var notif = _step.value;\n\n plaf.clearNotification(notif);\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n delete this.notifsByRoom[room.roomId];\n }\n },\n\n _evaluateEvent: function _evaluateEvent(ev) {\n var room = _MatrixClientPeg2.default.get().getRoom(ev.getRoomId());\n var actions = _MatrixClientPeg2.default.get().getPushActionsForEvent(ev);\n if (actions && actions.notify) {\n if (this.isEnabled()) {\n this._displayPopupNotification(ev, room);\n }\n if (actions.tweaks.sound && this.isAudioEnabled()) {\n _PlatformPeg2.default.get().loudNotification(ev, room);\n this._playAudioNotification(ev, room);\n }\n }\n }\n};\n\nif (!global.mxNotifier) {\n global.mxNotifier = Notifier;\n}\n\nmodule.exports = global.mxNotifier;\n//# sourceMappingURL=Notifier.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _regenerator = require('babel-runtime/regenerator');\n\nvar _regenerator2 = _interopRequireDefault(_regenerator);\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nvar _bluebird = require('bluebird');\n\nvar _bluebird2 = _interopRequireDefault(_bluebird);\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _events = require('events');\n\nvar _events2 = _interopRequireDefault(_events);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar BULK_REQUEST_DEBOUNCE_MS = 200;\n\n// Does the server support groups? Assume yes until we receive M_UNRECOGNIZED.\n// If true, flair can function and we should keep sending requests for groups and avatars.\nvar _groupSupport = true;\n\nvar USER_GROUPS_CACHE_BUST_MS = 1800000; // 30 mins\nvar GROUP_PROFILES_CACHE_BUST_MS = 1800000; // 30 mins\n\n/**\n * Stores data used by \n */\n\nvar FlairStore = function (_EventEmitter) {\n (0, _inherits3.default)(FlairStore, _EventEmitter);\n\n function FlairStore(matrixClient) {\n (0, _classCallCheck3.default)(this, FlairStore);\n\n var _this = (0, _possibleConstructorReturn3.default)(this, (FlairStore.__proto__ || (0, _getPrototypeOf2.default)(FlairStore)).call(this));\n\n _this._matrixClient = matrixClient;\n _this._userGroups = {\n // $userId: ['+group1:domain', '+group2:domain', ...]\n };\n _this._groupProfiles = {\n // $groupId: {\n // avatar_url: 'mxc://...'\n // }\n };\n _this._groupProfilesPromise = {\n // $groupId: Promise\n };\n _this._usersPending = {\n // $userId: {\n // prom: Promise\n // resolve: () => {}\n // reject: () => {}\n // }\n };\n _this._usersInFlight = {\n // This has the same schema as _usersPending\n };\n\n _this._debounceTimeoutID = null;\n return _this;\n }\n\n (0, _createClass3.default)(FlairStore, [{\n key: 'groupSupport',\n value: function groupSupport() {\n return _groupSupport;\n }\n }, {\n key: 'invalidatePublicisedGroups',\n value: function invalidatePublicisedGroups(userId) {\n delete this._userGroups[userId];\n }\n }, {\n key: 'getPublicisedGroupsCached',\n value: function getPublicisedGroupsCached(matrixClient, userId) {\n var _this2 = this;\n\n if (this._userGroups[userId]) {\n return _bluebird2.default.resolve(this._userGroups[userId]);\n }\n\n // Bulk lookup ongoing, return promise to resolve/reject\n if (this._usersPending[userId]) {\n return this._usersPending[userId].prom;\n }\n // User has been moved from pending to in-flight\n if (this._usersInFlight[userId]) {\n return this._usersInFlight[userId].prom;\n }\n\n this._usersPending[userId] = {};\n this._usersPending[userId].prom = new _bluebird2.default(function (resolve, reject) {\n _this2._usersPending[userId].resolve = resolve;\n _this2._usersPending[userId].reject = reject;\n }).then(function (groups) {\n _this2._userGroups[userId] = groups;\n setTimeout(function () {\n delete _this2._userGroups[userId];\n }, USER_GROUPS_CACHE_BUST_MS);\n return _this2._userGroups[userId];\n }).catch(function (err) {\n // Indicate whether the homeserver supports groups\n if (err.errcode === 'M_UNRECOGNIZED') {\n console.warn('Cannot display flair, server does not support groups');\n _groupSupport = false;\n // Return silently to avoid spamming for non-supporting servers\n return;\n }\n console.error('Could not get groups for user', userId, err);\n throw err;\n }).finally(function () {\n delete _this2._usersInFlight[userId];\n });\n\n // This debounce will allow consecutive requests for the public groups of users that\n // are sent in intervals of < BULK_REQUEST_DEBOUNCE_MS to be batched and only requested\n // when no more requests are received within the next BULK_REQUEST_DEBOUNCE_MS. The naive\n // implementation would do a request that only requested the groups for `userId`, leading\n // to a worst and best case of 1 user per request. This implementation's worst is still\n // 1 user per request but only if the requests are > BULK_REQUEST_DEBOUNCE_MS apart and the\n // best case is N users per request.\n //\n // This is to reduce the number of requests made whilst trading off latency when viewing\n // a Flair component.\n if (this._debounceTimeoutID) clearTimeout(this._debounceTimeoutID);\n this._debounceTimeoutID = setTimeout(function () {\n _this2._batchedGetPublicGroups(matrixClient);\n }, BULK_REQUEST_DEBOUNCE_MS);\n\n return this._usersPending[userId].prom;\n }\n }, {\n key: '_batchedGetPublicGroups',\n value: function () {\n var _ref = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee(matrixClient) {\n var _this3 = this;\n\n var resp, updatedUserGroups;\n return _regenerator2.default.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n // Move users pending to users in flight\n this._usersInFlight = this._usersPending;\n this._usersPending = {};\n\n resp = {\n users: []\n };\n _context.prev = 3;\n _context.next = 6;\n return (0, _bluebird.resolve)(matrixClient.getPublicisedGroups((0, _keys2.default)(this._usersInFlight)));\n\n case 6:\n resp = _context.sent;\n _context.next = 13;\n break;\n\n case 9:\n _context.prev = 9;\n _context.t0 = _context['catch'](3);\n\n // Propagate the same error to all usersInFlight\n (0, _keys2.default)(this._usersInFlight).forEach(function (userId) {\n // The promise should always exist for userId, but do a null-check anyway\n if (!_this3._usersInFlight[userId]) return;\n _this3._usersInFlight[userId].reject(_context.t0);\n });\n return _context.abrupt('return');\n\n case 13:\n updatedUserGroups = resp.users;\n\n (0, _keys2.default)(this._usersInFlight).forEach(function (userId) {\n // The promise should always exist for userId, but do a null-check anyway\n if (!_this3._usersInFlight[userId]) return;\n _this3._usersInFlight[userId].resolve(updatedUserGroups[userId] || []);\n });\n\n case 15:\n case 'end':\n return _context.stop();\n }\n }\n }, _callee, this, [[3, 9]]);\n }));\n\n function _batchedGetPublicGroups(_x) {\n return _ref.apply(this, arguments);\n }\n\n return _batchedGetPublicGroups;\n }()\n }, {\n key: 'getGroupProfileCached',\n value: function () {\n var _ref2 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(matrixClient, groupId) {\n var _this4 = this;\n\n var profile;\n return _regenerator2.default.wrap(function _callee2$(_context2) {\n while (1) {\n switch (_context2.prev = _context2.next) {\n case 0:\n if (!this._groupProfiles[groupId]) {\n _context2.next = 2;\n break;\n }\n\n return _context2.abrupt('return', this._groupProfiles[groupId]);\n\n case 2:\n if (!this._groupProfilesPromise[groupId]) {\n _context2.next = 12;\n break;\n }\n\n _context2.prev = 3;\n _context2.next = 6;\n return (0, _bluebird.resolve)(this._groupProfilesPromise[groupId]);\n\n case 6:\n _context2.next = 11;\n break;\n\n case 8:\n _context2.prev = 8;\n _context2.t0 = _context2['catch'](3);\n return _context2.abrupt('return', null);\n\n case 11:\n return _context2.abrupt('return', this._groupProfiles[groupId]);\n\n case 12:\n\n // No request yet, start one\n console.log('FlairStore: Request group profile of ' + groupId);\n this._groupProfilesPromise[groupId] = matrixClient.getGroupProfile(groupId);\n\n profile = void 0;\n _context2.prev = 15;\n _context2.next = 18;\n return (0, _bluebird.resolve)(this._groupProfilesPromise[groupId]);\n\n case 18:\n profile = _context2.sent;\n _context2.next = 26;\n break;\n\n case 21:\n _context2.prev = 21;\n _context2.t1 = _context2['catch'](15);\n\n console.log('FlairStore: Failed to get group profile for ' + groupId, _context2.t1);\n // Don't retry, but allow a retry when the profile is next requested\n delete this._groupProfilesPromise[groupId];\n return _context2.abrupt('return', null);\n\n case 26:\n\n this._groupProfiles[groupId] = {\n groupId: groupId,\n avatarUrl: profile.avatar_url,\n name: profile.name,\n shortDescription: profile.short_description\n };\n delete this._groupProfilesPromise[groupId];\n\n /// XXX: This is verging on recreating a third \"Flux\"-looking Store. We really\n /// should replace FlairStore with a Flux store and some async actions.\n console.log('FlairStore: Emit updateGroupProfile for ' + groupId);\n this.emit('updateGroupProfile');\n\n setTimeout(function () {\n _this4.refreshGroupProfile(matrixClient, groupId);\n }, GROUP_PROFILES_CACHE_BUST_MS);\n\n return _context2.abrupt('return', this._groupProfiles[groupId]);\n\n case 32:\n case 'end':\n return _context2.stop();\n }\n }\n }, _callee2, this, [[3, 8], [15, 21]]);\n }));\n\n function getGroupProfileCached(_x2, _x3) {\n return _ref2.apply(this, arguments);\n }\n\n return getGroupProfileCached;\n }()\n }, {\n key: 'refreshGroupProfile',\n value: function refreshGroupProfile(matrixClient, groupId) {\n // Invalidate the cache\n delete this._groupProfiles[groupId];\n // Fetch new profile data, and cache it\n return this.getGroupProfileCached(matrixClient, groupId);\n }\n }]);\n return FlairStore;\n}(_events2.default);\n\nif (global.singletonFlairStore === undefined) {\n global.singletonFlairStore = new FlairStore();\n}\nexports.default = global.singletonFlairStore;\nmodule.exports = exports['default'];\n//# sourceMappingURL=FlairStore.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _getIterator2 = require('babel-runtime/core-js/get-iterator');\n\nvar _getIterator3 = _interopRequireDefault(_getIterator2);\n\nvar _keys = require('babel-runtime/core-js/object/keys');\n\nvar _keys2 = _interopRequireDefault(_keys);\n\nexports.getDisplayAliasForRoom = getDisplayAliasForRoom;\nexports.getOnlyOtherMember = getOnlyOtherMember;\nexports.isConfCallRoom = isConfCallRoom;\nexports.looksLikeDirectMessageRoom = looksLikeDirectMessageRoom;\nexports.guessAndSetDMRoom = guessAndSetDMRoom;\nexports.setDMRoom = setDMRoom;\n\nvar _MatrixClientPeg = require('./MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _bluebird = require('bluebird');\n\nvar _bluebird2 = _interopRequireDefault(_bluebird);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Given a room object, return the alias we should use for it,\n * if any. This could be the canonical alias if one exists, otherwise\n * an alias selected arbitrarily but deterministically from the list\n * of aliases. Otherwise return null;\n */\n/*\nCopyright 2015, 2016 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nfunction getDisplayAliasForRoom(room) {\n return room.getCanonicalAlias() || room.getAliases()[0];\n}\n\n/**\n * If the room contains only two members including the logged-in user,\n * return the other one. Otherwise, return null.\n */\nfunction getOnlyOtherMember(room, myUserId) {\n if (room.currentState.getJoinedMemberCount() === 2) {\n return room.getJoinedMembers().filter(function (m) {\n return m.userId !== myUserId;\n })[0];\n }\n\n return null;\n}\n\nfunction _isConfCallRoom(room, myUserId, conferenceHandler) {\n if (!conferenceHandler) return false;\n\n var myMembership = room.getMyMembership();\n if (myMembership != \"join\") {\n return false;\n }\n\n var otherMember = getOnlyOtherMember(room, myUserId);\n if (!otherMember) {\n return false;\n }\n\n if (conferenceHandler.isConferenceUser(otherMember.userId)) {\n return true;\n }\n\n return false;\n}\n\n// Cache whether a room is a conference call. Assumes that rooms will always\n// either will or will not be a conference call room.\nvar isConfCallRoomCache = {\n // $roomId: bool\n};\n\nfunction isConfCallRoom(room, myUserId, conferenceHandler) {\n if (isConfCallRoomCache[room.roomId] !== undefined) {\n return isConfCallRoomCache[room.roomId];\n }\n\n var result = _isConfCallRoom(room, myUserId, conferenceHandler);\n\n isConfCallRoomCache[room.roomId] = result;\n\n return result;\n}\n\nfunction looksLikeDirectMessageRoom(room, myUserId) {\n var myMembership = room.getMyMembership();\n var me = room.getMember(myUserId);\n\n if (myMembership == \"join\" || myMembership === \"ban\" || me && me.isKicked()) {\n // Used to split rooms via tags\n var tagNames = (0, _keys2.default)(room.tags);\n // Used for 1:1 direct chats\n // Show 1:1 chats in seperate \"Direct Messages\" section as long as they haven't\n // been moved to a different tag section\n var totalMemberCount = room.currentState.getJoinedMemberCount() + room.currentState.getInvitedMemberCount();\n if (totalMemberCount === 2 && !tagNames.length) {\n return true;\n }\n }\n return false;\n}\n\nfunction guessAndSetDMRoom(room, isDirect) {\n var newTarget = void 0;\n if (isDirect) {\n var guessedUserId = guessDMRoomTargetId(room, _MatrixClientPeg2.default.get().getUserId());\n newTarget = guessedUserId;\n } else {\n newTarget = null;\n }\n\n return setDMRoom(room.roomId, newTarget);\n}\n\n/**\n * Marks or unmarks the given room as being as a DM room.\n * @param {string} roomId The ID of the room to modify\n * @param {string} userId The user ID of the desired DM\n room target user or null to un-mark\n this room as a DM room\n * @returns {object} A promise\n */\nfunction setDMRoom(roomId, userId) {\n if (_MatrixClientPeg2.default.get().isGuest()) {\n return _bluebird2.default.resolve();\n }\n\n var mDirectEvent = _MatrixClientPeg2.default.get().getAccountData('m.direct');\n var dmRoomMap = {};\n\n if (mDirectEvent !== undefined) dmRoomMap = mDirectEvent.getContent();\n\n // remove it from the lists of any others users\n // (it can only be a DM room for one person)\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = (0, _getIterator3.default)((0, _keys2.default)(dmRoomMap)), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var thisUserId = _step.value;\n\n var _roomList = dmRoomMap[thisUserId];\n\n if (thisUserId != userId) {\n var indexOfRoom = _roomList.indexOf(roomId);\n if (indexOfRoom > -1) {\n _roomList.splice(indexOfRoom, 1);\n }\n }\n }\n\n // now add it, if it's not already there\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n if (userId) {\n var roomList = dmRoomMap[userId] || [];\n if (roomList.indexOf(roomId) == -1) {\n roomList.push(roomId);\n }\n dmRoomMap[userId] = roomList;\n }\n\n return _MatrixClientPeg2.default.get().setAccountData('m.direct', dmRoomMap);\n}\n\n/**\n * Given a room, estimate which of its members is likely to\n * be the target if the room were a DM room and return that user.\n *\n * @param {Object} room Target room\n * @param {string} myUserId User ID of the current user\n * @returns {string} User ID of the user that the room is probably a DM with\n */\nfunction guessDMRoomTargetId(room, myUserId) {\n var oldestTs = void 0;\n var oldestUser = void 0;\n\n // Pick the joined user who's been here longest (and isn't us),\n var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n for (var _iterator2 = (0, _getIterator3.default)(room.getJoinedMembers()), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n var user = _step2.value;\n\n if (user.userId == myUserId) continue;\n\n if (oldestTs === undefined || user.events.member && user.events.member.getTs() < oldestTs) {\n oldestUser = user;\n oldestTs = user.events.member.getTs();\n }\n }\n } catch (err) {\n _didIteratorError2 = true;\n _iteratorError2 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion2 && _iterator2.return) {\n _iterator2.return();\n }\n } finally {\n if (_didIteratorError2) {\n throw _iteratorError2;\n }\n }\n }\n\n if (oldestUser) return oldestUser.userId;\n\n // if there are no joined members other than us, use the oldest member\n var _iteratorNormalCompletion3 = true;\n var _didIteratorError3 = false;\n var _iteratorError3 = undefined;\n\n try {\n for (var _iterator3 = (0, _getIterator3.default)(room.currentState.getMembers()), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {\n var _user = _step3.value;\n\n if (_user.userId == myUserId) continue;\n\n if (oldestTs === undefined || _user.events.member && _user.events.member.getTs() < oldestTs) {\n oldestUser = _user;\n oldestTs = _user.events.member.getTs();\n }\n }\n } catch (err) {\n _didIteratorError3 = true;\n _iteratorError3 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion3 && _iterator3.return) {\n _iterator3.return();\n }\n } finally {\n if (_didIteratorError3) {\n throw _iteratorError3;\n }\n }\n }\n\n if (oldestUser === undefined) return myUserId;\n return oldestUser.userId;\n}\n//# sourceMappingURL=Rooms.js.map","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _getArea = require('../get-area');\n\nvar _getArea2 = _interopRequireDefault(_getArea);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nexports.default = function () {\n var top = window.pageYOffset;\n var left = window.pageXOffset;\n var width = window.innerWidth;\n var height = window.innerHeight;\n\n var right = left + width;\n var bottom = top + height;\n\n return (0, _getArea2.default)({\n top: top, left: left, right: right, bottom: bottom\n });\n};","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar prefix = function prefix(key) {\n return 'private-react-beautiful-dnd-key-do-not-use-' + key;\n};\n\nvar storeKey = exports.storeKey = prefix('store');\nvar droppableIdKey = exports.droppableIdKey = prefix('droppable-id');\nvar dimensionMarshalKey = exports.dimensionMarshalKey = prefix('dimension-marshal');\nvar styleContextKey = exports.styleContextKey = prefix('style-context');\nvar canLiftContextKey = exports.canLiftContextKey = prefix('can-lift');","module.exports = function (bitmap, value) {\n return {\n enumerable: !(bitmap & 1),\n configurable: !(bitmap & 2),\n writable: !(bitmap & 4),\n value: value\n };\n};\n","var id = 0;\nvar px = Math.random();\nmodule.exports = function (key) {\n return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));\n};\n","// 19.1.2.14 / 15.2.3.14 Object.keys(O)\nvar $keys = require('./_object-keys-internal');\nvar enumBugKeys = require('./_enum-bug-keys');\n\nmodule.exports = Object.keys || function keys(O) {\n return $keys(O, enumBugKeys);\n};\n","var toInteger = require('./_to-integer');\nvar max = Math.max;\nvar min = Math.min;\nmodule.exports = function (index, length) {\n index = toInteger(index);\n return index < 0 ? max(index + length, 0) : min(index, length);\n};\n","// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])\nvar anObject = require('./_an-object');\nvar dPs = require('./_object-dps');\nvar enumBugKeys = require('./_enum-bug-keys');\nvar IE_PROTO = require('./_shared-key')('IE_PROTO');\nvar Empty = function () { /* empty */ };\nvar PROTOTYPE = 'prototype';\n\n// Create object with fake `null` prototype: use iframe Object with cleared prototype\nvar createDict = function () {\n // Thrash, waste and sodomy: IE GC bug\n var iframe = require('./_dom-create')('iframe');\n var i = enumBugKeys.length;\n var lt = '<';\n var gt = '>';\n var iframeDocument;\n iframe.style.display = 'none';\n require('./_html').appendChild(iframe);\n iframe.src = 'javascript:'; // eslint-disable-line no-script-url\n // createDict = iframe.contentWindow.Object;\n // html.removeChild(iframe);\n iframeDocument = iframe.contentWindow.document;\n iframeDocument.open();\n iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);\n iframeDocument.close();\n createDict = iframeDocument.F;\n while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];\n return createDict();\n};\n\nmodule.exports = Object.create || function create(O, Properties) {\n var result;\n if (O !== null) {\n Empty[PROTOTYPE] = anObject(O);\n result = new Empty();\n Empty[PROTOTYPE] = null;\n // add \"__proto__\" for Object.getPrototypeOf polyfill\n result[IE_PROTO] = O;\n } else result = createDict();\n return Properties === undefined ? result : dPs(result, Properties);\n};\n","// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)\nvar $keys = require('./_object-keys-internal');\nvar hiddenKeys = require('./_enum-bug-keys').concat('length', 'prototype');\n\nexports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {\n return $keys(O, hiddenKeys);\n};\n","'use strict';\nvar global = require('./_global');\nvar dP = require('./_object-dp');\nvar DESCRIPTORS = require('./_descriptors');\nvar SPECIES = require('./_wks')('species');\n\nmodule.exports = function (KEY) {\n var C = global[KEY];\n if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {\n configurable: true,\n get: function () { return this; }\n });\n};\n","module.exports = function (it, Constructor, name, forbiddenField) {\n if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) {\n throw TypeError(name + ': incorrect invocation!');\n } return it;\n};\n","var ctx = require('./_ctx');\nvar call = require('./_iter-call');\nvar isArrayIter = require('./_is-array-iter');\nvar anObject = require('./_an-object');\nvar toLength = require('./_to-length');\nvar getIterFn = require('./core.get-iterator-method');\nvar BREAK = {};\nvar RETURN = {};\nvar exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {\n var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable);\n var f = ctx(fn, that, entries ? 2 : 1);\n var index = 0;\n var length, step, iterator, result;\n if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!');\n // fast case for arrays with default iterator\n if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) {\n result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);\n if (result === BREAK || result === RETURN) return result;\n } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {\n result = call(iterator, f, step.value, entries);\n if (result === BREAK || result === RETURN) return result;\n }\n};\nexports.BREAK = BREAK;\nexports.RETURN = RETURN;\n","var redefine = require('./_redefine');\nmodule.exports = function (target, src, safe) {\n for (var key in src) redefine(target, key, src[key], safe);\n return target;\n};\n","var isObject = require('./_is-object');\nmodule.exports = function (it, TYPE) {\n if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!');\n return it;\n};\n","module.exports = !require('./_descriptors') && !require('./_fails')(function () {\n return Object.defineProperty(require('./_dom-create')('div'), 'a', { get: function () { return 7; } }).a != 7;\n});\n","var has = require('./_has');\nvar toIObject = require('./_to-iobject');\nvar arrayIndexOf = require('./_array-includes')(false);\nvar IE_PROTO = require('./_shared-key')('IE_PROTO');\n\nmodule.exports = function (object, names) {\n var O = toIObject(object);\n var i = 0;\n var result = [];\n var key;\n for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);\n // Don't enum bug & hidden keys\n while (names.length > i) if (has(O, key = names[i++])) {\n ~arrayIndexOf(result, key) || result.push(key);\n }\n return result;\n};\n","// fallback for non-array-like ES3 and non-enumerable old V8 strings\nvar cof = require('./_cof');\n// eslint-disable-next-line no-prototype-builtins\nmodule.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {\n return cof(it) == 'String' ? it.split('') : Object(it);\n};\n","// getting tag from 19.1.3.6 Object.prototype.toString()\nvar cof = require('./_cof');\nvar TAG = require('./_wks')('toStringTag');\n// ES3 wrong here\nvar ARG = cof(function () { return arguments; }()) == 'Arguments';\n\n// fallback for IE11 Script Access Denied error\nvar tryGet = function (it, key) {\n try {\n return it[key];\n } catch (e) { /* empty */ }\n};\n\nmodule.exports = function (it) {\n var O, T, B;\n return it === undefined ? 'Undefined' : it === null ? 'Null'\n // @@toStringTag case\n : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T\n // builtinTag case\n : ARG ? cof(O)\n // ES3 arguments fallback\n : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;\n};\n","exports.f = require('./_wks');\n","var global = require('./_global');\nvar core = require('./_core');\nvar LIBRARY = require('./_library');\nvar wksExt = require('./_wks-ext');\nvar defineProperty = require('./_object-dp').f;\nmodule.exports = function (name) {\n var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});\n if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\n'use strict';\n\nvar _assign = require('object-assign');\n\nvar ReactBaseClasses = require('./ReactBaseClasses');\nvar ReactChildren = require('./ReactChildren');\nvar ReactDOMFactories = require('./ReactDOMFactories');\nvar ReactElement = require('./ReactElement');\nvar ReactPropTypes = require('./ReactPropTypes');\nvar ReactVersion = require('./ReactVersion');\n\nvar createReactClass = require('./createClass');\nvar onlyChild = require('./onlyChild');\n\nvar createElement = ReactElement.createElement;\nvar createFactory = ReactElement.createFactory;\nvar cloneElement = ReactElement.cloneElement;\n\nif (process.env.NODE_ENV !== 'production') {\n var lowPriorityWarning = require('./lowPriorityWarning');\n var canDefineProperty = require('./canDefineProperty');\n var ReactElementValidator = require('./ReactElementValidator');\n var didWarnPropTypesDeprecated = false;\n createElement = ReactElementValidator.createElement;\n createFactory = ReactElementValidator.createFactory;\n cloneElement = ReactElementValidator.cloneElement;\n}\n\nvar __spread = _assign;\nvar createMixin = function (mixin) {\n return mixin;\n};\n\nif (process.env.NODE_ENV !== 'production') {\n var warnedForSpread = false;\n var warnedForCreateMixin = false;\n __spread = function () {\n lowPriorityWarning(warnedForSpread, 'React.__spread is deprecated and should not be used. Use ' + 'Object.assign directly or another helper function with similar ' + 'semantics. You may be seeing this warning due to your compiler. ' + 'See https://fb.me/react-spread-deprecation for more details.');\n warnedForSpread = true;\n return _assign.apply(null, arguments);\n };\n\n createMixin = function (mixin) {\n lowPriorityWarning(warnedForCreateMixin, 'React.createMixin is deprecated and should not be used. ' + 'In React v16.0, it will be removed. ' + 'You can use this mixin directly instead. ' + 'See https://fb.me/createmixin-was-never-implemented for more info.');\n warnedForCreateMixin = true;\n return mixin;\n };\n}\n\nvar React = {\n // Modern\n\n Children: {\n map: ReactChildren.map,\n forEach: ReactChildren.forEach,\n count: ReactChildren.count,\n toArray: ReactChildren.toArray,\n only: onlyChild\n },\n\n Component: ReactBaseClasses.Component,\n PureComponent: ReactBaseClasses.PureComponent,\n\n createElement: createElement,\n cloneElement: cloneElement,\n isValidElement: ReactElement.isValidElement,\n\n // Classic\n\n PropTypes: ReactPropTypes,\n createClass: createReactClass,\n createFactory: createFactory,\n createMixin: createMixin,\n\n // This looks DOM specific but these are actually isomorphic helpers\n // since they are just generating DOM strings.\n DOM: ReactDOMFactories,\n\n version: ReactVersion,\n\n // Deprecated hook for JSX spread, don't use this for anything.\n __spread: __spread\n};\n\nif (process.env.NODE_ENV !== 'production') {\n var warnedForCreateClass = false;\n if (canDefineProperty) {\n Object.defineProperty(React, 'PropTypes', {\n get: function () {\n lowPriorityWarning(didWarnPropTypesDeprecated, 'Accessing PropTypes via the main React package is deprecated,' + ' and will be removed in React v16.0.' + ' Use the latest available v15.* prop-types package from npm instead.' + ' For info on usage, compatibility, migration and more, see ' + 'https://fb.me/prop-types-docs');\n didWarnPropTypesDeprecated = true;\n return ReactPropTypes;\n }\n });\n\n Object.defineProperty(React, 'createClass', {\n get: function () {\n lowPriorityWarning(warnedForCreateClass, 'Accessing createClass via the main React package is deprecated,' + ' and will be removed in React v16.0.' + \" Use a plain JavaScript class instead. If you're not yet \" + 'ready to migrate, create-react-class v15.* is available ' + 'on npm as a temporary, drop-in replacement. ' + 'For more info see https://fb.me/react-create-class');\n warnedForCreateClass = true;\n return createReactClass;\n }\n });\n }\n\n // React.DOM factories are deprecated. Wrap these methods so that\n // invocations of the React.DOM namespace and alert users to switch\n // to the `react-dom-factories` package.\n React.DOM = {};\n var warnedForFactories = false;\n Object.keys(ReactDOMFactories).forEach(function (factory) {\n React.DOM[factory] = function () {\n if (!warnedForFactories) {\n lowPriorityWarning(false, 'Accessing factories like React.DOM.%s has been deprecated ' + 'and will be removed in v16.0+. Use the ' + 'react-dom-factories package instead. ' + ' Version 1.0 provides a drop-in replacement.' + ' For more info, see https://fb.me/react-dom-factories', factory);\n warnedForFactories = true;\n }\n return ReactDOMFactories[factory].apply(ReactDOMFactories, arguments);\n };\n });\n}\n\nmodule.exports = React;","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n * \n */\n\n'use strict';\n\nvar _prodInvariant = require('./reactProdInvariant');\n\nvar invariant = require('fbjs/lib/invariant');\n\n/**\n * Static poolers. Several custom versions for each potential number of\n * arguments. A completely generic pooler is easy to implement, but would\n * require accessing the `arguments` object. In each of these, `this` refers to\n * the Class itself, not an instance. If any others are needed, simply add them\n * here, or in their own files.\n */\nvar oneArgumentPooler = function (copyFieldsFrom) {\n var Klass = this;\n if (Klass.instancePool.length) {\n var instance = Klass.instancePool.pop();\n Klass.call(instance, copyFieldsFrom);\n return instance;\n } else {\n return new Klass(copyFieldsFrom);\n }\n};\n\nvar twoArgumentPooler = function (a1, a2) {\n var Klass = this;\n if (Klass.instancePool.length) {\n var instance = Klass.instancePool.pop();\n Klass.call(instance, a1, a2);\n return instance;\n } else {\n return new Klass(a1, a2);\n }\n};\n\nvar threeArgumentPooler = function (a1, a2, a3) {\n var Klass = this;\n if (Klass.instancePool.length) {\n var instance = Klass.instancePool.pop();\n Klass.call(instance, a1, a2, a3);\n return instance;\n } else {\n return new Klass(a1, a2, a3);\n }\n};\n\nvar fourArgumentPooler = function (a1, a2, a3, a4) {\n var Klass = this;\n if (Klass.instancePool.length) {\n var instance = Klass.instancePool.pop();\n Klass.call(instance, a1, a2, a3, a4);\n return instance;\n } else {\n return new Klass(a1, a2, a3, a4);\n }\n};\n\nvar standardReleaser = function (instance) {\n var Klass = this;\n !(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0;\n instance.destructor();\n if (Klass.instancePool.length < Klass.poolSize) {\n Klass.instancePool.push(instance);\n }\n};\n\nvar DEFAULT_POOL_SIZE = 10;\nvar DEFAULT_POOLER = oneArgumentPooler;\n\n/**\n * Augments `CopyConstructor` to be a poolable class, augmenting only the class\n * itself (statically) not adding any prototypical fields. Any CopyConstructor\n * you give this may have a `poolSize` property, and will look for a\n * prototypical `destructor` on instances.\n *\n * @param {Function} CopyConstructor Constructor that can be used to reset.\n * @param {Function} pooler Customizable pooler.\n */\nvar addPoolingTo = function (CopyConstructor, pooler) {\n // Casting as any so that flow ignores the actual implementation and trusts\n // it to match the type we declared\n var NewKlass = CopyConstructor;\n NewKlass.instancePool = [];\n NewKlass.getPooled = pooler || DEFAULT_POOLER;\n if (!NewKlass.poolSize) {\n NewKlass.poolSize = DEFAULT_POOL_SIZE;\n }\n NewKlass.release = standardReleaser;\n return NewKlass;\n};\n\nvar PooledClass = {\n addPoolingTo: addPoolingTo,\n oneArgumentPooler: oneArgumentPooler,\n twoArgumentPooler: twoArgumentPooler,\n threeArgumentPooler: threeArgumentPooler,\n fourArgumentPooler: fourArgumentPooler\n};\n\nmodule.exports = PooledClass;","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\n'use strict';\n\nvar ReactRef = require('./ReactRef');\nvar ReactInstrumentation = require('./ReactInstrumentation');\n\nvar warning = require('fbjs/lib/warning');\n\n/**\n * Helper to call ReactRef.attachRefs with this composite component, split out\n * to avoid allocations in the transaction mount-ready queue.\n */\nfunction attachRefs() {\n ReactRef.attachRefs(this, this._currentElement);\n}\n\nvar ReactReconciler = {\n /**\n * Initializes the component, renders markup, and registers event listeners.\n *\n * @param {ReactComponent} internalInstance\n * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction\n * @param {?object} the containing host component instance\n * @param {?object} info about the host container\n * @return {?string} Rendered markup to be inserted into the DOM.\n * @final\n * @internal\n */\n mountComponent: function (internalInstance, transaction, hostParent, hostContainerInfo, context, parentDebugID) // 0 in production and for roots\n {\n if (process.env.NODE_ENV !== 'production') {\n if (internalInstance._debugID !== 0) {\n ReactInstrumentation.debugTool.onBeforeMountComponent(internalInstance._debugID, internalInstance._currentElement, parentDebugID);\n }\n }\n var markup = internalInstance.mountComponent(transaction, hostParent, hostContainerInfo, context, parentDebugID);\n if (internalInstance._currentElement && internalInstance._currentElement.ref != null) {\n transaction.getReactMountReady().enqueue(attachRefs, internalInstance);\n }\n if (process.env.NODE_ENV !== 'production') {\n if (internalInstance._debugID !== 0) {\n ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID);\n }\n }\n return markup;\n },\n\n /**\n * Returns a value that can be passed to\n * ReactComponentEnvironment.replaceNodeWithMarkup.\n */\n getHostNode: function (internalInstance) {\n return internalInstance.getHostNode();\n },\n\n /**\n * Releases any resources allocated by `mountComponent`.\n *\n * @final\n * @internal\n */\n unmountComponent: function (internalInstance, safely) {\n if (process.env.NODE_ENV !== 'production') {\n if (internalInstance._debugID !== 0) {\n ReactInstrumentation.debugTool.onBeforeUnmountComponent(internalInstance._debugID);\n }\n }\n ReactRef.detachRefs(internalInstance, internalInstance._currentElement);\n internalInstance.unmountComponent(safely);\n if (process.env.NODE_ENV !== 'production') {\n if (internalInstance._debugID !== 0) {\n ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID);\n }\n }\n },\n\n /**\n * Update a component using a new element.\n *\n * @param {ReactComponent} internalInstance\n * @param {ReactElement} nextElement\n * @param {ReactReconcileTransaction} transaction\n * @param {object} context\n * @internal\n */\n receiveComponent: function (internalInstance, nextElement, transaction, context) {\n var prevElement = internalInstance._currentElement;\n\n if (nextElement === prevElement && context === internalInstance._context) {\n // Since elements are immutable after the owner is rendered,\n // we can do a cheap identity compare here to determine if this is a\n // superfluous reconcile. It's possible for state to be mutable but such\n // change should trigger an update of the owner which would recreate\n // the element. We explicitly check for the existence of an owner since\n // it's possible for an element created outside a composite to be\n // deeply mutated and reused.\n\n // TODO: Bailing out early is just a perf optimization right?\n // TODO: Removing the return statement should affect correctness?\n return;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (internalInstance._debugID !== 0) {\n ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement);\n }\n }\n\n var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement);\n\n if (refsChanged) {\n ReactRef.detachRefs(internalInstance, prevElement);\n }\n\n internalInstance.receiveComponent(nextElement, transaction, context);\n\n if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) {\n transaction.getReactMountReady().enqueue(attachRefs, internalInstance);\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (internalInstance._debugID !== 0) {\n ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);\n }\n }\n },\n\n /**\n * Flush any dirty changes in a component.\n *\n * @param {ReactComponent} internalInstance\n * @param {ReactReconcileTransaction} transaction\n * @internal\n */\n performUpdateIfNecessary: function (internalInstance, transaction, updateBatchNumber) {\n if (internalInstance._updateBatchNumber !== updateBatchNumber) {\n // The component's enqueued batch number should always be the current\n // batch or the following one.\n process.env.NODE_ENV !== 'production' ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0;\n return;\n }\n if (process.env.NODE_ENV !== 'production') {\n if (internalInstance._debugID !== 0) {\n ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement);\n }\n }\n internalInstance.performUpdateIfNecessary(transaction);\n if (process.env.NODE_ENV !== 'production') {\n if (internalInstance._debugID !== 0) {\n ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);\n }\n }\n }\n};\n\nmodule.exports = ReactReconciler;","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","/*\nCopyright 2016, 2017 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\"use strict\";\n\n/**\n * @module models/event-timeline\n */\n\nvar _freeze = require(\"babel-runtime/core-js/object/freeze\");\n\nvar _freeze2 = _interopRequireDefault(_freeze);\n\nvar _getIterator2 = require(\"babel-runtime/core-js/get-iterator\");\n\nvar _getIterator3 = _interopRequireDefault(_getIterator2);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar RoomState = require(\"./room-state\");\n\n/**\n * Construct a new EventTimeline\n *\n * An EventTimeline represents a contiguous sequence of events in a room.\n *\n *
As well as keeping track of the events themselves, it stores the state of\n * the room at the beginning and end of the timeline, and pagination tokens for\n * going backwards and forwards in the timeline.\n *\n *
In order that clients can meaningfully maintain an index into a timeline,\n * the EventTimeline object tracks a 'baseIndex'. This starts at zero, but is\n * incremented when events are prepended to the timeline. The index of an event\n * relative to baseIndex therefore remains constant.\n *\n *
Once a timeline joins up with its neighbour, they are linked together into a\n * doubly-linked list.\n *\n * @param {EventTimelineSet} eventTimelineSet the set of timelines this is part of\n * @constructor\n */\nfunction EventTimeline(eventTimelineSet) {\n this._eventTimelineSet = eventTimelineSet;\n this._roomId = eventTimelineSet.room ? eventTimelineSet.room.roomId : null;\n this._events = [];\n this._baseIndex = 0;\n this._startState = new RoomState(this._roomId);\n this._startState.paginationToken = null;\n this._endState = new RoomState(this._roomId);\n this._endState.paginationToken = null;\n\n this._prevTimeline = null;\n this._nextTimeline = null;\n\n // this is used by client.js\n this._paginationRequests = { 'b': null, 'f': null };\n\n this._name = this._roomId + \":\" + new Date().toISOString();\n}\n\n/**\n * Symbolic constant for methods which take a 'direction' argument:\n * refers to the start of the timeline, or backwards in time.\n */\nEventTimeline.BACKWARDS = \"b\";\n\n/**\n * Symbolic constant for methods which take a 'direction' argument:\n * refers to the end of the timeline, or forwards in time.\n */\nEventTimeline.FORWARDS = \"f\";\n\n/**\n * Initialise the start and end state with the given events\n *\n *
This can only be called before any events are added.\n *\n * @param {MatrixEvent[]} stateEvents list of state events to initialise the\n * state with.\n * @throws {Error} if an attempt is made to call this after addEvent is called.\n */\nEventTimeline.prototype.initialiseState = function (stateEvents) {\n if (this._events.length > 0) {\n throw new Error(\"Cannot initialise state after events are added\");\n }\n\n // We previously deep copied events here and used different copies in\n // the oldState and state events: this decision seems to date back\n // quite a way and was apparently made to fix a bug where modifications\n // made to the start state leaked through to the end state.\n // This really shouldn't be possible though: the events themselves should\n // not change. Duplicating the events uses a lot of extra memory,\n // so we now no longer do it. To assert that they really do never change,\n // freeze them! Note that we can't do this for events in general:\n // although it looks like the only things preventing us are the\n // 'status' flag, forwardLooking (which is only set once when adding to the\n // timeline) and possibly the sender (which seems like it should never be\n // reset but in practice causes a lot of the tests to break).\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = (0, _getIterator3.default)(stateEvents), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var e = _step.value;\n\n (0, _freeze2.default)(e);\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n this._startState.setStateEvents(stateEvents);\n this._endState.setStateEvents(stateEvents);\n};\n\n/**\n * Forks the (live) timeline, taking ownership of the existing directional state of this timeline.\n * All attached listeners will keep receiving state updates from the new live timeline state.\n * The end state of this timeline gets replaced with an independent copy of the current RoomState,\n * and will need a new pagination token if it ever needs to paginate forwards.\n\n * @param {string} direction EventTimeline.BACKWARDS to get the state at the\n * start of the timeline; EventTimeline.FORWARDS to get the state at the end\n * of the timeline.\n *\n * @return {EventTimeline} the new timeline\n */\nEventTimeline.prototype.forkLive = function (direction) {\n var forkState = this.getState(direction);\n var timeline = new EventTimeline(this._eventTimelineSet);\n timeline._startState = forkState.clone();\n // Now clobber the end state of the new live timeline with that from the\n // previous live timeline. It will be identical except that we'll keep\n // using the same RoomMember objects for the 'live' set of members with any\n // listeners still attached\n timeline._endState = forkState;\n // Firstly, we just stole the current timeline's end state, so it needs a new one.\n // Make an immutable copy of the state so back pagination will get the correct sentinels.\n this._endState = forkState.clone();\n return timeline;\n};\n\n/**\n * Creates an independent timeline, inheriting the directional state from this timeline.\n *\n * @param {string} direction EventTimeline.BACKWARDS to get the state at the\n * start of the timeline; EventTimeline.FORWARDS to get the state at the end\n * of the timeline.\n *\n * @return {EventTimeline} the new timeline\n */\nEventTimeline.prototype.fork = function (direction) {\n var forkState = this.getState(direction);\n var timeline = new EventTimeline(this._eventTimelineSet);\n timeline._startState = forkState.clone();\n timeline._endState = forkState.clone();\n return timeline;\n};\n\n/**\n * Get the ID of the room for this timeline\n * @return {string} room ID\n */\nEventTimeline.prototype.getRoomId = function () {\n return this._roomId;\n};\n\n/**\n * Get the filter for this timeline's timelineSet (if any)\n * @return {Filter} filter\n */\nEventTimeline.prototype.getFilter = function () {\n return this._eventTimelineSet.getFilter();\n};\n\n/**\n * Get the timelineSet for this timeline\n * @return {EventTimelineSet} timelineSet\n */\nEventTimeline.prototype.getTimelineSet = function () {\n return this._eventTimelineSet;\n};\n\n/**\n * Get the base index.\n *\n *
This is an index which is incremented when events are prepended to the\n * timeline. An individual event therefore stays at the same index in the array\n * relative to the base index (although note that a given event's index may\n * well be less than the base index, thus giving that event a negative relative\n * index).\n *\n * @return {number}\n */\nEventTimeline.prototype.getBaseIndex = function () {\n return this._baseIndex;\n};\n\n/**\n * Get the list of events in this context\n *\n * @return {MatrixEvent[]} An array of MatrixEvents\n */\nEventTimeline.prototype.getEvents = function () {\n return this._events;\n};\n\n/**\n * Get the room state at the start/end of the timeline\n *\n * @param {string} direction EventTimeline.BACKWARDS to get the state at the\n * start of the timeline; EventTimeline.FORWARDS to get the state at the end\n * of the timeline.\n *\n * @return {RoomState} state at the start/end of the timeline\n */\nEventTimeline.prototype.getState = function (direction) {\n if (direction == EventTimeline.BACKWARDS) {\n return this._startState;\n } else if (direction == EventTimeline.FORWARDS) {\n return this._endState;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n};\n\n/**\n * Get a pagination token\n *\n * @param {string} direction EventTimeline.BACKWARDS to get the pagination\n * token for going backwards in time; EventTimeline.FORWARDS to get the\n * pagination token for going forwards in time.\n *\n * @return {?string} pagination token\n */\nEventTimeline.prototype.getPaginationToken = function (direction) {\n return this.getState(direction).paginationToken;\n};\n\n/**\n * Set a pagination token\n *\n * @param {?string} token pagination token\n *\n * @param {string} direction EventTimeline.BACKWARDS to set the pagination\n * token for going backwards in time; EventTimeline.FORWARDS to set the\n * pagination token for going forwards in time.\n */\nEventTimeline.prototype.setPaginationToken = function (token, direction) {\n this.getState(direction).paginationToken = token;\n};\n\n/**\n * Get the next timeline in the series\n *\n * @param {string} direction EventTimeline.BACKWARDS to get the previous\n * timeline; EventTimeline.FORWARDS to get the next timeline.\n *\n * @return {?EventTimeline} previous or following timeline, if they have been\n * joined up.\n */\nEventTimeline.prototype.getNeighbouringTimeline = function (direction) {\n if (direction == EventTimeline.BACKWARDS) {\n return this._prevTimeline;\n } else if (direction == EventTimeline.FORWARDS) {\n return this._nextTimeline;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n};\n\n/**\n * Set the next timeline in the series\n *\n * @param {EventTimeline} neighbour previous/following timeline\n *\n * @param {string} direction EventTimeline.BACKWARDS to set the previous\n * timeline; EventTimeline.FORWARDS to set the next timeline.\n *\n * @throws {Error} if an attempt is made to set the neighbouring timeline when\n * it is already set.\n */\nEventTimeline.prototype.setNeighbouringTimeline = function (neighbour, direction) {\n if (this.getNeighbouringTimeline(direction)) {\n throw new Error(\"timeline already has a neighbouring timeline - \" + \"cannot reset neighbour (direction: \" + direction + \")\");\n }\n\n if (direction == EventTimeline.BACKWARDS) {\n this._prevTimeline = neighbour;\n } else if (direction == EventTimeline.FORWARDS) {\n this._nextTimeline = neighbour;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n\n // make sure we don't try to paginate this timeline\n this.setPaginationToken(null, direction);\n};\n\n/**\n * Add a new event to the timeline, and update the state\n *\n * @param {MatrixEvent} event new event\n * @param {boolean} atStart true to insert new event at the start\n */\nEventTimeline.prototype.addEvent = function (event, atStart) {\n var stateContext = atStart ? this._startState : this._endState;\n\n // only call setEventMetadata on the unfiltered timelineSets\n var timelineSet = this.getTimelineSet();\n if (timelineSet.room && timelineSet.room.getUnfilteredTimelineSet() === timelineSet) {\n EventTimeline.setEventMetadata(event, stateContext, atStart);\n\n // modify state\n if (event.isState()) {\n stateContext.setStateEvents([event]);\n // it is possible that the act of setting the state event means we\n // can set more metadata (specifically sender/target props), so try\n // it again if the prop wasn't previously set. It may also mean that\n // the sender/target is updated (if the event set was a room member event)\n // so we want to use the *updated* member (new avatar/name) instead.\n //\n // However, we do NOT want to do this on member events if we're going\n // back in time, else we'll set the .sender value for BEFORE the given\n // member event, whereas we want to set the .sender value for the ACTUAL\n // member event itself.\n if (!event.sender || event.getType() === \"m.room.member\" && !atStart) {\n EventTimeline.setEventMetadata(event, stateContext, atStart);\n }\n }\n }\n\n var insertIndex = void 0;\n\n if (atStart) {\n insertIndex = 0;\n } else {\n insertIndex = this._events.length;\n }\n\n this._events.splice(insertIndex, 0, event); // insert element\n if (atStart) {\n this._baseIndex++;\n }\n};\n\n/**\n * Static helper method to set sender and target properties\n *\n * @param {MatrixEvent} event the event whose metadata is to be set\n * @param {RoomState} stateContext the room state to be queried\n * @param {bool} toStartOfTimeline if true the event's forwardLooking flag is set false\n */\nEventTimeline.setEventMetadata = function (event, stateContext, toStartOfTimeline) {\n // set sender and target properties\n event.sender = stateContext.getSentinelMember(event.getSender());\n if (event.getType() === \"m.room.member\") {\n event.target = stateContext.getSentinelMember(event.getStateKey());\n }\n if (event.isState()) {\n // room state has no concept of 'old' or 'current', but we want the\n // room state to regress back to previous values if toStartOfTimeline\n // is set, which means inspecting prev_content if it exists. This\n // is done by toggling the forwardLooking flag.\n if (toStartOfTimeline) {\n event.forwardLooking = false;\n }\n }\n};\n\n/**\n * Remove an event from the timeline\n *\n * @param {string} eventId ID of event to be removed\n * @return {?MatrixEvent} removed event, or null if not found\n */\nEventTimeline.prototype.removeEvent = function (eventId) {\n for (var i = this._events.length - 1; i >= 0; i--) {\n var ev = this._events[i];\n if (ev.getId() == eventId) {\n this._events.splice(i, 1);\n if (i < this._baseIndex) {\n this._baseIndex--;\n }\n return ev;\n }\n }\n return null;\n};\n\n/**\n * Return a string to identify this timeline, for debugging\n *\n * @return {string} name for this timeline\n */\nEventTimeline.prototype.toString = function () {\n return this._name;\n};\n\n/**\n * The EventTimeline class\n */\nmodule.exports = EventTimeline;\n//# sourceMappingURL=event-timeline.js.map","var baseIsNative = require('./_baseIsNative'),\n getValue = require('./_getValue');\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nmodule.exports = getNative;\n","/*\nCopyright 2015, 2016 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n'use strict';\n\nvar _matrixJsSdk = require('matrix-js-sdk');\n\nvar _MatrixClientPeg = require('./MatrixClientPeg');\n\nvar _MatrixClientPeg2 = _interopRequireDefault(_MatrixClientPeg);\n\nvar _DMRoomMap = require('./utils/DMRoomMap');\n\nvar _DMRoomMap2 = _interopRequireDefault(_DMRoomMap);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nmodule.exports = {\n avatarUrlForMember: function avatarUrlForMember(member, width, height, resizeMethod) {\n var url = member.getAvatarUrl(_MatrixClientPeg2.default.get().getHomeserverUrl(), Math.floor(width * window.devicePixelRatio), Math.floor(height * window.devicePixelRatio), resizeMethod, false, false);\n if (!url) {\n // member can be null here currently since on invites, the JS SDK\n // does not have enough info to build a RoomMember object for\n // the inviter.\n url = this.defaultAvatarUrlForString(member ? member.userId : '');\n }\n return url;\n },\n\n avatarUrlForUser: function avatarUrlForUser(user, width, height, resizeMethod) {\n var url = _matrixJsSdk.ContentRepo.getHttpUriForMxc(_MatrixClientPeg2.default.get().getHomeserverUrl(), user.avatarUrl, Math.floor(width * window.devicePixelRatio), Math.floor(height * window.devicePixelRatio), resizeMethod);\n if (!url || url.length === 0) {\n return null;\n }\n return url;\n },\n\n defaultAvatarUrlForString: function defaultAvatarUrlForString(s) {\n var images = ['03b381', '368bd6', 'ac3ba8'];\n var total = 0;\n for (var i = 0; i < s.length; ++i) {\n total += s.charCodeAt(i);\n }\n return require('../res/img/' + images[total % images.length] + '.png');\n },\n\n /**\n * returns the first (non-sigil) character of 'name',\n * converted to uppercase\n * @param {string} name\n * @return {string} the first letter\n */\n getInitialLetter: function getInitialLetter(name) {\n if (name.length < 1) {\n return undefined;\n }\n\n var idx = 0;\n var initial = name[0];\n if ((initial === '@' || initial === '#' || initial === '+') && name[1]) {\n idx++;\n }\n\n // string.codePointAt(0) would do this, but that isn't supported by\n // some browsers (notably PhantomJS).\n var chars = 1;\n var first = name.charCodeAt(idx);\n\n // check if it’s the start of a surrogate pair\n if (first >= 0xD800 && first <= 0xDBFF && name[idx + 1]) {\n var second = name.charCodeAt(idx + 1);\n if (second >= 0xDC00 && second <= 0xDFFF) {\n chars++;\n }\n }\n\n var firstChar = name.substring(idx, idx + chars);\n return firstChar.toUpperCase();\n },\n avatarUrlForRoom: function avatarUrlForRoom(room, width, height, resizeMethod) {\n var explicitRoomAvatar = room.getAvatarUrl(_MatrixClientPeg2.default.get().getHomeserverUrl(), width, height, resizeMethod, false);\n if (explicitRoomAvatar) {\n return explicitRoomAvatar;\n }\n\n var otherMember = null;\n var otherUserId = _DMRoomMap2.default.shared().getUserIdForRoomId(room.roomId);\n if (otherUserId) {\n otherMember = room.getMember(otherUserId);\n } else {\n // if the room is not marked as a 1:1, but only has max 2 members\n // then still try to show any avatar (pref. other member)\n otherMember = room.getAvatarFallbackMember();\n }\n if (otherMember) {\n return otherMember.getAvatarUrl(_MatrixClientPeg2.default.get().getHomeserverUrl(), width, height, resizeMethod, false);\n }\n return null;\n }\n};\n//# sourceMappingURL=Avatar.js.map","'use strict';\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _bluebird = require('bluebird');\n\nvar _bluebird2 = _interopRequireDefault(_bluebird);\n\nvar _SettingsStore = require('./settings/SettingsStore');\n\nvar _SettingsStore2 = _interopRequireDefault(_SettingsStore);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\nCopyright 2016 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar request = require('browser-request');\n\nvar SdkConfig = require('./SdkConfig');\nvar MatrixClientPeg = require('./MatrixClientPeg');\n\n// The version of the integration manager API we're intending to work with\nvar imApiVersion = \"1.1\";\n\nvar ScalarAuthClient = function () {\n function ScalarAuthClient() {\n (0, _classCallCheck3.default)(this, ScalarAuthClient);\n\n this.scalarToken = null;\n }\n\n (0, _createClass3.default)(ScalarAuthClient, [{\n key: 'connect',\n value: function connect() {\n var _this = this;\n\n return this.getScalarToken().then(function (tok) {\n _this.scalarToken = tok;\n });\n }\n }, {\n key: 'hasCredentials',\n value: function hasCredentials() {\n return this.scalarToken != null; // undef or null\n }\n\n // Returns a scalar_token string\n\n }, {\n key: 'getScalarToken',\n value: function getScalarToken() {\n var _this2 = this;\n\n var token = window.localStorage.getItem(\"mx_scalar_token\");\n\n if (!token) {\n return this.registerForToken();\n } else {\n return this.validateToken(token).then(function (userId) {\n var me = MatrixClientPeg.get().getUserId();\n if (userId !== me) {\n throw new Error(\"Scalar token is owned by someone else: \" + me);\n }\n return token;\n }).catch(function (err) {\n console.error(err);\n\n // Something went wrong - try to get a new token.\n console.warn(\"Registering for new scalar token\");\n return _this2.registerForToken();\n });\n }\n }\n }, {\n key: 'validateToken',\n value: function validateToken(token) {\n var url = SdkConfig.get().integrations_rest_url + \"/account\";\n\n return new _bluebird2.default(function (resolve, reject) {\n request({\n method: \"GET\",\n uri: url,\n qs: { scalar_token: token, v: imApiVersion },\n json: true\n }, function (err, response, body) {\n if (err) {\n reject(err);\n } else if (response.statusCode / 100 !== 2) {\n reject({ statusCode: response.statusCode });\n } else if (!body || !body.user_id) {\n reject(new Error(\"Missing user_id in response\"));\n } else {\n resolve(body.user_id);\n }\n });\n });\n }\n }, {\n key: 'registerForToken',\n value: function registerForToken() {\n var _this3 = this;\n\n // Get openid bearer token from the HS as the first part of our dance\n return MatrixClientPeg.get().getOpenIdToken().then(function (token_object) {\n // Now we can send that to scalar and exchange it for a scalar token\n return _this3.exchangeForScalarToken(token_object);\n }).then(function (token_object) {\n window.localStorage.setItem(\"mx_scalar_token\", token_object);\n return token_object;\n });\n }\n }, {\n key: 'exchangeForScalarToken',\n value: function exchangeForScalarToken(openid_token_object) {\n var scalar_rest_url = SdkConfig.get().integrations_rest_url;\n\n return new _bluebird2.default(function (resolve, reject) {\n request({\n method: 'POST',\n uri: scalar_rest_url + '/register',\n qs: { v: imApiVersion },\n body: openid_token_object,\n json: true\n }, function (err, response, body) {\n if (err) {\n reject(err);\n } else if (response.statusCode / 100 !== 2) {\n reject({ statusCode: response.statusCode });\n } else if (!body || !body.scalar_token) {\n reject(new Error(\"Missing scalar_token in response\"));\n } else {\n resolve(body.scalar_token);\n }\n });\n });\n }\n }, {\n key: 'getScalarPageTitle',\n value: function getScalarPageTitle(url) {\n var scalarPageLookupUrl = SdkConfig.get().integrations_rest_url + '/widgets/title_lookup';\n scalarPageLookupUrl = this.getStarterLink(scalarPageLookupUrl);\n scalarPageLookupUrl += '&curl=' + encodeURIComponent(url);\n\n return new _bluebird2.default(function (resolve, reject) {\n request({\n method: 'GET',\n uri: scalarPageLookupUrl,\n json: true\n }, function (err, response, body) {\n if (err) {\n reject(err);\n } else if (response.statusCode / 100 !== 2) {\n reject({ statusCode: response.statusCode });\n } else if (!body) {\n reject(new Error(\"Missing page title in response\"));\n } else {\n var title = \"\";\n if (body.page_title_cache_item && body.page_title_cache_item.cached_title) {\n title = body.page_title_cache_item.cached_title;\n }\n resolve(title);\n }\n });\n });\n }\n\n /**\n * Mark all assets associated with the specified widget as \"disabled\" in the\n * integration manager database.\n * This can be useful to temporarily prevent purchased assets from being displayed.\n * @param {string} widgetType [description]\n * @param {string} widgetId [description]\n * @return {Promise} Resolves on completion\n */\n\n }, {\n key: 'disableWidgetAssets',\n value: function disableWidgetAssets(widgetType, widgetId) {\n var url = SdkConfig.get().integrations_rest_url + '/widgets/set_assets_state';\n url = this.getStarterLink(url);\n return new _bluebird2.default(function (resolve, reject) {\n request({\n method: 'GET',\n uri: url,\n json: true,\n qs: {\n 'widget_type': widgetType,\n 'widget_id': widgetId,\n 'state': 'disable'\n }\n }, function (err, response, body) {\n if (err) {\n reject(err);\n } else if (response.statusCode / 100 !== 2) {\n reject({ statusCode: response.statusCode });\n } else if (!body) {\n reject(new Error(\"Failed to set widget assets state\"));\n } else {\n resolve();\n }\n });\n });\n }\n }, {\n key: 'getScalarInterfaceUrlForRoom',\n value: function getScalarInterfaceUrlForRoom(room, screen, id) {\n var roomId = room.roomId;\n var roomName = room.name;\n var url = SdkConfig.get().integrations_ui_url;\n url += \"?scalar_token=\" + encodeURIComponent(this.scalarToken);\n url += \"&room_id=\" + encodeURIComponent(roomId);\n url += \"&room_name=\" + encodeURIComponent(roomName);\n url += \"&theme=\" + encodeURIComponent(_SettingsStore2.default.getValue(\"theme\"));\n if (id) {\n url += '&integ_id=' + encodeURIComponent(id);\n }\n if (screen) {\n url += '&screen=' + encodeURIComponent(screen);\n }\n return url;\n }\n }, {\n key: 'getStarterLink',\n value: function getStarterLink(starterLinkUrl) {\n return starterLinkUrl + \"?scalar_token=\" + encodeURIComponent(this.scalarToken);\n }\n }]);\n return ScalarAuthClient;\n}();\n\nmodule.exports = ScalarAuthClient;\n//# sourceMappingURL=ScalarAuthClient.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\nCopyright 2015 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nvar DEBUG = 0;\n\n// utility to turn #rrggbb or rgb(r,g,b) into [red,green,blue]\nfunction colorToRgb(color) {\n if (!color) {\n return [0, 0, 0];\n }\n\n if (color[0] === '#') {\n color = color.slice(1);\n if (color.length === 3) {\n color = color[0] + color[0] + color[1] + color[1] + color[2] + color[2];\n }\n var val = parseInt(color, 16);\n var r = val >> 16 & 255;\n var g = val >> 8 & 255;\n var b = val & 255;\n return [r, g, b];\n } else {\n var match = color.match(/rgb\\((.*?),(.*?),(.*?)\\)/);\n if (match) {\n return [parseInt(match[1]), parseInt(match[2]), parseInt(match[3])];\n }\n }\n return [0, 0, 0];\n}\n\n// utility to turn [red,green,blue] into #rrggbb\nfunction rgbToColor(rgb) {\n var val = rgb[0] << 16 | rgb[1] << 8 | rgb[2];\n return '#' + (0x1000000 + val).toString(16).slice(1);\n}\n\nvar Tinter = function () {\n function Tinter() {\n (0, _classCallCheck3.default)(this, Tinter);\n\n // The default colour keys to be replaced as referred to in CSS\n // (should be overridden by .mx_theme_accentColor and .mx_theme_secondaryAccentColor)\n this.keyRgb = [\"rgb(118, 207, 166)\", // Vector Green\n \"rgb(234, 245, 240)\", // Vector Light Green\n \"rgb(211, 239, 225)\"];\n\n // Some algebra workings for calculating the tint % of Vector Green & Light Green\n // x * 118 + (1 - x) * 255 = 234\n // x * 118 + 255 - 255 * x = 234\n // x * 118 - x * 255 = 234 - 255\n // (255 - 118) x = 255 - 234\n // x = (255 - 234) / (255 - 118) = 0.16\n\n // The colour keys to be replaced as referred to in SVGs\n this.keyHex = [\"#76CFA6\", // Vector Green\n \"#EAF5F0\", // Vector Light Green\n \"#D3EFE1\", // roomsublist-label-bg-color (20% Green overlaid on Light Green)\n \"#FFFFFF\", // white highlights of the SVGs (for switching to dark theme)\n \"#000000\"];\n\n // track the replacement colours actually being used\n // defaults to our keys.\n this.colors = [this.keyHex[0], this.keyHex[1], this.keyHex[2], this.keyHex[3], this.keyHex[4]];\n\n // track the most current tint request inputs (which may differ from the\n // end result stored in this.colors\n this.currentTint = [undefined, undefined, undefined, undefined, undefined];\n\n this.cssFixups = [\n // { theme: {\n // style: a style object that should be fixed up taken from a stylesheet\n // attr: name of the attribute to be clobbered, e.g. 'color'\n // index: ordinal of primary, secondary or tertiary\n // },\n // }\n ];\n\n // CSS attributes to be fixed up\n this.cssAttrs = [\"color\", \"backgroundColor\", \"borderColor\", \"borderTopColor\", \"borderBottomColor\", \"borderLeftColor\"];\n\n this.svgAttrs = [\"fill\", \"stroke\"];\n\n // List of functions to call when the tint changes.\n this.tintables = [];\n\n // the currently loaded theme (if any)\n this.theme = undefined;\n\n // whether to force a tint (e.g. after changing theme)\n this.forceTint = false;\n }\n\n /**\n * Register a callback to fire when the tint changes.\n * This is used to rewrite the tintable SVGs with the new tint.\n *\n * It's not possible to unregister a tintable callback. So this can only be\n * used to register a static callback. If a set of tintables will change\n * over time then the best bet is to register a single callback for the\n * entire set.\n *\n * @param {Function} tintable Function to call when the tint changes.\n */\n\n\n (0, _createClass3.default)(Tinter, [{\n key: 'registerTintable',\n value: function registerTintable(tintable) {\n this.tintables.push(tintable);\n }\n }, {\n key: 'getKeyRgb',\n value: function getKeyRgb() {\n return this.keyRgb;\n }\n }, {\n key: 'tint',\n value: function tint(primaryColor, secondaryColor, tertiaryColor) {\n return;\n // eslint-disable-next-line no-unreachable\n this.currentTint[0] = primaryColor;\n this.currentTint[1] = secondaryColor;\n this.currentTint[2] = tertiaryColor;\n\n this.calcCssFixups();\n\n if (DEBUG) {\n console.log(\"Tinter.tint(\" + primaryColor + \", \" + secondaryColor + \", \" + tertiaryColor + \")\");\n }\n\n if (!primaryColor) {\n primaryColor = this.keyRgb[0];\n secondaryColor = this.keyRgb[1];\n tertiaryColor = this.keyRgb[2];\n }\n\n if (!secondaryColor) {\n var x = 0.16; // average weighting factor calculated from vector green & light green\n var rgb = colorToRgb(primaryColor);\n rgb[0] = x * rgb[0] + (1 - x) * 255;\n rgb[1] = x * rgb[1] + (1 - x) * 255;\n rgb[2] = x * rgb[2] + (1 - x) * 255;\n secondaryColor = rgbToColor(rgb);\n }\n\n if (!tertiaryColor) {\n var _x = 0.19;\n var rgb1 = colorToRgb(primaryColor);\n var rgb2 = colorToRgb(secondaryColor);\n rgb1[0] = _x * rgb1[0] + (1 - _x) * rgb2[0];\n rgb1[1] = _x * rgb1[1] + (1 - _x) * rgb2[1];\n rgb1[2] = _x * rgb1[2] + (1 - _x) * rgb2[2];\n tertiaryColor = rgbToColor(rgb1);\n }\n\n if (this.forceTint == false && this.colors[0] === primaryColor && this.colors[1] === secondaryColor && this.colors[2] === tertiaryColor) {\n return;\n }\n\n this.forceTint = false;\n\n this.colors[0] = primaryColor;\n this.colors[1] = secondaryColor;\n this.colors[2] = tertiaryColor;\n\n if (DEBUG) {\n console.log(\"Tinter.tint final: (\" + primaryColor + \", \" + secondaryColor + \", \" + tertiaryColor + \")\");\n }\n\n // go through manually fixing up the stylesheets.\n this.applyCssFixups();\n\n // tell all the SVGs to go fix themselves up\n // we don't do this as a dispatch otherwise it will visually lag\n this.tintables.forEach(function (tintable) {\n tintable();\n });\n }\n }, {\n key: 'tintSvgWhite',\n value: function tintSvgWhite(whiteColor) {\n this.currentTint[3] = whiteColor;\n\n if (!whiteColor) {\n whiteColor = this.colors[3];\n }\n if (this.colors[3] === whiteColor) {\n return;\n }\n this.colors[3] = whiteColor;\n this.tintables.forEach(function (tintable) {\n tintable();\n });\n }\n }, {\n key: 'tintSvgBlack',\n value: function tintSvgBlack(blackColor) {\n this.currentTint[4] = blackColor;\n\n if (!blackColor) {\n blackColor = this.colors[4];\n }\n if (this.colors[4] === blackColor) {\n return;\n }\n this.colors[4] = blackColor;\n this.tintables.forEach(function (tintable) {\n tintable();\n });\n }\n }, {\n key: 'setTheme',\n value: function setTheme(theme) {\n this.theme = theme;\n\n // update keyRgb from the current theme CSS itself, if it defines it\n if (document.getElementById('mx_theme_accentColor')) {\n this.keyRgb[0] = window.getComputedStyle(document.getElementById('mx_theme_accentColor')).color;\n }\n if (document.getElementById('mx_theme_secondaryAccentColor')) {\n this.keyRgb[1] = window.getComputedStyle(document.getElementById('mx_theme_secondaryAccentColor')).color;\n }\n if (document.getElementById('mx_theme_tertiaryAccentColor')) {\n this.keyRgb[2] = window.getComputedStyle(document.getElementById('mx_theme_tertiaryAccentColor')).color;\n }\n\n this.calcCssFixups();\n this.forceTint = true;\n\n this.tint(this.currentTint[0], this.currentTint[1], this.currentTint[2]);\n\n if (theme === 'dark') {\n // abuse the tinter to change all the SVG's #fff to #2d2d2d\n // XXX: obviously this shouldn't be hardcoded here.\n this.tintSvgWhite('#2d2d2d');\n this.tintSvgBlack('#dddddd');\n } else {\n this.tintSvgWhite('#ffffff');\n this.tintSvgBlack('#000000');\n }\n }\n }, {\n key: 'calcCssFixups',\n value: function calcCssFixups() {\n // cache our fixups\n if (this.cssFixups[this.theme]) return;\n\n if (DEBUG) {\n console.debug(\"calcCssFixups start for \" + this.theme + \" (checking \" + document.styleSheets.length + \" stylesheets)\");\n }\n\n this.cssFixups[this.theme] = [];\n\n for (var i = 0; i < document.styleSheets.length; i++) {\n var ss = document.styleSheets[i];\n try {\n if (!ss) continue; // well done safari >:(\n // Chromium apparently sometimes returns null here; unsure why.\n // see $14534907369972FRXBx:matrix.org in HQ\n // ...ah, it's because there's a third party extension like\n // privacybadger inserting its own stylesheet in there with a\n // resource:// URI or something which results in a XSS error.\n // See also #vector:matrix.org/$145357669685386ebCfr:matrix.org\n // ...except some browsers apparently return stylesheets without\n // hrefs, which we have no choice but ignore right now\n\n // XXX seriously? we are hardcoding the name of vector's CSS file in\n // here?\n //\n // Why do we need to limit it to vector's CSS file anyway - if there\n // are other CSS files affecting the doc don't we want to apply the\n // same transformations to them?\n //\n // Iterating through the CSS looking for matches to hack on feels\n // pretty horrible anyway. And what if the application skin doesn't use\n // Vector Green as its primary color?\n // --richvdh\n\n // Yes, tinting assumes that you are using the Riot skin for now.\n // The right solution will be to move the CSS over to react-sdk.\n // And yes, the default assets for the base skin might as well use\n // Vector Green as any other colour.\n // --matthew\n\n // stylesheets we don't have permission to access (eg. ones from extensions) have a null\n // href and will throw exceptions if we try to access their rules.\n if (!ss.href || !ss.href.match(new RegExp('/theme-' + this.theme + '.css$'))) continue;\n if (ss.disabled) continue;\n if (!ss.cssRules) continue;\n\n if (DEBUG) console.debug(\"calcCssFixups checking \" + ss.cssRules.length + \" rules for \" + ss.href);\n\n for (var j = 0; j < ss.cssRules.length; j++) {\n var rule = ss.cssRules[j];\n if (!rule.style) continue;\n if (rule.selectorText && rule.selectorText.match(/#mx_theme/)) continue;\n for (var k = 0; k < this.cssAttrs.length; k++) {\n var attr = this.cssAttrs[k];\n for (var l = 0; l < this.keyRgb.length; l++) {\n if (rule.style[attr] === this.keyRgb[l]) {\n this.cssFixups[this.theme].push({\n style: rule.style,\n attr: attr,\n index: l\n });\n }\n }\n }\n }\n } catch (e) {\n // Catch any random exceptions that happen here: all sorts of things can go\n // wrong with this (nulls, SecurityErrors) and mostly it's for other\n // stylesheets that we don't want to proces anyway. We should not propagate an\n // exception out since this will cause the app to fail to start.\n console.log(\"Failed to calculate CSS fixups for a stylesheet: \" + ss.href, e);\n }\n }\n if (DEBUG) {\n console.log(\"calcCssFixups end (\" + this.cssFixups[this.theme].length + \" fixups)\");\n }\n }\n }, {\n key: 'applyCssFixups',\n value: function applyCssFixups() {\n if (DEBUG) {\n console.log(\"applyCssFixups start (\" + this.cssFixups[this.theme].length + \" fixups)\");\n }\n for (var i = 0; i < this.cssFixups[this.theme].length; i++) {\n var cssFixup = this.cssFixups[this.theme][i];\n try {\n cssFixup.style[cssFixup.attr] = this.colors[cssFixup.index];\n } catch (e) {\n // Firefox Quantum explodes if you manually edit the CSS in the\n // inspector and then try to do a tint, as apparently all the\n // fixups are then stale.\n console.error(\"Failed to apply cssFixup in Tinter! \", e.name);\n }\n }\n if (DEBUG) console.log(\"applyCssFixups end\");\n }\n\n // XXX: we could just move this all into TintableSvg, but as it's so similar\n // to the CSS fixup stuff in Tinter (just that the fixups are stored in TintableSvg)\n // keeping it here for now.\n\n }, {\n key: 'calcSvgFixups',\n value: function calcSvgFixups(svgs) {\n // go through manually fixing up SVG colours.\n // we could do this by stylesheets, but keeping the stylesheets\n // updated would be a PITA, so just brute-force search for the\n // key colour; cache the element and apply.\n\n if (DEBUG) console.log(\"calcSvgFixups start for \" + svgs);\n var fixups = [];\n for (var i = 0; i < svgs.length; i++) {\n var svgDoc = void 0;\n try {\n svgDoc = svgs[i].contentDocument;\n } catch (e) {\n var msg = 'Failed to get svg.contentDocument of ' + svgs[i].toString();\n if (e.message) {\n msg += e.message;\n }\n if (e.stack) {\n msg += ' | stack: ' + e.stack;\n }\n console.error(msg);\n }\n if (!svgDoc) continue;\n var tags = svgDoc.getElementsByTagName(\"*\");\n for (var j = 0; j < tags.length; j++) {\n var tag = tags[j];\n for (var k = 0; k < this.svgAttrs.length; k++) {\n var attr = this.svgAttrs[k];\n for (var l = 0; l < this.keyHex.length; l++) {\n if (tag.getAttribute(attr) && tag.getAttribute(attr).toUpperCase() === this.keyHex[l]) {\n fixups.push({\n node: tag,\n attr: attr,\n index: l\n });\n }\n }\n }\n }\n }\n if (DEBUG) console.log(\"calcSvgFixups end\");\n\n return fixups;\n }\n }, {\n key: 'applySvgFixups',\n value: function applySvgFixups(fixups) {\n if (DEBUG) console.log(\"applySvgFixups start for \" + fixups);\n for (var i = 0; i < fixups.length; i++) {\n var svgFixup = fixups[i];\n svgFixup.node.setAttribute(svgFixup.attr, this.colors[svgFixup.index]);\n }\n if (DEBUG) console.log(\"applySvgFixups end\");\n }\n }]);\n return Tinter;\n}();\n\nif (global.singletonTinter === undefined) {\n global.singletonTinter = new Tinter();\n}\nexports.default = global.singletonTinter;\nmodule.exports = exports['default'];\n//# sourceMappingURL=Tinter.js.map","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _getPrototypeOf = require(\"babel-runtime/core-js/object/get-prototype-of\");\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require(\"babel-runtime/helpers/classCallCheck\");\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require(\"babel-runtime/helpers/createClass\");\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require(\"babel-runtime/helpers/possibleConstructorReturn\");\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require(\"babel-runtime/helpers/inherits\");\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _react = require(\"react\");\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _propTypes = require(\"prop-types\");\n\nvar _propTypes2 = _interopRequireDefault(_propTypes);\n\nvar _ToggleSwitch = require(\"./ToggleSwitch\");\n\nvar _ToggleSwitch2 = _interopRequireDefault(_ToggleSwitch);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar LabelledToggleSwitch = function (_React$Component) {\n (0, _inherits3.default)(LabelledToggleSwitch, _React$Component);\n\n function LabelledToggleSwitch() {\n (0, _classCallCheck3.default)(this, LabelledToggleSwitch);\n return (0, _possibleConstructorReturn3.default)(this, (LabelledToggleSwitch.__proto__ || (0, _getPrototypeOf2.default)(LabelledToggleSwitch)).apply(this, arguments));\n }\n\n (0, _createClass3.default)(LabelledToggleSwitch, [{\n key: \"render\",\n value: function render() {\n // This is a minimal version of a SettingsFlag\n\n var firstPart = _react2.default.createElement(\n \"span\",\n { className: \"mx_SettingsFlag_label\" },\n this.props.label\n );\n var secondPart = _react2.default.createElement(_ToggleSwitch2.default, { checked: this.props.value, disabled: this.props.disabled,\n onChange: this.props.onChange });\n\n if (this.props.toggleInFront) {\n var temp = firstPart;\n firstPart = secondPart;\n secondPart = temp;\n }\n\n return _react2.default.createElement(\n \"div\",\n { className: \"mx_SettingsFlag\" },\n firstPart,\n secondPart\n );\n }\n }]);\n return LabelledToggleSwitch;\n}(_react2.default.Component); /*\n Copyright 2019 New Vector Ltd\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nLabelledToggleSwitch.propTypes = {\n // The value for the toggle switch\n value: _propTypes2.default.bool.isRequired,\n\n // The function to call when the value changes\n onChange: _propTypes2.default.func.isRequired,\n\n // The translated label for the switch\n label: _propTypes2.default.string.isRequired,\n\n // Whether or not to disable the toggle switch\n disabled: _propTypes2.default.bool,\n\n // True to put the toggle in front of the label\n // Default false.\n toggleInFront: _propTypes2.default.bool\n};\nexports.default = LabelledToggleSwitch;\nmodule.exports = exports[\"default\"];\n//# sourceMappingURL=LabelledToggleSwitch.js.map","module.exports = __webpack_public_path__ + \"img/spinner.0b29ec9.gif\";","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _bluebird = require('bluebird');\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _react = require('react');\n\nvar _react2 = _interopRequireDefault(_react);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar AutocompleteProvider = function () {\n function AutocompleteProvider(commandRegex, forcedCommandRegex) {\n (0, _classCallCheck3.default)(this, AutocompleteProvider);\n\n if (commandRegex) {\n if (!commandRegex.global) {\n throw new Error('commandRegex must have global flag set');\n }\n this.commandRegex = commandRegex;\n }\n if (forcedCommandRegex) {\n if (!forcedCommandRegex.global) {\n throw new Error('forcedCommandRegex must have global flag set');\n }\n this.forcedCommandRegex = forcedCommandRegex;\n }\n }\n\n (0, _createClass3.default)(AutocompleteProvider, [{\n key: 'destroy',\n value: function destroy() {}\n // stub\n\n\n /**\n * Of the matched commands in the query, returns the first that contains or is contained by the selection, or null.\n * @param {string} query The query string\n * @param {SelectionRange} selection Selection to search\n * @param {boolean} force True if the user is forcing completion\n * @return {object} { command, range } where both objects fields are null if no match\n */\n\n }, {\n key: 'getCurrentCommand',\n value: function getCurrentCommand(query, selection) {\n var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\n var commandRegex = this.commandRegex;\n\n if (force && this.shouldForceComplete()) {\n commandRegex = this.forcedCommandRegex || /\\S+/g;\n }\n\n if (commandRegex == null) {\n return null;\n }\n\n commandRegex.lastIndex = 0;\n\n var match = void 0;\n while ((match = commandRegex.exec(query)) != null) {\n var start = match.index;\n var end = start + match[0].length;\n if (selection.start <= end && selection.end >= start) {\n return {\n command: match,\n range: {\n start: start,\n end: end\n }\n };\n }\n }\n return {\n command: null,\n range: {\n start: -1,\n end: -1\n }\n };\n }\n }, {\n key: 'getCompletions',\n value: function () {\n var _ref = (0, _bluebird.method)(function (query, selection) {\n var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n\n return [];\n });\n\n function getCompletions(_x2, _x3, _x4) {\n return _ref.apply(this, arguments);\n }\n\n return getCompletions;\n }()\n }, {\n key: 'getName',\n value: function getName() {\n return 'Default Provider';\n }\n }, {\n key: 'renderCompletions',\n value: function renderCompletions(completions) {\n console.error('stub; should be implemented in subclasses');\n return null;\n }\n\n // Whether we should provide completions even if triggered forcefully, without a sigil.\n\n }, {\n key: 'shouldForceComplete',\n value: function shouldForceComplete() {\n return false;\n }\n }]);\n return AutocompleteProvider;\n}(); /*\n Copyright 2016 Aviral Dasgupta\n Copyright 2017 Vector Creations Ltd\n Copyright 2017, 2018 New Vector Ltd\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nexports.default = AutocompleteProvider;\nmodule.exports = exports['default'];\n//# sourceMappingURL=AutocompleteProvider.js.map","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.PillCompletion = exports.TextualCompletion = undefined;\n\nvar _extends2 = require('babel-runtime/helpers/extends');\n\nvar _extends3 = _interopRequireDefault(_extends2);\n\nvar _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');\n\nvar _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);\n\nvar _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');\n\nvar _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);\n\nvar _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');\n\nvar _classCallCheck3 = _interopRequireDefault(_classCallCheck2);\n\nvar _createClass2 = require('babel-runtime/helpers/createClass');\n\nvar _createClass3 = _interopRequireDefault(_createClass2);\n\nvar _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');\n\nvar _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);\n\nvar _inherits2 = require('babel-runtime/helpers/inherits');\n\nvar _inherits3 = _interopRequireDefault(_inherits2);\n\nvar _react = require('react');\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _propTypes = require('prop-types');\n\nvar _propTypes2 = _interopRequireDefault(_propTypes);\n\nvar _classnames = require('classnames');\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/* These were earlier stateless functional components but had to be converted\nsince we need to use refs/findDOMNode to access the underlying DOM node to focus the correct completion,\nsomething that is not entirely possible with stateless functional components. One could\npresumably wrap them in a
before rendering but I think this is the better way to do it.\n */\n\nvar TextualCompletion = exports.TextualCompletion = function (_React$Component) {\n (0, _inherits3.default)(TextualCompletion, _React$Component);\n\n function TextualCompletion() {\n (0, _classCallCheck3.default)(this, TextualCompletion);\n return (0, _possibleConstructorReturn3.default)(this, (TextualCompletion.__proto__ || (0, _getPrototypeOf2.default)(TextualCompletion)).apply(this, arguments));\n }\n\n (0, _createClass3.default)(TextualCompletion, [{\n key: 'render',\n value: function render() {\n var _props = this.props,\n title = _props.title,\n subtitle = _props.subtitle,\n description = _props.description,\n className = _props.className,\n restProps = (0, _objectWithoutProperties3.default)(_props, ['title', 'subtitle', 'description', 'className']);\n\n return _react2.default.createElement(\n 'div',\n (0, _extends3.default)({ className: (0, _classnames2.default)('mx_Autocomplete_Completion_block', className) }, restProps),\n _react2.default.createElement(\n 'span',\n { className: 'mx_Autocomplete_Completion_title' },\n title\n ),\n _react2.default.createElement(\n 'span',\n { className: 'mx_Autocomplete_Completion_subtitle' },\n subtitle\n ),\n _react2.default.createElement(\n 'span',\n { className: 'mx_Autocomplete_Completion_description' },\n description\n )\n );\n }\n }]);\n return TextualCompletion;\n}(_react2.default.Component); /*\n Copyright 2016 Aviral Dasgupta\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nTextualCompletion.propTypes = {\n title: _propTypes2.default.string,\n subtitle: _propTypes2.default.string,\n description: _propTypes2.default.string,\n className: _propTypes2.default.string\n};\n\nvar PillCompletion = exports.PillCompletion = function (_React$Component2) {\n (0, _inherits3.default)(PillCompletion, _React$Component2);\n\n function PillCompletion() {\n (0, _classCallCheck3.default)(this, PillCompletion);\n return (0, _possibleConstructorReturn3.default)(this, (PillCompletion.__proto__ || (0, _getPrototypeOf2.default)(PillCompletion)).apply(this, arguments));\n }\n\n (0, _createClass3.default)(PillCompletion, [{\n key: 'render',\n value: function render() {\n var _props2 = this.props,\n title = _props2.title,\n subtitle = _props2.subtitle,\n description = _props2.description,\n initialComponent = _props2.initialComponent,\n className = _props2.className,\n restProps = (0, _objectWithoutProperties3.default)(_props2, ['title', 'subtitle', 'description', 'initialComponent', 'className']);\n\n return _react2.default.createElement(\n 'div',\n (0, _extends3.default)({ className: (0, _classnames2.default)('mx_Autocomplete_Completion_pill', className) }, restProps),\n initialComponent,\n _react2.default.createElement(\n 'span',\n { className: 'mx_Autocomplete_Completion_title' },\n title\n ),\n _react2.default.createElement(\n 'span',\n { className: 'mx_Autocomplete_Completion_subtitle' },\n subtitle\n ),\n _react2.default.createElement(\n 'span',\n { className: 'mx_Autocomplete_Completion_description' },\n description\n )\n );\n }\n }]);\n return PillCompletion;\n}(_react2.default.Component);\n\nPillCompletion.propTypes = {\n title: _propTypes2.default.string,\n subtitle: _propTypes2.default.string,\n description: _propTypes2.default.string,\n initialComponent: _propTypes2.default.element,\n className: _propTypes2.default.string\n};\n//# sourceMappingURL=Components.js.map","var def = require('./_object-dp').f;\nvar has = require('./_has');\nvar TAG = require('./_wks')('toStringTag');\n\nmodule.exports = function (it, tag, stat) {\n if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });\n};\n","// getting tag from 19.1.3.6 Object.prototype.toString()\nvar cof = require('./_cof');\nvar TAG = require('./_wks')('toStringTag');\n// ES3 wrong here\nvar ARG = cof(function () { return arguments; }()) == 'Arguments';\n\n// fallback for IE11 Script Access Denied error\nvar tryGet = function (it, key) {\n try {\n return it[key];\n } catch (e) { /* empty */ }\n};\n\nmodule.exports = function (it) {\n var O, T, B;\n return it === undefined ? 'Undefined' : it === null ? 'Null'\n // @@toStringTag case\n : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T\n // builtinTag case\n : ARG ? cof(O)\n // ES3 arguments fallback\n : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;\n};\n","var $export = require('./_export');\nvar defined = require('./_defined');\nvar fails = require('./_fails');\nvar spaces = require('./_string-ws');\nvar space = '[' + spaces + ']';\nvar non = '\\u200b\\u0085';\nvar ltrim = RegExp('^' + space + space + '*');\nvar rtrim = RegExp(space + space + '*$');\n\nvar exporter = function (KEY, exec, ALIAS) {\n var exp = {};\n var FORCE = fails(function () {\n return !!spaces[KEY]() || non[KEY]() != non;\n });\n var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];\n if (ALIAS) exp[ALIAS] = fn;\n $export($export.P + $export.F * FORCE, 'String', exp);\n};\n\n// 1 -> String#trimLeft\n// 2 -> String#trimRight\n// 3 -> String#trim\nvar trim = exporter.trim = function (string, TYPE) {\n string = String(defined(string));\n if (TYPE & 1) string = string.replace(ltrim, '');\n if (TYPE & 2) string = string.replace(rtrim, '');\n return string;\n};\n\nmodule.exports = exporter;\n","module.exports = {};\n","'use strict';\nvar LIBRARY = require('./_library');\nvar $export = require('./_export');\nvar redefine = require('./_redefine');\nvar hide = require('./_hide');\nvar Iterators = require('./_iterators');\nvar $iterCreate = require('./_iter-create');\nvar setToStringTag = require('./_set-to-string-tag');\nvar getPrototypeOf = require('./_object-gpo');\nvar ITERATOR = require('./_wks')('iterator');\nvar BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`\nvar FF_ITERATOR = '@@iterator';\nvar KEYS = 'keys';\nvar VALUES = 'values';\n\nvar returnThis = function () { return this; };\n\nmodule.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {\n $iterCreate(Constructor, NAME, next);\n var getMethod = function (kind) {\n if (!BUGGY && kind in proto) return proto[kind];\n switch (kind) {\n case KEYS: return function keys() { return new Constructor(this, kind); };\n case VALUES: return function values() { return new Constructor(this, kind); };\n } return function entries() { return new Constructor(this, kind); };\n };\n var TAG = NAME + ' Iterator';\n var DEF_VALUES = DEFAULT == VALUES;\n var VALUES_BUG = false;\n var proto = Base.prototype;\n var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];\n var $default = $native || getMethod(DEFAULT);\n var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;\n var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;\n var methods, key, IteratorPrototype;\n // Fix native\n if ($anyNative) {\n IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));\n if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {\n // Set @@toStringTag to native iterators\n setToStringTag(IteratorPrototype, TAG, true);\n // fix for some old engines\n if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis);\n }\n }\n // fix Array#{values, @@iterator}.name in V8 / FF\n if (DEF_VALUES && $native && $native.name !== VALUES) {\n VALUES_BUG = true;\n $default = function values() { return $native.call(this); };\n }\n // Define iterator\n if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {\n hide(proto, ITERATOR, $default);\n }\n // Plug for library\n Iterators[NAME] = $default;\n Iterators[TAG] = returnThis;\n if (DEFAULT) {\n methods = {\n values: DEF_VALUES ? $default : getMethod(VALUES),\n keys: IS_SET ? $default : getMethod(KEYS),\n entries: $entries\n };\n if (FORCED) for (key in methods) {\n if (!(key in proto)) redefine(proto, key, methods[key]);\n } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);\n }\n return methods;\n};\n","var classof = require('./_classof');\nvar ITERATOR = require('./_wks')('iterator');\nvar Iterators = require('./_iterators');\nmodule.exports = require('./_core').getIteratorMethod = function (it) {\n if (it != undefined) return it[ITERATOR]\n || it['@@iterator']\n || Iterators[classof(it)];\n};\n","exports.f = Object.getOwnPropertySymbols;\n","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\n'use strict';\n\nvar _assign = require('object-assign');\n\nvar ReactCurrentOwner = require('./ReactCurrentOwner');\n\nvar warning = require('fbjs/lib/warning');\nvar canDefineProperty = require('./canDefineProperty');\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar REACT_ELEMENT_TYPE = require('./ReactElementSymbol');\n\nvar RESERVED_PROPS = {\n key: true,\n ref: true,\n __self: true,\n __source: true\n};\n\nvar specialPropKeyWarningShown, specialPropRefWarningShown;\n\nfunction hasValidRef(config) {\n if (process.env.NODE_ENV !== 'production') {\n if (hasOwnProperty.call(config, 'ref')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n return config.ref !== undefined;\n}\n\nfunction hasValidKey(config) {\n if (process.env.NODE_ENV !== 'production') {\n if (hasOwnProperty.call(config, 'key')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'key').get;\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n return config.key !== undefined;\n}\n\nfunction defineKeyPropWarningGetter(props, displayName) {\n var warnAboutAccessingKey = function () {\n if (!specialPropKeyWarningShown) {\n specialPropKeyWarningShown = true;\n process.env.NODE_ENV !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0;\n }\n };\n warnAboutAccessingKey.isReactWarning = true;\n Object.defineProperty(props, 'key', {\n get: warnAboutAccessingKey,\n configurable: true\n });\n}\n\nfunction defineRefPropWarningGetter(props, displayName) {\n var warnAboutAccessingRef = function () {\n if (!specialPropRefWarningShown) {\n specialPropRefWarningShown = true;\n process.env.NODE_ENV !== 'production' ? warning(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0;\n }\n };\n warnAboutAccessingRef.isReactWarning = true;\n Object.defineProperty(props, 'ref', {\n get: warnAboutAccessingRef,\n configurable: true\n });\n}\n\n/**\n * Factory method to create a new React element. This no longer adheres to\n * the class pattern, so do not use new to call it. Also, no instanceof check\n * will work. Instead test $$typeof field against Symbol.for('react.element') to check\n * if something is a React Element.\n *\n * @param {*} type\n * @param {*} key\n * @param {string|object} ref\n * @param {*} self A *temporary* helper to detect places where `this` is\n * different from the `owner` when React.createElement is called, so that we\n * can warn. We want to get rid of owner and replace string `ref`s with arrow\n * functions, and as long as `this` and owner are the same, there will be no\n * change in behavior.\n * @param {*} source An annotation object (added by a transpiler or otherwise)\n * indicating filename, line number, and/or other information.\n * @param {*} owner\n * @param {*} props\n * @internal\n */\nvar ReactElement = function (type, key, ref, self, source, owner, props) {\n var element = {\n // This tag allow us to uniquely identify this as a React Element\n $$typeof: REACT_ELEMENT_TYPE,\n\n // Built-in properties that belong on the element\n type: type,\n key: key,\n ref: ref,\n props: props,\n\n // Record the component responsible for creating this element.\n _owner: owner\n };\n\n if (process.env.NODE_ENV !== 'production') {\n // The validation flag is currently mutative. We put it on\n // an external backing store so that we can freeze the whole object.\n // This can be replaced with a WeakMap once they are implemented in\n // commonly used development environments.\n element._store = {};\n\n // To make comparing ReactElements easier for testing purposes, we make\n // the validation flag non-enumerable (where possible, which should\n // include every environment we run tests in), so the test framework\n // ignores it.\n if (canDefineProperty) {\n Object.defineProperty(element._store, 'validated', {\n configurable: false,\n enumerable: false,\n writable: true,\n value: false\n });\n // self and source are DEV only properties.\n Object.defineProperty(element, '_self', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: self\n });\n // Two elements created in two different places should be considered\n // equal for testing purposes and therefore we hide it from enumeration.\n Object.defineProperty(element, '_source', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: source\n });\n } else {\n element._store.validated = false;\n element._self = self;\n element._source = source;\n }\n if (Object.freeze) {\n Object.freeze(element.props);\n Object.freeze(element);\n }\n }\n\n return element;\n};\n\n/**\n * Create and return a new ReactElement of the given type.\n * See https://facebook.github.io/react/docs/top-level-api.html#react.createelement\n */\nReactElement.createElement = function (type, config, children) {\n var propName;\n\n // Reserved names are extracted\n var props = {};\n\n var key = null;\n var ref = null;\n var self = null;\n var source = null;\n\n if (config != null) {\n if (hasValidRef(config)) {\n ref = config.ref;\n }\n if (hasValidKey(config)) {\n key = '' + config.key;\n }\n\n self = config.__self === undefined ? null : config.__self;\n source = config.__source === undefined ? null : config.__source;\n // Remaining properties are added to a new props object\n for (propName in config) {\n if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n props[propName] = config[propName];\n }\n }\n }\n\n // Children can be more than one argument, and those are transferred onto\n // the newly allocated props object.\n var childrenLength = arguments.length - 2;\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 2];\n }\n if (process.env.NODE_ENV !== 'production') {\n if (Object.freeze) {\n Object.freeze(childArray);\n }\n }\n props.children = childArray;\n }\n\n // Resolve default props\n if (type && type.defaultProps) {\n var defaultProps = type.defaultProps;\n for (propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n if (key || ref) {\n if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) {\n var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;\n if (key) {\n defineKeyPropWarningGetter(props, displayName);\n }\n if (ref) {\n defineRefPropWarningGetter(props, displayName);\n }\n }\n }\n }\n return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);\n};\n\n/**\n * Return a function that produces ReactElements of a given type.\n * See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory\n */\nReactElement.createFactory = function (type) {\n var factory = ReactElement.createElement.bind(null, type);\n // Expose the type on the factory and the prototype so that it can be\n // easily accessed on elements. E.g. `
.type === Foo`.\n // This should not be named `constructor` since this may not be the function\n // that created the element, and it may not even be a constructor.\n // Legacy hook TODO: Warn if this is accessed\n factory.type = type;\n return factory;\n};\n\nReactElement.cloneAndReplaceKey = function (oldElement, newKey) {\n var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);\n\n return newElement;\n};\n\n/**\n * Clone and return a new ReactElement using element as the starting point.\n * See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement\n */\nReactElement.cloneElement = function (element, config, children) {\n var propName;\n\n // Original props are copied\n var props = _assign({}, element.props);\n\n // Reserved names are extracted\n var key = element.key;\n var ref = element.ref;\n // Self is preserved since the owner is preserved.\n var self = element._self;\n // Source is preserved since cloneElement is unlikely to be targeted by a\n // transpiler, and the original source is probably a better indicator of the\n // true owner.\n var source = element._source;\n\n // Owner will be preserved, unless ref is overridden\n var owner = element._owner;\n\n if (config != null) {\n if (hasValidRef(config)) {\n // Silently steal the ref from the parent.\n ref = config.ref;\n owner = ReactCurrentOwner.current;\n }\n if (hasValidKey(config)) {\n key = '' + config.key;\n }\n\n // Remaining properties override existing props\n var defaultProps;\n if (element.type && element.type.defaultProps) {\n defaultProps = element.type.defaultProps;\n }\n for (propName in config) {\n if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n if (config[propName] === undefined && defaultProps !== undefined) {\n // Resolve default props\n props[propName] = defaultProps[propName];\n } else {\n props[propName] = config[propName];\n }\n }\n }\n }\n\n // Children can be more than one argument, and those are transferred onto\n // the newly allocated props object.\n var childrenLength = arguments.length - 2;\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 2];\n }\n props.children = childArray;\n }\n\n return ReactElement(element.type, key, ref, self, source, owner, props);\n};\n\n/**\n * Verifies the object is a ReactElement.\n * See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement\n * @param {?object} object\n * @return {boolean} True if `object` is a valid component.\n * @final\n */\nReactElement.isValidElement = function (object) {\n return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n};\n\nmodule.exports = ReactElement;","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\n'use strict';\n\nvar _prodInvariant = require('./reactProdInvariant');\n\nvar invariant = require('fbjs/lib/invariant');\n\nfunction checkMask(value, bitmask) {\n return (value & bitmask) === bitmask;\n}\n\nvar DOMPropertyInjection = {\n /**\n * Mapping from normalized, camelcased property names to a configuration that\n * specifies how the associated DOM property should be accessed or rendered.\n */\n MUST_USE_PROPERTY: 0x1,\n HAS_BOOLEAN_VALUE: 0x4,\n HAS_NUMERIC_VALUE: 0x8,\n HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8,\n HAS_OVERLOADED_BOOLEAN_VALUE: 0x20,\n\n /**\n * Inject some specialized knowledge about the DOM. This takes a config object\n * with the following properties:\n *\n * isCustomAttribute: function that given an attribute name will return true\n * if it can be inserted into the DOM verbatim. Useful for data-* or aria-*\n * attributes where it's impossible to enumerate all of the possible\n * attribute names,\n *\n * Properties: object mapping DOM property name to one of the\n * DOMPropertyInjection constants or null. If your attribute isn't in here,\n * it won't get written to the DOM.\n *\n * DOMAttributeNames: object mapping React attribute name to the DOM\n * attribute name. Attribute names not specified use the **lowercase**\n * normalized name.\n *\n * DOMAttributeNamespaces: object mapping React attribute name to the DOM\n * attribute namespace URL. (Attribute names not specified use no namespace.)\n *\n * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties.\n * Property names not specified use the normalized name.\n *\n * DOMMutationMethods: Properties that require special mutation methods. If\n * `value` is undefined, the mutation method should unset the property.\n *\n * @param {object} domPropertyConfig the config as described above.\n */\n injectDOMPropertyConfig: function (domPropertyConfig) {\n var Injection = DOMPropertyInjection;\n var Properties = domPropertyConfig.Properties || {};\n var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {};\n var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {};\n var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {};\n var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};\n\n if (domPropertyConfig.isCustomAttribute) {\n DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute);\n }\n\n for (var propName in Properties) {\n !!DOMProperty.properties.hasOwnProperty(propName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\\'re trying to inject DOM property \\'%s\\' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.', propName) : _prodInvariant('48', propName) : void 0;\n\n var lowerCased = propName.toLowerCase();\n var propConfig = Properties[propName];\n\n var propertyInfo = {\n attributeName: lowerCased,\n attributeNamespace: null,\n propertyName: propName,\n mutationMethod: null,\n\n mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY),\n hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE),\n hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE),\n hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE),\n hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE)\n };\n !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s', propName) : _prodInvariant('50', propName) : void 0;\n\n if (process.env.NODE_ENV !== 'production') {\n DOMProperty.getPossibleStandardName[lowerCased] = propName;\n }\n\n if (DOMAttributeNames.hasOwnProperty(propName)) {\n var attributeName = DOMAttributeNames[propName];\n propertyInfo.attributeName = attributeName;\n if (process.env.NODE_ENV !== 'production') {\n DOMProperty.getPossibleStandardName[attributeName] = propName;\n }\n }\n\n if (DOMAttributeNamespaces.hasOwnProperty(propName)) {\n propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName];\n }\n\n if (DOMPropertyNames.hasOwnProperty(propName)) {\n propertyInfo.propertyName = DOMPropertyNames[propName];\n }\n\n if (DOMMutationMethods.hasOwnProperty(propName)) {\n propertyInfo.mutationMethod = DOMMutationMethods[propName];\n }\n\n DOMProperty.properties[propName] = propertyInfo;\n }\n }\n};\n\n/* eslint-disable max-len */\nvar ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD';\n/* eslint-enable max-len */\n\n/**\n * DOMProperty exports lookup objects that can be used like functions:\n *\n * > DOMProperty.isValid['id']\n * true\n * > DOMProperty.isValid['foobar']\n * undefined\n *\n * Although this may be confusing, it performs better in general.\n *\n * @see http://jsperf.com/key-exists\n * @see http://jsperf.com/key-missing\n */\nvar DOMProperty = {\n ID_ATTRIBUTE_NAME: 'data-reactid',\n ROOT_ATTRIBUTE_NAME: 'data-reactroot',\n\n ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR,\n ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\\\-.0-9\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040',\n\n /**\n * Map from property \"standard name\" to an object with info about how to set\n * the property in the DOM. Each object contains:\n *\n * attributeName:\n * Used when rendering markup or with `*Attribute()`.\n * attributeNamespace\n * propertyName:\n * Used on DOM node instances. (This includes properties that mutate due to\n * external factors.)\n * mutationMethod:\n * If non-null, used instead of the property or `setAttribute()` after\n * initial render.\n * mustUseProperty:\n * Whether the property must be accessed and mutated as an object property.\n * hasBooleanValue:\n * Whether the property should be removed when set to a falsey value.\n * hasNumericValue:\n * Whether the property must be numeric or parse as a numeric and should be\n * removed when set to a falsey value.\n * hasPositiveNumericValue:\n * Whether the property must be positive numeric or parse as a positive\n * numeric and should be removed when set to a falsey value.\n * hasOverloadedBooleanValue:\n * Whether the property can be used as a flag as well as with a value.\n * Removed when strictly equal to false; present without a value when\n * strictly equal to true; present with a value otherwise.\n */\n properties: {},\n\n /**\n * Mapping from lowercase property names to the properly cased version, used\n * to warn in the case of missing properties. Available only in __DEV__.\n *\n * autofocus is predefined, because adding it to the property whitelist\n * causes unintended side effects.\n *\n * @type {Object}\n */\n getPossibleStandardName: process.env.NODE_ENV !== 'production' ? { autofocus: 'autoFocus' } : null,\n\n /**\n * All of the isCustomAttribute() functions that have been injected.\n */\n _isCustomAttributeFunctions: [],\n\n /**\n * Checks whether a property name is a custom attribute.\n * @method\n */\n isCustomAttribute: function (attributeName) {\n for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) {\n var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i];\n if (isCustomAttributeFn(attributeName)) {\n return true;\n }\n }\n return false;\n },\n\n injection: DOMPropertyInjection\n};\n\nmodule.exports = DOMProperty;","/**\n * Copyright (c) 2015-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n */\n\n'use strict';\n\nvar DOMNamespaces = require('./DOMNamespaces');\nvar setInnerHTML = require('./setInnerHTML');\n\nvar createMicrosoftUnsafeLocalFunction = require('./createMicrosoftUnsafeLocalFunction');\nvar setTextContent = require('./setTextContent');\n\nvar ELEMENT_NODE_TYPE = 1;\nvar DOCUMENT_FRAGMENT_NODE_TYPE = 11;\n\n/**\n * In IE (8-11) and Edge, appending nodes with no children is dramatically\n * faster than appending a full subtree, so we essentially queue up the\n * .appendChild calls here and apply them so each node is added to its parent\n * before any children are added.\n *\n * In other browsers, doing so is slower or neutral compared to the other order\n * (in Firefox, twice as slow) so we only do this inversion in IE.\n *\n * See https://github.com/spicyj/innerhtml-vs-createelement-vs-clonenode.\n */\nvar enableLazy = typeof document !== 'undefined' && typeof document.documentMode === 'number' || typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && /\\bEdge\\/\\d/.test(navigator.userAgent);\n\nfunction insertTreeChildren(tree) {\n if (!enableLazy) {\n return;\n }\n var node = tree.node;\n var children = tree.children;\n if (children.length) {\n for (var i = 0; i < children.length; i++) {\n insertTreeBefore(node, children[i], null);\n }\n } else if (tree.html != null) {\n setInnerHTML(node, tree.html);\n } else if (tree.text != null) {\n setTextContent(node, tree.text);\n }\n}\n\nvar insertTreeBefore = createMicrosoftUnsafeLocalFunction(function (parentNode, tree, referenceNode) {\n // DocumentFragments aren't actually part of the DOM after insertion so\n // appending children won't update the DOM. We need to ensure the fragment\n // is properly populated first, breaking out of our lazy approach for just\n // this level. Also, some