(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["converse"] = factory();
else
root["converse"] = factory();
})(this, () => {
return /******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 494:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
const atob = __webpack_require__(672);
const btoa = __webpack_require__(817);
module.exports = {
atob,
btoa
};
/***/ }),
/***/ 672:
/***/ ((module) => {
"use strict";
/**
* Implementation of atob() according to the HTML and Infra specs, except that
* instead of throwing INVALID_CHARACTER_ERR we return null.
*/
function atob(data) {
if (arguments.length === 0) {
throw new TypeError("1 argument required, but only 0 present.");
}
// Web IDL requires DOMStrings to just be converted using ECMAScript
// ToString, which in our case amounts to using a template literal.
data = `${data}`;
// "Remove all ASCII whitespace from data."
data = data.replace(/[ \t\n\f\r]/g, "");
// "If data's length divides by 4 leaving no remainder, then: if data ends
// with one or two U+003D (=) code points, then remove them from data."
if (data.length % 4 === 0) {
data = data.replace(/==?$/, "");
}
// "If data's length divides by 4 leaving a remainder of 1, then return
// failure."
//
// "If data contains a code point that is not one of
//
// U+002B (+)
// U+002F (/)
// ASCII alphanumeric
//
// then return failure."
if (data.length % 4 === 1 || /[^+/0-9A-Za-z]/.test(data)) {
return null;
}
// "Let output be an empty byte sequence."
let output = "";
// "Let buffer be an empty buffer that can have bits appended to it."
//
// We append bits via left-shift and or. accumulatedBits is used to track
// when we've gotten to 24 bits.
let buffer = 0;
let accumulatedBits = 0;
// "Let position be a position variable for data, initially pointing at the
// start of data."
//
// "While position does not point past the end of data:"
for (let i = 0; i < data.length; i++) {
// "Find the code point pointed to by position in the second column of
// Table 1: The Base 64 Alphabet of RFC 4648. Let n be the number given in
// the first cell of the same row.
//
// "Append to buffer the six bits corresponding to n, most significant bit
// first."
//
// atobLookup() implements the table from RFC 4648.
buffer <<= 6;
buffer |= atobLookup(data[i]);
accumulatedBits += 6;
// "If buffer has accumulated 24 bits, interpret them as three 8-bit
// big-endian numbers. Append three bytes with values equal to those
// numbers to output, in the same order, and then empty buffer."
if (accumulatedBits === 24) {
output += String.fromCharCode((buffer & 0xff0000) >> 16);
output += String.fromCharCode((buffer & 0xff00) >> 8);
output += String.fromCharCode(buffer & 0xff);
buffer = accumulatedBits = 0;
}
// "Advance position by 1."
}
// "If buffer is not empty, it contains either 12 or 18 bits. If it contains
// 12 bits, then discard the last four and interpret the remaining eight as
// an 8-bit big-endian number. If it contains 18 bits, then discard the last
// two and interpret the remaining 16 as two 8-bit big-endian numbers. Append
// the one or two bytes with values equal to those one or two numbers to
// output, in the same order."
if (accumulatedBits === 12) {
buffer >>= 4;
output += String.fromCharCode(buffer);
} else if (accumulatedBits === 18) {
buffer >>= 2;
output += String.fromCharCode((buffer & 0xff00) >> 8);
output += String.fromCharCode(buffer & 0xff);
}
// "Return output."
return output;
}
/**
* A lookup table for atob(), which converts an ASCII character to the
* corresponding six-bit number.
*/
const keystr =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function atobLookup(chr) {
const index = keystr.indexOf(chr);
// Throw exception if character is not in the lookup string; should not be hit in tests
return index < 0 ? undefined : index;
}
module.exports = atob;
/***/ }),
/***/ 817:
/***/ ((module) => {
"use strict";
/**
* btoa() as defined by the HTML and Infra specs, which mostly just references
* RFC 4648.
*/
function btoa(s) {
if (arguments.length === 0) {
throw new TypeError("1 argument required, but only 0 present.");
}
let i;
// String conversion as required by Web IDL.
s = `${s}`;
// "The btoa() method must throw an "InvalidCharacterError" DOMException if
// data contains any character whose code point is greater than U+00FF."
for (i = 0; i < s.length; i++) {
if (s.charCodeAt(i) > 255) {
return null;
}
}
let out = "";
for (i = 0; i < s.length; i += 3) {
const groupsOfSix = [undefined, undefined, undefined, undefined];
groupsOfSix[0] = s.charCodeAt(i) >> 2;
groupsOfSix[1] = (s.charCodeAt(i) & 0x03) << 4;
if (s.length > i + 1) {
groupsOfSix[1] |= s.charCodeAt(i + 1) >> 4;
groupsOfSix[2] = (s.charCodeAt(i + 1) & 0x0f) << 2;
}
if (s.length > i + 2) {
groupsOfSix[2] |= s.charCodeAt(i + 2) >> 6;
groupsOfSix[3] = s.charCodeAt(i + 2) & 0x3f;
}
for (let j = 0; j < groupsOfSix.length; j++) {
if (typeof groupsOfSix[j] === "undefined") {
out += "=";
} else {
out += btoaLookup(groupsOfSix[j]);
}
}
}
return out;
}
/**
* Lookup table for btoa(), which converts a six-bit number into the
* corresponding ASCII character.
*/
const keystr =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function btoaLookup(index) {
if (index >= 0 && index < 64) {
return keystr[index];
}
// Throw INVALID_CHARACTER_ERR exception here -- won't be hit in the tests.
return undefined;
}
module.exports = btoa;
/***/ }),
/***/ 487:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
(function (global, factory) {
true ? factory(exports, __webpack_require__(483)) : 0;
})(this, function (exports, localforage) {
'use strict';
localforage = 'default' in localforage ? localforage['default'] : localforage;
function getSerializerPromise(localForageInstance) {
if (getSerializerPromise.result) {
return getSerializerPromise.result;
}
if (!localForageInstance || typeof localForageInstance.getSerializer !== 'function') {
return Promise.reject(new Error('localforage.getSerializer() was not available! ' + 'localforage v1.4+ is required!'));
}
getSerializerPromise.result = localForageInstance.getSerializer();
return getSerializerPromise.result;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
return promise;
}
function getItemKeyValue(key, callback) {
var localforageInstance = this;
var promise = localforageInstance.getItem(key).then(function (value) {
return {
key: key,
value: value
};
});
executeCallback(promise, callback);
return promise;
}
function getItemsGeneric(keys /*, callback*/) {
var localforageInstance = this;
var promise = new Promise(function (resolve, reject) {
var itemPromises = [];
for (var i = 0, len = keys.length; i < len; i++) {
itemPromises.push(getItemKeyValue.call(localforageInstance, keys[i]));
}
Promise.all(itemPromises).then(function (keyValuePairs) {
var result = {};
for (var i = 0, len = keyValuePairs.length; i < len; i++) {
var keyValuePair = keyValuePairs[i];
result[keyValuePair.key] = keyValuePair.value;
}
resolve(result);
}).catch(reject);
});
return promise;
}
function getAllItemsUsingIterate() {
var localforageInstance = this;
var accumulator = {};
return localforageInstance.iterate(function (value, key /*, iterationNumber*/) {
accumulator[key] = value;
}).then(function () {
return accumulator;
});
}
function getIDBKeyRange() {
/* global IDBKeyRange, webkitIDBKeyRange, mozIDBKeyRange */
if (typeof IDBKeyRange !== 'undefined') {
return IDBKeyRange;
}
if (typeof webkitIDBKeyRange !== 'undefined') {
return webkitIDBKeyRange;
}
if (typeof mozIDBKeyRange !== 'undefined') {
return mozIDBKeyRange;
}
}
var idbKeyRange = getIDBKeyRange();
function getItemsIndexedDB(keys /*, callback*/) {
keys = keys.slice();
var localforageInstance = this;
function comparer(a, b) {
return a < b ? -1 : a > b ? 1 : 0;
}
var promise = new Promise(function (resolve, reject) {
localforageInstance.ready().then(function () {
// Thanks https://hacks.mozilla.org/2014/06/breaking-the-borders-of-indexeddb/
var dbInfo = localforageInstance._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var set = keys.sort(comparer);
var keyRangeValue = idbKeyRange.bound(keys[0], keys[keys.length - 1], false, false);
var req;
if ('getAll' in store) {
req = store.getAll(keyRangeValue);
req.onsuccess = function () {
var value = req.result;
if (value === undefined) {
value = null;
}
resolve(value);
};
} else {
req = store.openCursor(keyRangeValue);
var result = {};
var i = 0;
req.onsuccess = function () /*event*/{
var cursor = req.result; // event.target.result;
if (!cursor) {
resolve(result);
return;
}
var key = cursor.key;
while (key > set[i]) {
i++; // The cursor has passed beyond this key. Check next.
if (i === set.length) {
// There is no next. Stop searching.
resolve(result);
return;
}
}
if (key === set[i]) {
// The current cursor value should be included and we should continue
// a single step in case next item has the same key or possibly our
// next key in set.
var value = cursor.value;
if (value === undefined) {
value = null;
}
result[key] = value;
// onfound(cursor.value);
cursor.continue();
} else {
// cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.
cursor.continue(set[i]);
}
};
}
req.onerror = function () /*event*/{
reject(req.error);
};
}).catch(reject);
});
return promise;
}
function getItemsWebsql(keys /*, callback*/) {
var localforageInstance = this;
var promise = new Promise(function (resolve, reject) {
localforageInstance.ready().then(function () {
return getSerializerPromise(localforageInstance);
}).then(function (serializer) {
var dbInfo = localforageInstance._dbInfo;
dbInfo.db.transaction(function (t) {
var queryParts = new Array(keys.length);
for (var i = 0, len = keys.length; i < len; i++) {
queryParts[i] = '?';
}
t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE (key IN (' + queryParts.join(',') + '))', keys, function (t, results) {
var result = {};
var rows = results.rows;
for (var i = 0, len = rows.length; i < len; i++) {
var item = rows.item(i);
var value = item.value;
// Check to see if this is serialized content we need to
// unpack.
if (value) {
value = serializer.deserialize(value);
}
result[item.key] = value;
}
resolve(result);
}, function (t, error) {
reject(error);
});
});
}).catch(reject);
});
return promise;
}
function localforageGetItems(keys, callback) {
var localforageInstance = this;
var promise;
if (!arguments.length || keys === null) {
promise = getAllItemsUsingIterate.apply(localforageInstance);
} else {
var currentDriver = localforageInstance.driver();
if (currentDriver === localforageInstance.INDEXEDDB) {
promise = getItemsIndexedDB.apply(localforageInstance, arguments);
} else if (currentDriver === localforageInstance.WEBSQL) {
promise = getItemsWebsql.apply(localforageInstance, arguments);
} else {
promise = getItemsGeneric.apply(localforageInstance, arguments);
}
}
executeCallback(promise, callback);
return promise;
}
function extendPrototype(localforage$$1) {
var localforagePrototype = Object.getPrototypeOf(localforage$$1);
if (localforagePrototype) {
localforagePrototype.getItems = localforageGetItems;
localforagePrototype.getItems.indexedDB = function () {
return getItemsIndexedDB.apply(this, arguments);
};
localforagePrototype.getItems.websql = function () {
return getItemsWebsql.apply(this, arguments);
};
localforagePrototype.getItems.generic = function () {
return getItemsGeneric.apply(this, arguments);
};
}
}
var extendPrototypeResult = extendPrototype(localforage);
exports.localforageGetItems = localforageGetItems;
exports.extendPrototype = extendPrototype;
exports.extendPrototypeResult = extendPrototypeResult;
exports.getItemsGeneric = getItemsGeneric;
Object.defineProperty(exports, '__esModule', {
value: true
});
});
/***/ }),
/***/ 293:
/***/ ((module, exports, __webpack_require__) => {
var __WEBPACK_AMD_DEFINE_RESULT__;/* global window, exports, define */
!function () {
'use strict';
var re = {
not_string: /[^s]/,
not_bool: /[^t]/,
not_type: /[^T]/,
not_primitive: /[^v]/,
number: /[diefg]/,
numeric_arg: /[bcdiefguxX]/,
json: /[j]/,
not_json: /[^j]/,
text: /^[^\x25]+/,
modulo: /^\x25{2}/,
placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
key: /^([a-z_][a-z_\d]*)/i,
key_access: /^\.([a-z_][a-z_\d]*)/i,
index_access: /^\[(\d+)\]/,
sign: /^[+-]/
};
function sprintf(key) {
// `arguments` is not an array, but should be fine for this call
return sprintf_format(sprintf_parse(key), arguments);
}
function vsprintf(fmt, argv) {
return sprintf.apply(null, [fmt].concat(argv || []));
}
function sprintf_format(parse_tree, argv) {
var cursor = 1,
tree_length = parse_tree.length,
arg,
output = '',
i,
k,
ph,
pad,
pad_character,
pad_length,
is_positive,
sign;
for (i = 0; i < tree_length; i++) {
if (typeof parse_tree[i] === 'string') {
output += parse_tree[i];
} else if (typeof parse_tree[i] === 'object') {
ph = parse_tree[i]; // convenience purposes only
if (ph.keys) {
// keyword argument
arg = argv[cursor];
for (k = 0; k < ph.keys.length; k++) {
if (arg == undefined) {
throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k - 1]));
}
arg = arg[ph.keys[k]];
}
} else if (ph.param_no) {
// positional argument (explicit)
arg = argv[ph.param_no];
} else {
// positional argument (implicit)
arg = argv[cursor++];
}
if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
arg = arg();
}
if (re.numeric_arg.test(ph.type) && typeof arg !== 'number' && isNaN(arg)) {
throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg));
}
if (re.number.test(ph.type)) {
is_positive = arg >= 0;
}
switch (ph.type) {
case 'b':
arg = parseInt(arg, 10).toString(2);
break;
case 'c':
arg = String.fromCharCode(parseInt(arg, 10));
break;
case 'd':
case 'i':
arg = parseInt(arg, 10);
break;
case 'j':
arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0);
break;
case 'e':
arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential();
break;
case 'f':
arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg);
break;
case 'g':
arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg);
break;
case 'o':
arg = (parseInt(arg, 10) >>> 0).toString(8);
break;
case 's':
arg = String(arg);
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case 't':
arg = String(!!arg);
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case 'T':
arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case 'u':
arg = parseInt(arg, 10) >>> 0;
break;
case 'v':
arg = arg.valueOf();
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case 'x':
arg = (parseInt(arg, 10) >>> 0).toString(16);
break;
case 'X':
arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase();
break;
}
if (re.json.test(ph.type)) {
output += arg;
} else {
if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
sign = is_positive ? '+' : '-';
arg = arg.toString().replace(re.sign, '');
} else {
sign = '';
}
pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' ';
pad_length = ph.width - (sign + arg).length;
pad = ph.width ? pad_length > 0 ? pad_character.repeat(pad_length) : '' : '';
output += ph.align ? sign + arg + pad : pad_character === '0' ? sign + pad + arg : pad + sign + arg;
}
}
}
return output;
}
var sprintf_cache = Object.create(null);
function sprintf_parse(fmt) {
if (sprintf_cache[fmt]) {
return sprintf_cache[fmt];
}
var _fmt = fmt,
match,
parse_tree = [],
arg_names = 0;
while (_fmt) {
if ((match = re.text.exec(_fmt)) !== null) {
parse_tree.push(match[0]);
} else if ((match = re.modulo.exec(_fmt)) !== null) {
parse_tree.push('%');
} else if ((match = re.placeholder.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1;
var field_list = [],
replacement_field = match[2],
field_match = [];
if ((field_match = re.key.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
if ((field_match = re.key_access.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
} else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
} else {
throw new SyntaxError('[sprintf] failed to parse named argument key');
}
}
} else {
throw new SyntaxError('[sprintf] failed to parse named argument key');
}
match[2] = field_list;
} else {
arg_names |= 2;
}
if (arg_names === 3) {
throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported');
}
parse_tree.push({
placeholder: match[0],
param_no: match[1],
keys: match[2],
sign: match[3],
pad_char: match[4],
align: match[5],
width: match[6],
precision: match[7],
type: match[8]
});
} else {
throw new SyntaxError('[sprintf] unexpected placeholder');
}
_fmt = _fmt.substring(match[0].length);
}
return sprintf_cache[fmt] = parse_tree;
}
/**
* export to either browser or node.js
*/
/* eslint-disable quote-props */
if (true) {
exports.sprintf = sprintf;
exports.vsprintf = vsprintf;
}
if (typeof window !== 'undefined') {
window['sprintf'] = sprintf;
window['vsprintf'] = vsprintf;
if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
return {
'sprintf': sprintf,
'vsprintf': vsprintf
};
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
}
/* eslint-enable quote-props */
}(); // eslint-disable-line
/***/ }),
/***/ 939:
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* URI.js - Mutating URLs
* IPv6 Support
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
(function (root, factory) {
'use strict';
// https://github.com/umdjs/umd/blob/master/returnExports.js
if ( true && module.exports) {
// Node
module.exports = factory();
} else if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
})(this, function (root) {
'use strict';
/*
var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156";
var _out = IPv6.best(_in);
var _expected = "fe80::204:61ff:fe9d:f156";
console.log(_in, _out, _expected, _out === _expected);
*/
// save current IPv6 variable, if any
var _IPv6 = root && root.IPv6;
function bestPresentation(address) {
// based on:
// Javascript to test an IPv6 address for proper format, and to
// present the "best text representation" according to IETF Draft RFC at
// http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04
// 8 Feb 2010 Rich Brown, Dartware, LLC
// Please feel free to use this code as long as you provide a link to
// http://www.intermapper.com
// http://intermapper.com/support/tools/IPV6-Validator.aspx
// http://download.dartware.com/thirdparty/ipv6validator.js
var _address = address.toLowerCase();
var segments = _address.split(':');
var length = segments.length;
var total = 8;
// trim colons (:: or ::a:b:c… or …a:b:c::)
if (segments[0] === '' && segments[1] === '' && segments[2] === '') {
// must have been ::
// remove first two items
segments.shift();
segments.shift();
} else if (segments[0] === '' && segments[1] === '') {
// must have been ::xxxx
// remove the first item
segments.shift();
} else if (segments[length - 1] === '' && segments[length - 2] === '') {
// must have been xxxx::
segments.pop();
}
length = segments.length;
// adjust total segments for IPv4 trailer
if (segments[length - 1].indexOf('.') !== -1) {
// found a "." which means IPv4
total = 7;
}
// fill empty segments them with "0000"
var pos;
for (pos = 0; pos < length; pos++) {
if (segments[pos] === '') {
break;
}
}
if (pos < total) {
segments.splice(pos, 1, '0000');
while (segments.length < total) {
segments.splice(pos, 0, '0000');
}
}
// strip leading zeros
var _segments;
for (var i = 0; i < total; i++) {
_segments = segments[i].split('');
for (var j = 0; j < 3; j++) {
if (_segments[0] === '0' && _segments.length > 1) {
_segments.splice(0, 1);
} else {
break;
}
}
segments[i] = _segments.join('');
}
// find longest sequence of zeroes and coalesce them into one segment
var best = -1;
var _best = 0;
var _current = 0;
var current = -1;
var inzeroes = false;
// i; already declared
for (i = 0; i < total; i++) {
if (inzeroes) {
if (segments[i] === '0') {
_current += 1;
} else {
inzeroes = false;
if (_current > _best) {
best = current;
_best = _current;
}
}
} else {
if (segments[i] === '0') {
inzeroes = true;
current = i;
_current = 1;
}
}
}
if (_current > _best) {
best = current;
_best = _current;
}
if (_best > 1) {
segments.splice(best, _best, '');
}
length = segments.length;
// assemble remaining segments
var result = '';
if (segments[0] === '') {
result = ':';
}
for (i = 0; i < length; i++) {
result += segments[i];
if (i === length - 1) {
break;
}
result += ':';
}
if (segments[length - 1] === '') {
result += ':';
}
return result;
}
function noConflict() {
/*jshint validthis: true */
if (root.IPv6 === this) {
root.IPv6 = _IPv6;
}
return this;
}
return {
best: bestPresentation,
noConflict: noConflict
};
});
/***/ }),
/***/ 338:
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* URI.js - Mutating URLs
* Second Level Domain (SLD) Support
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
(function (root, factory) {
'use strict';
// https://github.com/umdjs/umd/blob/master/returnExports.js
if ( true && module.exports) {
// Node
module.exports = factory();
} else if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
})(this, function (root) {
'use strict';
// save current SecondLevelDomains variable, if any
var _SecondLevelDomains = root && root.SecondLevelDomains;
var SLD = {
// list of known Second Level Domains
// converted list of SLDs from https://github.com/gavingmiller/second-level-domains
// ----
// publicsuffix.org is more current and actually used by a couple of browsers internally.
// downside is it also contains domains like "dyndns.org" - which is fine for the security
// issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js
// ----
list: {
'ac': ' com gov mil net org ',
'ae': ' ac co gov mil name net org pro sch ',
'af': ' com edu gov net org ',
'al': ' com edu gov mil net org ',
'ao': ' co ed gv it og pb ',
'ar': ' com edu gob gov int mil net org tur ',
'at': ' ac co gv or ',
'au': ' asn com csiro edu gov id net org ',
'ba': ' co com edu gov mil net org rs unbi unmo unsa untz unze ',
'bb': ' biz co com edu gov info net org store tv ',
'bh': ' biz cc com edu gov info net org ',
'bn': ' com edu gov net org ',
'bo': ' com edu gob gov int mil net org tv ',
'br': ' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ',
'bs': ' com edu gov net org ',
'bz': ' du et om ov rg ',
'ca': ' ab bc mb nb nf nl ns nt nu on pe qc sk yk ',
'ck': ' biz co edu gen gov info net org ',
'cn': ' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ',
'co': ' com edu gov mil net nom org ',
'cr': ' ac c co ed fi go or sa ',
'cy': ' ac biz com ekloges gov ltd name net org parliament press pro tm ',
'do': ' art com edu gob gov mil net org sld web ',
'dz': ' art asso com edu gov net org pol ',
'ec': ' com edu fin gov info med mil net org pro ',
'eg': ' com edu eun gov mil name net org sci ',
'er': ' com edu gov ind mil net org rochest w ',
'es': ' com edu gob nom org ',
'et': ' biz com edu gov info name net org ',
'fj': ' ac biz com info mil name net org pro ',
'fk': ' ac co gov net nom org ',
'fr': ' asso com f gouv nom prd presse tm ',
'gg': ' co net org ',
'gh': ' com edu gov mil org ',
'gn': ' ac com gov net org ',
'gr': ' com edu gov mil net org ',
'gt': ' com edu gob ind mil net org ',
'gu': ' com edu gov net org ',
'hk': ' com edu gov idv net org ',
'hu': ' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ',
'id': ' ac co go mil net or sch web ',
'il': ' ac co gov idf k12 muni net org ',
'in': ' ac co edu ernet firm gen gov i ind mil net nic org res ',
'iq': ' com edu gov i mil net org ',
'ir': ' ac co dnssec gov i id net org sch ',
'it': ' edu gov ',
'je': ' co net org ',
'jo': ' com edu gov mil name net org sch ',
'jp': ' ac ad co ed go gr lg ne or ',
'ke': ' ac co go info me mobi ne or sc ',
'kh': ' com edu gov mil net org per ',
'ki': ' biz com de edu gov info mob net org tel ',
'km': ' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ',
'kn': ' edu gov net org ',
'kr': ' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ',
'kw': ' com edu gov net org ',
'ky': ' com edu gov net org ',
'kz': ' com edu gov mil net org ',
'lb': ' com edu gov net org ',
'lk': ' assn com edu gov grp hotel int ltd net ngo org sch soc web ',
'lr': ' com edu gov net org ',
'lv': ' asn com conf edu gov id mil net org ',
'ly': ' com edu gov id med net org plc sch ',
'ma': ' ac co gov m net org press ',
'mc': ' asso tm ',
'me': ' ac co edu gov its net org priv ',
'mg': ' com edu gov mil nom org prd tm ',
'mk': ' com edu gov inf name net org pro ',
'ml': ' com edu gov net org presse ',
'mn': ' edu gov org ',
'mo': ' com edu gov net org ',
'mt': ' com edu gov net org ',
'mv': ' aero biz com coop edu gov info int mil museum name net org pro ',
'mw': ' ac co com coop edu gov int museum net org ',
'mx': ' com edu gob net org ',
'my': ' com edu gov mil name net org sch ',
'nf': ' arts com firm info net other per rec store web ',
'ng': ' biz com edu gov mil mobi name net org sch ',
'ni': ' ac co com edu gob mil net nom org ',
'np': ' com edu gov mil net org ',
'nr': ' biz com edu gov info net org ',
'om': ' ac biz co com edu gov med mil museum net org pro sch ',
'pe': ' com edu gob mil net nom org sld ',
'ph': ' com edu gov i mil net ngo org ',
'pk': ' biz com edu fam gob gok gon gop gos gov net org web ',
'pl': ' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ',
'pr': ' ac biz com edu est gov info isla name net org pro prof ',
'ps': ' com edu gov net org plo sec ',
'pw': ' belau co ed go ne or ',
'ro': ' arts com firm info nom nt org rec store tm www ',
'rs': ' ac co edu gov in org ',
'sb': ' com edu gov net org ',
'sc': ' com edu gov net org ',
'sh': ' co com edu gov net nom org ',
'sl': ' com edu gov net org ',
'st': ' co com consulado edu embaixada gov mil net org principe saotome store ',
'sv': ' com edu gob org red ',
'sz': ' ac co org ',
'tr': ' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ',
'tt': ' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ',
'tw': ' club com ebiz edu game gov idv mil net org ',
'mu': ' ac co com gov net or org ',
'mz': ' ac co edu gov org ',
'na': ' co com ',
'nz': ' ac co cri geek gen govt health iwi maori mil net org parliament school ',
'pa': ' abo ac com edu gob ing med net nom org sld ',
'pt': ' com edu gov int net nome org publ ',
'py': ' com edu gov mil net org ',
'qa': ' com edu gov mil net org ',
're': ' asso com nom ',
'ru': ' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ',
'rw': ' ac co com edu gouv gov int mil net ',
'sa': ' com edu gov med net org pub sch ',
'sd': ' com edu gov info med net org tv ',
'se': ' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ',
'sg': ' com edu gov idn net org per ',
'sn': ' art com edu gouv org perso univ ',
'sy': ' com edu gov mil net news org ',
'th': ' ac co go in mi net or ',
'tj': ' ac biz co com edu go gov info int mil name net nic org test web ',
'tn': ' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ',
'tz': ' ac co go ne or ',
'ua': ' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ',
'ug': ' ac co go ne or org sc ',
'uk': ' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ',
'us': ' dni fed isa kids nsn ',
'uy': ' com edu gub mil net org ',
've': ' co com edu gob info mil net org web ',
'vi': ' co com k12 net org ',
'vn': ' ac biz com edu gov health info int name net org pro ',
'ye': ' co com gov ltd me net org plc ',
'yu': ' ac co edu gov org ',
'za': ' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ',
'zm': ' ac co com edu gov net org sch ',
// https://en.wikipedia.org/wiki/CentralNic#Second-level_domains
'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ',
'net': 'gb jp se uk ',
'org': 'ae',
'de': 'com '
},
// gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost
// in both performance and memory footprint. No initialization required.
// http://jsperf.com/uri-js-sld-regex-vs-binary-search/4
// Following methods use lastIndexOf() rather than array.split() in order
// to avoid any memory allocations.
has: function (domain) {
var tldOffset = domain.lastIndexOf('.');
if (tldOffset <= 0 || tldOffset >= domain.length - 1) {
return false;
}
var sldOffset = domain.lastIndexOf('.', tldOffset - 1);
if (sldOffset <= 0 || sldOffset >= tldOffset - 1) {
return false;
}
var sldList = SLD.list[domain.slice(tldOffset + 1)];
if (!sldList) {
return false;
}
return sldList.indexOf(' ' + domain.slice(sldOffset + 1, tldOffset) + ' ') >= 0;
},
is: function (domain) {
var tldOffset = domain.lastIndexOf('.');
if (tldOffset <= 0 || tldOffset >= domain.length - 1) {
return false;
}
var sldOffset = domain.lastIndexOf('.', tldOffset - 1);
if (sldOffset >= 0) {
return false;
}
var sldList = SLD.list[domain.slice(tldOffset + 1)];
if (!sldList) {
return false;
}
return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0;
},
get: function (domain) {
var tldOffset = domain.lastIndexOf('.');
if (tldOffset <= 0 || tldOffset >= domain.length - 1) {
return null;
}
var sldOffset = domain.lastIndexOf('.', tldOffset - 1);
if (sldOffset <= 0 || sldOffset >= tldOffset - 1) {
return null;
}
var sldList = SLD.list[domain.slice(tldOffset + 1)];
if (!sldList) {
return null;
}
if (sldList.indexOf(' ' + domain.slice(sldOffset + 1, tldOffset) + ' ') < 0) {
return null;
}
return domain.slice(sldOffset + 1);
},
noConflict: function () {
if (root.SecondLevelDomains === this) {
root.SecondLevelDomains = _SecondLevelDomains;
}
return this;
}
};
return SLD;
});
/***/ }),
/***/ 988:
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* URI.js - Mutating URLs
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
(function (root, factory) {
'use strict';
// https://github.com/umdjs/umd/blob/master/returnExports.js
if ( true && module.exports) {
// Node
module.exports = factory(__webpack_require__(562), __webpack_require__(939), __webpack_require__(338));
} else if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(562), __webpack_require__(939), __webpack_require__(338)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
})(this, function (punycode, IPv6, SLD, root) {
'use strict';
/*global location, escape, unescape */
// FIXME: v2.0.0 renamce non-camelCase properties to uppercase
/*jshint camelcase: false */
// save current URI variable, if any
var _URI = root && root.URI;
function URI(url, base) {
var _urlSupplied = arguments.length >= 1;
var _baseSupplied = arguments.length >= 2;
// Allow instantiation without the 'new' keyword
if (!(this instanceof URI)) {
if (_urlSupplied) {
if (_baseSupplied) {
return new URI(url, base);
}
return new URI(url);
}
return new URI();
}
if (url === undefined) {
if (_urlSupplied) {
throw new TypeError('undefined is not a valid argument for URI');
}
if (typeof location !== 'undefined') {
url = location.href + '';
} else {
url = '';
}
}
if (url === null) {
if (_urlSupplied) {
throw new TypeError('null is not a valid argument for URI');
}
}
this.href(url);
// resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor
if (base !== undefined) {
return this.absoluteTo(base);
}
return this;
}
function isInteger(value) {
return /^[0-9]+$/.test(value);
}
URI.version = '1.19.11';
var p = URI.prototype;
var hasOwn = Object.prototype.hasOwnProperty;
function escapeRegEx(string) {
// https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963
return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
function getType(value) {
// IE8 doesn't return [Object Undefined] but [Object Object] for undefined value
if (value === undefined) {
return 'Undefined';
}
return String(Object.prototype.toString.call(value)).slice(8, -1);
}
function isArray(obj) {
return getType(obj) === 'Array';
}
function filterArrayValues(data, value) {
var lookup = {};
var i, length;
if (getType(value) === 'RegExp') {
lookup = null;
} else if (isArray(value)) {
for (i = 0, length = value.length; i < length; i++) {
lookup[value[i]] = true;
}
} else {
lookup[value] = true;
}
for (i = 0, length = data.length; i < length; i++) {
/*jshint laxbreak: true */
var _match = lookup && lookup[data[i]] !== undefined || !lookup && value.test(data[i]);
/*jshint laxbreak: false */
if (_match) {
data.splice(i, 1);
length--;
i--;
}
}
return data;
}
function arrayContains(list, value) {
var i, length;
// value may be string, number, array, regexp
if (isArray(value)) {
// Note: this can be optimized to O(n) (instead of current O(m * n))
for (i = 0, length = value.length; i < length; i++) {
if (!arrayContains(list, value[i])) {
return false;
}
}
return true;
}
var _type = getType(value);
for (i = 0, length = list.length; i < length; i++) {
if (_type === 'RegExp') {
if (typeof list[i] === 'string' && list[i].match(value)) {
return true;
}
} else if (list[i] === value) {
return true;
}
}
return false;
}
function arraysEqual(one, two) {
if (!isArray(one) || !isArray(two)) {
return false;
}
// arrays can't be equal if they have different amount of content
if (one.length !== two.length) {
return false;
}
one.sort();
two.sort();
for (var i = 0, l = one.length; i < l; i++) {
if (one[i] !== two[i]) {
return false;
}
}
return true;
}
function trimSlashes(text) {
var trim_expression = /^\/+|\/+$/g;
return text.replace(trim_expression, '');
}
URI._parts = function () {
return {
protocol: null,
username: null,
password: null,
hostname: null,
urn: null,
port: null,
path: null,
query: null,
fragment: null,
// state
preventInvalidHostname: URI.preventInvalidHostname,
duplicateQueryParameters: URI.duplicateQueryParameters,
escapeQuerySpace: URI.escapeQuerySpace
};
};
// state: throw on invalid hostname
// see https://github.com/medialize/URI.js/pull/345
// and https://github.com/medialize/URI.js/issues/354
URI.preventInvalidHostname = false;
// state: allow duplicate query parameters (a=1&a=1)
URI.duplicateQueryParameters = false;
// state: replaces + with %20 (space in query strings)
URI.escapeQuerySpace = true;
// static properties
URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i;
URI.idn_expression = /[^a-z0-9\._-]/i;
URI.punycode_expression = /(xn--)/i;
// well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care?
URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
// credits to Rich Brown
// source: http://forums.intermapper.com/viewtopic.php?p=1096#1096
// specification: http://www.ietf.org/rfc/rfc4291.txt
URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
// expression used is "gruber revised" (@gruber v2) determined to be the
// best solution in a regex-golf we did a couple of ages ago at
// * http://mathiasbynens.be/demo/url-regex
// * http://rodneyrehm.de/t/url-regex.html
URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig;
URI.findUri = {
// valid "scheme://" or "www."
start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,
// everything up to the next whitespace
end: /[\s\r\n]|$/,
// trim trailing punctuation captured by end RegExp
trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/,
// balanced parens inclusion (), [], {}, <>
parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g
};
URI.leading_whitespace_expression = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
URI.ascii_tab_whitespace = /[\u0009\u000A\u000D]+/g;
// http://www.iana.org/assignments/uri-schemes.html
// http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports
URI.defaultPorts = {
http: '80',
https: '443',
ftp: '21',
gopher: '70',
ws: '80',
wss: '443'
};
// list of protocols which always require a hostname
URI.hostProtocols = ['http', 'https'];
// allowed hostname characters according to RFC 3986
// ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded
// I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _
URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/;
// map DOM Elements to their URI attribute
URI.domAttributes = {
'a': 'href',
'blockquote': 'cite',
'link': 'href',
'base': 'href',
'script': 'src',
'form': 'action',
'img': 'src',
'area': 'href',
'iframe': 'src',
'embed': 'src',
'source': 'src',
'track': 'src',
'input': 'src',
// but only if type="image"
'audio': 'src',
'video': 'src'
};
URI.getDomAttribute = function (node) {
if (!node || !node.nodeName) {
return undefined;
}
var nodeName = node.nodeName.toLowerCase();
// <input> should only expose src for type="image"
if (nodeName === 'input' && node.type !== 'image') {
return undefined;
}
return URI.domAttributes[nodeName];
};
function escapeForDumbFirefox36(value) {
// https://github.com/medialize/URI.js/issues/91
return escape(value);
}
// encoding / decoding according to RFC3986
function strictEncodeURIComponent(string) {
// see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
return encodeURIComponent(string).replace(/[!'()*]/g, escapeForDumbFirefox36).replace(/\*/g, '%2A');
}
URI.encode = strictEncodeURIComponent;
URI.decode = decodeURIComponent;
URI.iso8859 = function () {
URI.encode = escape;
URI.decode = unescape;
};
URI.unicode = function () {
URI.encode = strictEncodeURIComponent;
URI.decode = decodeURIComponent;
};
URI.characters = {
pathname: {
encode: {
// RFC3986 2.1: For consistency, URI producers and normalizers should
// use uppercase hexadecimal digits for all percent-encodings.
expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig,
map: {
// -._~!'()*
'%24': '$',
'%26': '&',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '=',
'%3A': ':',
'%40': '@'
}
},
decode: {
expression: /[\/\?#]/g,
map: {
'/': '%2F',
'?': '%3F',
'#': '%23'
}
}
},
reserved: {
encode: {
// RFC3986 2.1: For consistency, URI producers and normalizers should
// use uppercase hexadecimal digits for all percent-encodings.
expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,
map: {
// gen-delims
'%3A': ':',
'%2F': '/',
'%3F': '?',
'%23': '#',
'%5B': '[',
'%5D': ']',
'%40': '@',
// sub-delims
'%21': '!',
'%24': '$',
'%26': '&',
'%27': '\'',
'%28': '(',
'%29': ')',
'%2A': '*',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '='
}
}
},
urnpath: {
// The characters under `encode` are the characters called out by RFC 2141 as being acceptable
// for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but
// these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also
// note that the colon character is not featured in the encoding map; this is because URI.js
// gives the colons in URNs semantic meaning as the delimiters of path segements, and so it
// should not appear unencoded in a segment itself.
// See also the note above about RFC3986 and capitalalized hex digits.
encode: {
expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,
map: {
'%21': '!',
'%24': '$',
'%27': '\'',
'%28': '(',
'%29': ')',
'%2A': '*',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '=',
'%40': '@'
}
},
// These characters are the characters called out by RFC2141 as "reserved" characters that
// should never appear in a URN, plus the colon character (see note above).
decode: {
expression: /[\/\?#:]/g,
map: {
'/': '%2F',
'?': '%3F',
'#': '%23',
':': '%3A'
}
}
}
};
URI.encodeQuery = function (string, escapeQuerySpace) {
var escaped = URI.encode(string + '');
if (escapeQuerySpace === undefined) {
escapeQuerySpace = URI.escapeQuerySpace;
}
return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped;
};
URI.decodeQuery = function (string, escapeQuerySpace) {
string += '';
if (escapeQuerySpace === undefined) {
escapeQuerySpace = URI.escapeQuerySpace;
}
try {
return URI.decode(escapeQuerySpace ? string.replace(/\+/g, '%20') : string);
} catch (e) {
// we're not going to mess with weird encodings,
// give up and return the undecoded original string
// see https://github.com/medialize/URI.js/issues/87
// see https://github.com/medialize/URI.js/issues/92
return string;
}
};
// generate encode/decode path functions
var _parts = {
'encode': 'encode',
'decode': 'decode'
};
var _part;
var generateAccessor = function (_group, _part) {
return function (string) {
try {
return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function (c) {
return URI.characters[_group][_part].map[c];
});
} catch (e) {
// we're not going to mess with weird encodings,
// give up and return the undecoded original string
// see https://github.com/medialize/URI.js/issues/87
// see https://github.com/medialize/URI.js/issues/92
return string;
}
};
};
for (_part in _parts) {
URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]);
URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]);
}
var generateSegmentedPathFunction = function (_sep, _codingFuncName, _innerCodingFuncName) {
return function (string) {
// Why pass in names of functions, rather than the function objects themselves? The
// definitions of some functions (but in particular, URI.decode) will occasionally change due
// to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure
// that the functions we use here are "fresh".
var actualCodingFunc;
if (!_innerCodingFuncName) {
actualCodingFunc = URI[_codingFuncName];
} else {
actualCodingFunc = function (string) {
return URI[_codingFuncName](URI[_innerCodingFuncName](string));
};
}
var segments = (string + '').split(_sep);
for (var i = 0, length = segments.length; i < length; i++) {
segments[i] = actualCodingFunc(segments[i]);
}
return segments.join(_sep);
};
};
// This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions.
URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment');
URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment');
URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode');
URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode');
URI.encodeReserved = generateAccessor('reserved', 'encode');
URI.parse = function (string, parts) {
var pos;
if (!parts) {
parts = {
preventInvalidHostname: URI.preventInvalidHostname
};
}
string = string.replace(URI.leading_whitespace_expression, '');
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
string = string.replace(URI.ascii_tab_whitespace, '');
// [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment]
// extract fragment
pos = string.indexOf('#');
if (pos > -1) {
// escaping?
parts.fragment = string.substring(pos + 1) || null;
string = string.substring(0, pos);
}
// extract query
pos = string.indexOf('?');
if (pos > -1) {
// escaping?
parts.query = string.substring(pos + 1) || null;
string = string.substring(0, pos);
}
// slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws)
string = string.replace(/^(https?|ftp|wss?)?:+[/\\]*/i, '$1://');
// slashes and backslashes have lost all meaning for scheme relative URLs
string = string.replace(/^[/\\]{2,}/i, '//');
// extract protocol
if (string.substring(0, 2) === '//') {
// relative-scheme
parts.protocol = null;
string = string.substring(2);
// extract "user:pass@host:port"
string = URI.parseAuthority(string, parts);
} else {
pos = string.indexOf(':');
if (pos > -1) {
parts.protocol = string.substring(0, pos) || null;
if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {
// : may be within the path
parts.protocol = undefined;
} else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') {
string = string.substring(pos + 3);
// extract "user:pass@host:port"
string = URI.parseAuthority(string, parts);
} else {
string = string.substring(pos + 1);
parts.urn = true;
}
}
}
// what's left must be the path
parts.path = string;
// and we're done
return parts;
};
URI.parseHost = function (string, parts) {
if (!string) {
string = '';
}
// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124
// See: https://code.google.com/p/chromium/issues/detail?id=25916
// https://github.com/medialize/URI.js/pull/233
string = string.replace(/\\/g, '/');
// extract host:port
var pos = string.indexOf('/');
var bracketPos;
var t;
if (pos === -1) {
pos = string.length;
}
if (string.charAt(0) === '[') {
// IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6
// I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts
// IPv6+port in the format [2001:db8::1]:80 (for the time being)
bracketPos = string.indexOf(']');
parts.hostname = string.substring(1, bracketPos) || null;
parts.port = string.substring(bracketPos + 2, pos) || null;
if (parts.port === '/') {
parts.port = null;
}
} else {
var firstColon = string.indexOf(':');
var firstSlash = string.indexOf('/');
var nextColon = string.indexOf(':', firstColon + 1);
if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) {
// IPv6 host contains multiple colons - but no port
// this notation is actually not allowed by RFC 3986, but we're a liberal parser
parts.hostname = string.substring(0, pos) || null;
parts.port = null;
} else {
t = string.substring(0, pos).split(':');
parts.hostname = t[0] || null;
parts.port = t[1] || null;
}
}
if (parts.hostname && string.substring(pos).charAt(0) !== '/') {
pos++;
string = '/' + string;
}
if (parts.preventInvalidHostname) {
URI.ensureValidHostname(parts.hostname, parts.protocol);
}
if (parts.port) {
URI.ensureValidPort(parts.port);
}
return string.substring(pos) || '/';
};
URI.parseAuthority = function (string, parts) {
string = URI.parseUserinfo(string, parts);
return URI.parseHost(string, parts);
};
URI.parseUserinfo = function (string, parts) {
// extract username:password
var _string = string;
var firstBackSlash = string.indexOf('\\');
if (firstBackSlash !== -1) {
string = string.replace(/\\/g, '/');
}
var firstSlash = string.indexOf('/');
var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1);
var t;
// authority@ must come before /path or \path
if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) {
t = string.substring(0, pos).split(':');
parts.username = t[0] ? URI.decode(t[0]) : null;
t.shift();
parts.password = t[0] ? URI.decode(t.join(':')) : null;
string = _string.substring(pos + 1);
} else {
parts.username = null;
parts.password = null;
}
return string;
};
URI.parseQuery = function (string, escapeQuerySpace) {
if (!string) {
return {};
}
// throw out the funky business - "?"[name"="value"&"]+
string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, '');
if (!string) {
return {};
}
var items = {};
var splits = string.split('&');
var length = splits.length;
var v, name, value;
for (var i = 0; i < length; i++) {
v = splits[i].split('=');
name = URI.decodeQuery(v.shift(), escapeQuerySpace);
// no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters
value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null;
if (name === '__proto__') {
// ignore attempt at exploiting JavaScript internals
continue;
} else if (hasOwn.call(items, name)) {
if (typeof items[name] === 'string' || items[name] === null) {
items[name] = [items[name]];
}
items[name].push(value);
} else {
items[name] = value;
}
}
return items;
};
URI.build = function (parts) {
var t = '';
var requireAbsolutePath = false;
if (parts.protocol) {
t += parts.protocol + ':';
}
if (!parts.urn && (t || parts.hostname)) {
t += '//';
requireAbsolutePath = true;
}
t += URI.buildAuthority(parts) || '';
if (typeof parts.path === 'string') {
if (parts.path.charAt(0) !== '/' && requireAbsolutePath) {
t += '/';
}
t += parts.path;
}
if (typeof parts.query === 'string' && parts.query) {
t += '?' + parts.query;
}
if (typeof parts.fragment === 'string' && parts.fragment) {
t += '#' + parts.fragment;
}
return t;
};
URI.buildHost = function (parts) {
var t = '';
if (!parts.hostname) {
return '';
} else if (URI.ip6_expression.test(parts.hostname)) {
t += '[' + parts.hostname + ']';
} else {
t += parts.hostname;
}
if (parts.port) {
t += ':' + parts.port;
}
return t;
};
URI.buildAuthority = function (parts) {
return URI.buildUserinfo(parts) + URI.buildHost(parts);
};
URI.buildUserinfo = function (parts) {
var t = '';
if (parts.username) {
t += URI.encode(parts.username);
}
if (parts.password) {
t += ':' + URI.encode(parts.password);
}
if (t) {
t += '@';
}
return t;
};
URI.buildQuery = function (data, duplicateQueryParameters, escapeQuerySpace) {
// according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html
// being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed
// the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax!
// URI.js treats the query string as being application/x-www-form-urlencoded
// see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type
var t = '';
var unique, key, i, length;
for (key in data) {
if (key === '__proto__') {
// ignore attempt at exploiting JavaScript internals
continue;
} else if (hasOwn.call(data, key)) {
if (isArray(data[key])) {
unique = {};
for (i = 0, length = data[key].length; i < length; i++) {
if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) {
t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace);
if (duplicateQueryParameters !== true) {
unique[data[key][i] + ''] = true;
}
}
}
} else if (data[key] !== undefined) {
t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace);
}
}
}
return t.substring(1);
};
URI.buildQueryParameter = function (name, value, escapeQuerySpace) {
// http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded
// don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization
return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : '');
};
URI.addQuery = function (data, name, value) {
if (typeof name === 'object') {
for (var key in name) {
if (hasOwn.call(name, key)) {
URI.addQuery(data, key, name[key]);
}
}
} else if (typeof name === 'string') {
if (data[name] === undefined) {
data[name] = value;
return;
} else if (typeof data[name] === 'string') {
data[name] = [data[name]];
}
if (!isArray(value)) {
value = [value];
}
data[name] = (data[name] || []).concat(value);
} else {
throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
}
};
URI.setQuery = function (data, name, value) {
if (typeof name === 'object') {
for (var key in name) {
if (hasOwn.call(name, key)) {
URI.setQuery(data, key, name[key]);
}
}
} else if (typeof name === 'string') {
data[name] = value === undefined ? null : value;
} else {
throw new TypeError('URI.setQuery() accepts an object, string as the name parameter');
}
};
URI.removeQuery = function (data, name, value) {
var i, length, key;
if (isArray(name)) {
for (i = 0, length = name.length; i < length; i++) {
data[name[i]] = undefined;
}
} else if (getType(name) === 'RegExp') {
for (key in data) {
if (name.test(key)) {
data[key] = undefined;
}
}
} else if (typeof name === 'object') {
for (key in name) {
if (hasOwn.call(name, key)) {
URI.removeQuery(data, key, name[key]);
}
}
} else if (typeof name === 'string') {
if (value !== undefined) {
if (getType(value) === 'RegExp') {
if (!isArray(data[name]) && value.test(data[name])) {
data[name] = undefined;
} else {
data[name] = filterArrayValues(data[name], value);
}
} else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) {
data[name] = undefined;
} else if (isArray(data[name])) {
data[name] = filterArrayValues(data[name], value);
}
} else {
data[name] = undefined;
}
} else {
throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter');
}
};
URI.hasQuery = function (data, name, value, withinArray) {
switch (getType(name)) {
case 'String':
// Nothing to do here
break;
case 'RegExp':
for (var key in data) {
if (hasOwn.call(data, key)) {
if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) {
return true;
}
}
}
return false;
case 'Object':
for (var _key in name) {
if (hasOwn.call(name, _key)) {
if (!URI.hasQuery(data, _key, name[_key])) {
return false;
}
}
}
return true;
default:
throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter');
}
switch (getType(value)) {
case 'Undefined':
// true if exists (but may be empty)
return name in data;
// data[name] !== undefined;
case 'Boolean':
// true if exists and non-empty
var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]);
return value === _booly;
case 'Function':
// allow complex comparison
return !!value(data[name], name, data);
case 'Array':
if (!isArray(data[name])) {
return false;
}
var op = withinArray ? arrayContains : arraysEqual;
return op(data[name], value);
case 'RegExp':
if (!isArray(data[name])) {
return Boolean(data[name] && data[name].match(value));
}
if (!withinArray) {
return false;
}
return arrayContains(data[name], value);
case 'Number':
value = String(value);
/* falls through */
case 'String':
if (!isArray(data[name])) {
return data[name] === value;
}
if (!withinArray) {
return false;
}
return arrayContains(data[name], value);
default:
throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter');
}
};
URI.joinPaths = function () {
var input = [];
var segments = [];
var nonEmptySegments = 0;
for (var i = 0; i < arguments.length; i++) {
var url = new URI(arguments[i]);
input.push(url);
var _segments = url.segment();
for (var s = 0; s < _segments.length; s++) {
if (typeof _segments[s] === 'string') {
segments.push(_segments[s]);
}
if (_segments[s]) {
nonEmptySegments++;
}
}
}
if (!segments.length || !nonEmptySegments) {
return new URI('');
}
var uri = new URI('').segment(segments);
if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') {
uri.path('/' + uri.path());
}
return uri.normalize();
};
URI.commonPath = function (one, two) {
var length = Math.min(one.length, two.length);
var pos;
// find first non-matching character
for (pos = 0; pos < length; pos++) {
if (one.charAt(pos) !== two.charAt(pos)) {
pos--;
break;
}
}
if (pos < 1) {
return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : '';
}
// revert to last /
if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') {
pos = one.substring(0, pos).lastIndexOf('/');
}
return one.substring(0, pos + 1);
};
URI.withinString = function (string, callback, options) {
options || (options = {});
var _start = options.start || URI.findUri.start;
var _end = options.end || URI.findUri.end;
var _trim = options.trim || URI.findUri.trim;
var _parens = options.parens || URI.findUri.parens;
var _attributeOpen = /[a-z0-9-]=["']?$/i;
_start.lastIndex = 0;
while (true) {
var match = _start.exec(string);
if (!match) {
break;
}
var start = match.index;
if (options.ignoreHtml) {
// attribut(e=["']?$)
var attributeOpen = string.slice(Math.max(start - 3, 0), start);
if (attributeOpen && _attributeOpen.test(attributeOpen)) {
continue;
}
}
var end = start + string.slice(start).search(_end);
var slice = string.slice(start, end);
// make sure we include well balanced parens
var parensEnd = -1;
while (true) {
var parensMatch = _parens.exec(slice);
if (!parensMatch) {
break;
}
var parensMatchEnd = parensMatch.index + parensMatch[0].length;
parensEnd = Math.max(parensEnd, parensMatchEnd);
}
if (parensEnd > -1) {
slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, '');
} else {
slice = slice.replace(_trim, '');
}
if (slice.length <= match[0].length) {
// the extract only contains the starting marker of a URI,
// e.g. "www" or "http://"
continue;
}
if (options.ignore && options.ignore.test(slice)) {
continue;
}
end = start + slice.length;
var result = callback(slice, start, end, string);
if (result === undefined) {
_start.lastIndex = end;
continue;
}
result = String(result);
string = string.slice(0, start) + result + string.slice(end);
_start.lastIndex = start + result.length;
}
_start.lastIndex = 0;
return string;
};
URI.ensureValidHostname = function (v, protocol) {
// Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986)
// they are not part of DNS and therefore ignored by URI.js
var hasHostname = !!v; // not null and not an empty string
var hasProtocol = !!protocol;
var rejectEmptyHostname = false;
if (hasProtocol) {
rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol);
}
if (rejectEmptyHostname && !hasHostname) {
throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol);
} else if (v && v.match(URI.invalid_hostname_characters)) {
// test punycode
if (!punycode) {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');
}
if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]');
}
}
};
URI.ensureValidPort = function (v) {
if (!v) {
return;
}
var port = Number(v);
if (isInteger(port) && port > 0 && port < 65536) {
return;
}
throw new TypeError('Port "' + v + '" is not a valid port');
};
// noConflict
URI.noConflict = function (removeAll) {
if (removeAll) {
var unconflicted = {
URI: this.noConflict()
};
if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') {
unconflicted.URITemplate = root.URITemplate.noConflict();
}
if (root.IPv6 && typeof root.IPv6.noConflict === 'function') {
unconflicted.IPv6 = root.IPv6.noConflict();
}
if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') {
unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict();
}
return unconflicted;
} else if (root.URI === this) {
root.URI = _URI;
}
return this;
};
p.build = function (deferBuild) {
if (deferBuild === true) {
this._deferred_build = true;
} else if (deferBuild === undefined || this._deferred_build) {
this._string = URI.build(this._parts);
this._deferred_build = false;
}
return this;
};
p.clone = function () {
return new URI(this);
};
p.valueOf = p.toString = function () {
return this.build(false)._string;
};
function generateSimpleAccessor(_part) {
return function (v, build) {
if (v === undefined) {
return this._parts[_part] || '';
} else {
this._parts[_part] = v || null;
this.build(!build);
return this;
}
};
}
function generatePrefixAccessor(_part, _key) {
return function (v, build) {
if (v === undefined) {
return this._parts[_part] || '';
} else {
if (v !== null) {
v = v + '';
if (v.charAt(0) === _key) {
v = v.substring(1);
}
}
this._parts[_part] = v;
this.build(!build);
return this;
}
};
}
p.protocol = generateSimpleAccessor('protocol');
p.username = generateSimpleAccessor('username');
p.password = generateSimpleAccessor('password');
p.hostname = generateSimpleAccessor('hostname');
p.port = generateSimpleAccessor('port');
p.query = generatePrefixAccessor('query', '?');
p.fragment = generatePrefixAccessor('fragment', '#');
p.search = function (v, build) {
var t = this.query(v, build);
return typeof t === 'string' && t.length ? '?' + t : t;
};
p.hash = function (v, build) {
var t = this.fragment(v, build);
return typeof t === 'string' && t.length ? '#' + t : t;
};
p.pathname = function (v, build) {
if (v === undefined || v === true) {
var res = this._parts.path || (this._parts.hostname ? '/' : '');
return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res;
} else {
if (this._parts.urn) {
this._parts.path = v ? URI.recodeUrnPath(v) : '';
} else {
this._parts.path = v ? URI.recodePath(v) : '/';
}
this.build(!build);
return this;
}
};
p.path = p.pathname;
p.href = function (href, build) {
var key;
if (href === undefined) {
return this.toString();
}
this._string = '';
this._parts = URI._parts();
var _URI = href instanceof URI;
var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname);
if (href.nodeName) {
var attribute = URI.getDomAttribute(href);
href = href[attribute] || '';
_object = false;
}
// window.location is reported to be an object, but it's not the sort
// of object we're looking for:
// * location.protocol ends with a colon
// * location.query != object.search
// * location.hash != object.fragment
// simply serializing the unknown object should do the trick
// (for location, not for everything...)
if (!_URI && _object && href.pathname !== undefined) {
href = href.toString();
}
if (typeof href === 'string' || href instanceof String) {
this._parts = URI.parse(String(href), this._parts);
} else if (_URI || _object) {
var src = _URI ? href._parts : href;
for (key in src) {
if (key === 'query') {
continue;
}
if (hasOwn.call(this._parts, key)) {
this._parts[key] = src[key];
}
}
if (src.query) {
this.query(src.query, false);
}
} else {
throw new TypeError('invalid input');
}
this.build(!build);
return this;
};
// identification accessors
p.is = function (what) {
var ip = false;
var ip4 = false;
var ip6 = false;
var name = false;
var sld = false;
var idn = false;
var punycode = false;
var relative = !this._parts.urn;
if (this._parts.hostname) {
relative = false;
ip4 = URI.ip4_expression.test(this._parts.hostname);
ip6 = URI.ip6_expression.test(this._parts.hostname);
ip = ip4 || ip6;
name = !ip;
sld = name && SLD && SLD.has(this._parts.hostname);
idn = name && URI.idn_expression.test(this._parts.hostname);
punycode = name && URI.punycode_expression.test(this._parts.hostname);
}
switch (what.toLowerCase()) {
case 'relative':
return relative;
case 'absolute':
return !relative;
// hostname identification
case 'domain':
case 'name':
return name;
case 'sld':
return sld;
case 'ip':
return ip;
case 'ip4':
case 'ipv4':
case 'inet4':
return ip4;
case 'ip6':
case 'ipv6':
case 'inet6':
return ip6;
case 'idn':
return idn;
case 'url':
return !this._parts.urn;
case 'urn':
return !!this._parts.urn;
case 'punycode':
return punycode;
}
return null;
};
// component specific input validation
var _protocol = p.protocol;
var _port = p.port;
var _hostname = p.hostname;
p.protocol = function (v, build) {
if (v) {
// accept trailing ://
v = v.replace(/:(\/\/)?$/, '');
if (!v.match(URI.protocol_expression)) {
throw new TypeError('Protocol "' + v + '" contains characters other than [A-Z0-9.+-] or doesn\'t start with [A-Z]');
}
}
return _protocol.call(this, v, build);
};
p.scheme = p.protocol;
p.port = function (v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v !== undefined) {
if (v === 0) {
v = null;
}
if (v) {
v += '';
if (v.charAt(0) === ':') {
v = v.substring(1);
}
URI.ensureValidPort(v);
}
}
return _port.call(this, v, build);
};
p.hostname = function (v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v !== undefined) {
var x = {
preventInvalidHostname: this._parts.preventInvalidHostname
};
var res = URI.parseHost(v, x);
if (res !== '/') {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
}
v = x.hostname;
if (this._parts.preventInvalidHostname) {
URI.ensureValidHostname(v, this._parts.protocol);
}
}
return _hostname.call(this, v, build);
};
// compound accessors
p.origin = function (v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
var protocol = this.protocol();
var authority = this.authority();
if (!authority) {
return '';
}
return (protocol ? protocol + '://' : '') + this.authority();
} else {
var origin = URI(v);
this.protocol(origin.protocol()).authority(origin.authority()).build(!build);
return this;
}
};
p.host = function (v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
return this._parts.hostname ? URI.buildHost(this._parts) : '';
} else {
var res = URI.parseHost(v, this._parts);
if (res !== '/') {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
}
this.build(!build);
return this;
}
};
p.authority = function (v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
return this._parts.hostname ? URI.buildAuthority(this._parts) : '';
} else {
var res = URI.parseAuthority(v, this._parts);
if (res !== '/') {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
}
this.build(!build);
return this;
}
};
p.userinfo = function (v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
var t = URI.buildUserinfo(this._parts);
return t ? t.substring(0, t.length - 1) : t;
} else {
if (v[v.length - 1] !== '@') {
v += '@';
}
URI.parseUserinfo(v, this._parts);
this.build(!build);
return this;
}
};
p.resource = function (v, build) {
var parts;
if (v === undefined) {
return this.path() + this.search() + this.hash();
}
parts = URI.parse(v);
this._parts.path = parts.path;
this._parts.query = parts.query;
this._parts.fragment = parts.fragment;
this.build(!build);
return this;
};
// fraction accessors
p.subdomain = function (v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
// convenience, return "www" from "www.example.org"
if (v === undefined) {
if (!this._parts.hostname || this.is('IP')) {
return '';
}
// grab domain and add another segment
var end = this._parts.hostname.length - this.domain().length - 1;
return this._parts.hostname.substring(0, end) || '';
} else {
var e = this._parts.hostname.length - this.domain().length;
var sub = this._parts.hostname.substring(0, e);
var replace = new RegExp('^' + escapeRegEx(sub));
if (v && v.charAt(v.length - 1) !== '.') {
v += '.';
}
if (v.indexOf(':') !== -1) {
throw new TypeError('Domains cannot contain colons');
}
if (v) {
URI.ensureValidHostname(v, this._parts.protocol);
}
this._parts.hostname = this._parts.hostname.replace(replace, v);
this.build(!build);
return this;
}
};
p.domain = function (v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (typeof v === 'boolean') {
build = v;
v = undefined;
}
// convenience, return "example.org" from "www.example.org"
if (v === undefined) {
if (!this._parts.hostname || this.is('IP')) {
return '';
}
// if hostname consists of 1 or 2 segments, it must be the domain
var t = this._parts.hostname.match(/\./g);
if (t && t.length < 2) {
return this._parts.hostname;
}
// grab tld and add another segment
var end = this._parts.hostname.length - this.tld(build).length - 1;
end = this._parts.hostname.lastIndexOf('.', end - 1) + 1;
return this._parts.hostname.substring(end) || '';
} else {
if (!v) {
throw new TypeError('cannot set domain empty');
}
if (v.indexOf(':') !== -1) {
throw new TypeError('Domains cannot contain colons');
}
URI.ensureValidHostname(v, this._parts.protocol);
if (!this._parts.hostname || this.is('IP')) {
this._parts.hostname = v;
} else {
var replace = new RegExp(escapeRegEx(this.domain()) + '$');
this._parts.hostname = this._parts.hostname.replace(replace, v);
}
this.build(!build);
return this;
}
};
p.tld = function (v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (typeof v === 'boolean') {
build = v;
v = undefined;
}
// return "org" from "www.example.org"
if (v === undefined) {
if (!this._parts.hostname || this.is('IP')) {
return '';
}
var pos = this._parts.hostname.lastIndexOf('.');
var tld = this._parts.hostname.substring(pos + 1);
if (build !== true && SLD && SLD.list[tld.toLowerCase()]) {
return SLD.get(this._parts.hostname) || tld;
}
return tld;
} else {
var replace;
if (!v) {
throw new TypeError('cannot set TLD empty');
} else if (v.match(/[^a-zA-Z0-9-]/)) {
if (SLD && SLD.is(v)) {
replace = new RegExp(escapeRegEx(this.tld()) + '$');
this._parts.hostname = this._parts.hostname.replace(replace, v);
} else {
throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]');
}
} else if (!this._parts.hostname || this.is('IP')) {
throw new ReferenceError('cannot set TLD on non-domain host');
} else {
replace = new RegExp(escapeRegEx(this.tld()) + '$');
this._parts.hostname = this._parts.hostname.replace(replace, v);
}
this.build(!build);
return this;
}
};
p.directory = function (v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined || v === true) {
if (!this._parts.path && !this._parts.hostname) {
return '';
}
if (this._parts.path === '/') {
return '/';
}
var end = this._parts.path.length - this.filename().length - 1;
var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : '');
return v ? URI.decodePath(res) : res;
} else {
var e = this._parts.path.length - this.filename().length;
var directory = this._parts.path.substring(0, e);
var replace = new RegExp('^' + escapeRegEx(directory));
// fully qualifier directories begin with a slash
if (!this.is('relative')) {
if (!v) {
v = '/';
}
if (v.charAt(0) !== '/') {
v = '/' + v;
}
}
// directories always end with a slash
if (v && v.charAt(v.length - 1) !== '/') {
v += '/';
}
v = URI.recodePath(v);
this._parts.path = this._parts.path.replace(replace, v);
this.build(!build);
return this;
}
};
p.filename = function (v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (typeof v !== 'string') {
if (!this._parts.path || this._parts.path === '/') {
return '';
}
var pos = this._parts.path.lastIndexOf('/');
var res = this._parts.path.substring(pos + 1);
return v ? URI.decodePathSegment(res) : res;
} else {
var mutatedDirectory = false;
if (v.charAt(0) === '/') {
v = v.substring(1);
}
if (v.match(/\.?\//)) {
mutatedDirectory = true;
}
var replace = new RegExp(escapeRegEx(this.filename()) + '$');
v = URI.recodePath(v);
this._parts.path = this._parts.path.replace(replace, v);
if (mutatedDirectory) {
this.normalizePath(build);
} else {
this.build(!build);
}
return this;
}
};
p.suffix = function (v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined || v === true) {
if (!this._parts.path || this._parts.path === '/') {
return '';
}
var filename = this.filename();
var pos = filename.lastIndexOf('.');
var s, res;
if (pos === -1) {
return '';
}
// suffix may only contain alnum characters (yup, I made this up.)
s = filename.substring(pos + 1);
res = /^[a-z0-9%]+$/i.test(s) ? s : '';
return v ? URI.decodePathSegment(res) : res;
} else {
if (v.charAt(0) === '.') {
v = v.substring(1);
}
var suffix = this.suffix();
var replace;
if (!suffix) {
if (!v) {
return this;
}
this._parts.path += '.' + URI.recodePath(v);
} else if (!v) {
replace = new RegExp(escapeRegEx('.' + suffix) + '$');
} else {
replace = new RegExp(escapeRegEx(suffix) + '$');
}
if (replace) {
v = URI.recodePath(v);
this._parts.path = this._parts.path.replace(replace, v);
}
this.build(!build);
return this;
}
};
p.segment = function (segment, v, build) {
var separator = this._parts.urn ? ':' : '/';
var path = this.path();
var absolute = path.substring(0, 1) === '/';
var segments = path.split(separator);
if (segment !== undefined && typeof segment !== 'number') {
build = v;
v = segment;
segment = undefined;
}
if (segment !== undefined && typeof segment !== 'number') {
throw new Error('Bad segment "' + segment + '", must be 0-based integer');
}
if (absolute) {
segments.shift();
}
if (segment < 0) {
// allow negative indexes to address from the end
segment = Math.max(segments.length + segment, 0);
}
if (v === undefined) {
/*jshint laxbreak: true */
return segment === undefined ? segments : segments[segment];
/*jshint laxbreak: false */
} else if (segment === null || segments[segment] === undefined) {
if (isArray(v)) {
segments = [];
// collapse empty elements within array
for (var i = 0, l = v.length; i < l; i++) {
if (!v[i].length && (!segments.length || !segments[segments.length - 1].length)) {
continue;
}
if (segments.length && !segments[segments.length - 1].length) {
segments.pop();
}
segments.push(trimSlashes(v[i]));
}
} else if (v || typeof v === 'string') {
v = trimSlashes(v);
if (segments[segments.length - 1] === '') {
// empty trailing elements have to be overwritten
// to prevent results such as /foo//bar
segments[segments.length - 1] = v;
} else {
segments.push(v);
}
}
} else {
if (v) {
segments[segment] = trimSlashes(v);
} else {
segments.splice(segment, 1);
}
}
if (absolute) {
segments.unshift('');
}
return this.path(segments.join(separator), build);
};
p.segmentCoded = function (segment, v, build) {
var segments, i, l;
if (typeof segment !== 'number') {
build = v;
v = segment;
segment = undefined;
}
if (v === undefined) {
segments = this.segment(segment, v, build);
if (!isArray(segments)) {
segments = segments !== undefined ? URI.decode(segments) : undefined;
} else {
for (i = 0, l = segments.length; i < l; i++) {
segments[i] = URI.decode(segments[i]);
}
}
return segments;
}
if (!isArray(v)) {
v = typeof v === 'string' || v instanceof String ? URI.encode(v) : v;
} else {
for (i = 0, l = v.length; i < l; i++) {
v[i] = URI.encode(v[i]);
}
}
return this.segment(segment, v, build);
};
// mutating query string
var q = p.query;
p.query = function (v, build) {
if (v === true) {
return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
} else if (typeof v === 'function') {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
var result = v.call(this, data);
this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
this.build(!build);
return this;
} else if (v !== undefined && typeof v !== 'string') {
this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
this.build(!build);
return this;
} else {
return q.call(this, v, build);
}
};
p.setQuery = function (name, value, build) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
if (typeof name === 'string' || name instanceof String) {
data[name] = value !== undefined ? value : null;
} else if (typeof name === 'object') {
for (var key in name) {
if (hasOwn.call(name, key)) {
data[key] = name[key];
}
}
} else {
throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
}
this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
if (typeof name !== 'string') {
build = value;
}
this.build(!build);
return this;
};
p.addQuery = function (name, value, build) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
URI.addQuery(data, name, value === undefined ? null : value);
this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
if (typeof name !== 'string') {
build = value;
}
this.build(!build);
return this;
};
p.removeQuery = function (name, value, build) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
URI.removeQuery(data, name, value);
this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
if (typeof name !== 'string') {
build = value;
}
this.build(!build);
return this;
};
p.hasQuery = function (name, value, withinArray) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
return URI.hasQuery(data, name, value, withinArray);
};
p.setSearch = p.setQuery;
p.addSearch = p.addQuery;
p.removeSearch = p.removeQuery;
p.hasSearch = p.hasQuery;
// sanitizing URLs
p.normalize = function () {
if (this._parts.urn) {
return this.normalizeProtocol(false).normalizePath(false).normalizeQuery(false).normalizeFragment(false).build();
}
return this.normalizeProtocol(false).normalizeHostname(false).normalizePort(false).normalizePath(false).normalizeQuery(false).normalizeFragment(false).build();
};
p.normalizeProtocol = function (build) {
if (typeof this._parts.protocol === 'string') {
this._parts.protocol = this._parts.protocol.toLowerCase();
this.build(!build);
}
return this;
};
p.normalizeHostname = function (build) {
if (this._parts.hostname) {
if (this.is('IDN') && punycode) {
this._parts.hostname = punycode.toASCII(this._parts.hostname);
} else if (this.is('IPv6') && IPv6) {
this._parts.hostname = IPv6.best(this._parts.hostname);
}
this._parts.hostname = this._parts.hostname.toLowerCase();
this.build(!build);
}
return this;
};
p.normalizePort = function (build) {
// remove port of it's the protocol's default
if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) {
this._parts.port = null;
this.build(!build);
}
return this;
};
p.normalizePath = function (build) {
var _path = this._parts.path;
if (!_path) {
return this;
}
if (this._parts.urn) {
this._parts.path = URI.recodeUrnPath(this._parts.path);
this.build(!build);
return this;
}
if (this._parts.path === '/') {
return this;
}
_path = URI.recodePath(_path);
var _was_relative;
var _leadingParents = '';
var _parent, _pos;
// handle relative paths
if (_path.charAt(0) !== '/') {
_was_relative = true;
_path = '/' + _path;
}
// handle relative files (as opposed to directories)
if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') {
_path += '/';
}
// resolve simples
_path = _path.replace(/(\/(\.\/)+)|(\/\.$)/g, '/').replace(/\/{2,}/g, '/');
// remember leading parents
if (_was_relative) {
_leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || '';
if (_leadingParents) {
_leadingParents = _leadingParents[0];
}
}
// resolve parents
while (true) {
_parent = _path.search(/\/\.\.(\/|$)/);
if (_parent === -1) {
// no more ../ to resolve
break;
} else if (_parent === 0) {
// top level cannot be relative, skip it
_path = _path.substring(3);
continue;
}
_pos = _path.substring(0, _parent).lastIndexOf('/');
if (_pos === -1) {
_pos = _parent;
}
_path = _path.substring(0, _pos) + _path.substring(_parent + 3);
}
// revert to relative
if (_was_relative && this.is('relative')) {
_path = _leadingParents + _path.substring(1);
}
this._parts.path = _path;
this.build(!build);
return this;
};
p.normalizePathname = p.normalizePath;
p.normalizeQuery = function (build) {
if (typeof this._parts.query === 'string') {
if (!this._parts.query.length) {
this._parts.query = null;
} else {
this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace));
}
this.build(!build);
}
return this;
};
p.normalizeFragment = function (build) {
if (!this._parts.fragment) {
this._parts.fragment = null;
this.build(!build);
}
return this;
};
p.normalizeSearch = p.normalizeQuery;
p.normalizeHash = p.normalizeFragment;
p.iso8859 = function () {
// expect unicode input, iso8859 output
var e = URI.encode;
var d = URI.decode;
URI.encode = escape;
URI.decode = decodeURIComponent;
try {
this.normalize();
} finally {
URI.encode = e;
URI.decode = d;
}
return this;
};
p.unicode = function () {
// expect iso8859 input, unicode output
var e = URI.encode;
var d = URI.decode;
URI.encode = strictEncodeURIComponent;
URI.decode = unescape;
try {
this.normalize();
} finally {
URI.encode = e;
URI.decode = d;
}
return this;
};
p.readable = function () {
var uri = this.clone();
// removing username, password, because they shouldn't be displayed according to RFC 3986
uri.username('').password('').normalize();
var t = '';
if (uri._parts.protocol) {
t += uri._parts.protocol + '://';
}
if (uri._parts.hostname) {
if (uri.is('punycode') && punycode) {
t += punycode.toUnicode(uri._parts.hostname);
if (uri._parts.port) {
t += ':' + uri._parts.port;
}
} else {
t += uri.host();
}
}
if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') {
t += '/';
}
t += uri.path(true);
if (uri._parts.query) {
var q = '';
for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) {
var kv = (qp[i] || '').split('=');
q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace).replace(/&/g, '%26');
if (kv[1] !== undefined) {
q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace).replace(/&/g, '%26');
}
}
t += '?' + q.substring(1);
}
t += URI.decodeQuery(uri.hash(), true);
return t;
};
// resolving relative and absolute URLs
p.absoluteTo = function (base) {
var resolved = this.clone();
var properties = ['protocol', 'username', 'password', 'hostname', 'port'];
var basedir, i, p;
if (this._parts.urn) {
throw new Error('URNs do not have any generally defined hierarchical components');
}
if (!(base instanceof URI)) {
base = new URI(base);
}
if (resolved._parts.protocol) {
// Directly returns even if this._parts.hostname is empty.
return resolved;
} else {
resolved._parts.protocol = base._parts.protocol;
}
if (this._parts.hostname) {
return resolved;
}
for (i = 0; p = properties[i]; i++) {
resolved._parts[p] = base._parts[p];
}
if (!resolved._parts.path) {
resolved._parts.path = base._parts.path;
if (!resolved._parts.query) {
resolved._parts.query = base._parts.query;
}
} else {
if (resolved._parts.path.substring(-2) === '..') {
resolved._parts.path += '/';
}
if (resolved.path().charAt(0) !== '/') {
basedir = base.directory();
basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : '';
resolved._parts.path = (basedir ? basedir + '/' : '') + resolved._parts.path;
resolved.normalizePath();
}
}
resolved.build();
return resolved;
};
p.relativeTo = function (base) {
var relative = this.clone().normalize();
var relativeParts, baseParts, common, relativePath, basePath;
if (relative._parts.urn) {
throw new Error('URNs do not have any generally defined hierarchical components');
}
base = new URI(base).normalize();
relativeParts = relative._parts;
baseParts = base._parts;
relativePath = relative.path();
basePath = base.path();
if (relativePath.charAt(0) !== '/') {
throw new Error('URI is already relative');
}
if (basePath.charAt(0) !== '/') {
throw new Error('Cannot calculate a URI relative to another relative URI');
}
if (relativeParts.protocol === baseParts.protocol) {
relativeParts.protocol = null;
}
if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) {
return relative.build();
}
if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) {
return relative.build();
}
if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) {
relativeParts.hostname = null;
relativeParts.port = null;
} else {
return relative.build();
}
if (relativePath === basePath) {
relativeParts.path = '';
return relative.build();
}
// determine common sub path
common = URI.commonPath(relativePath, basePath);
// If the paths have nothing in common, return a relative URL with the absolute path.
if (!common) {
return relative.build();
}
var parents = baseParts.path.substring(common.length).replace(/[^\/]*$/, '').replace(/.*?\//g, '../');
relativeParts.path = parents + relativeParts.path.substring(common.length) || './';
return relative.build();
};
// comparing URIs
p.equals = function (uri) {
var one = this.clone();
var two = new URI(uri);
var one_map = {};
var two_map = {};
var checked = {};
var one_query, two_query, key;
one.normalize();
two.normalize();
// exact match
if (one.toString() === two.toString()) {
return true;
}
// extract query string
one_query = one.query();
two_query = two.query();
one.query('');
two.query('');
// definitely not equal if not even non-query parts match
if (one.toString() !== two.toString()) {
return false;
}
// query parameters have the same length, even if they're permuted
if (one_query.length !== two_query.length) {
return false;
}
one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace);
two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace);
for (key in one_map) {
if (hasOwn.call(one_map, key)) {
if (!isArray(one_map[key])) {
if (one_map[key] !== two_map[key]) {
return false;
}
} else if (!arraysEqual(one_map[key], two_map[key])) {
return false;
}
checked[key] = true;
}
}
for (key in two_map) {
if (hasOwn.call(two_map, key)) {
if (!checked[key]) {
// two contains a parameter not present in one
return false;
}
}
}
return true;
};
// state
p.preventInvalidHostname = function (v) {
this._parts.preventInvalidHostname = !!v;
return this;
};
p.duplicateQueryParameters = function (v) {
this._parts.duplicateQueryParameters = !!v;
return this;
};
p.escapeQuerySpace = function (v) {
this._parts.escapeQuerySpace = !!v;
return this;
};
return URI;
});
/***/ }),
/***/ 562:
/***/ (function(module, exports, __webpack_require__) {
/* module decorator */ module = __webpack_require__.nmd(module);
var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.0 by @mathias */
;
(function (root) {
/** Detect free variables */
var freeExports = true && exports && !exports.nodeType && exports;
var freeModule = true && module && !module.nodeType && module;
var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g;
if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647,
// aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128,
// 0x80
delimiter = '-',
// '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^\x20-\x7E]/,
// unprintable ASCII chars + non-ASCII chars
regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g,
// RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
var result = [];
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
var labels = string.split('.');
var encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) {
// low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function (value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for /* no initialization */
(; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for /* no final expression */
(index = basic > 0 ? basic + 1 : 0; index < inputLength;) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for /* no condition */
(oldi = i, w = 1, k = base;; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for /* no condition */
(q = delta, k = base;; k += base) {
t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(input) {
return mapDomain(input, function (string) {
return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
});
}
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
function toASCII(input) {
return mapDomain(input, function (string) {
return regexNonASCII.test(string) ? 'xn--' + encode(string) : string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.3.2',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
return punycode;
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
})(this);
/***/ }),
/***/ 484:
/***/ (function(module) {
!function(t,e){ true?module.exports=e():0}(this,(function(){"use strict";var t=1e3,e=6e4,n=36e5,r="millisecond",i="second",s="minute",u="hour",a="day",o="week",f="month",h="quarter",c="year",d="date",l="Invalid Date",$=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,y=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(t){var e=["th","st","nd","rd"],n=t%100;return"["+t+(e[(n-20)%10]||e[n]||e[0])+"]"}},m=function(t,e,n){var r=String(t);return!r||r.length>=e?t:""+Array(e+1-r.length).join(n)+t},v={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return(e<=0?"+":"-")+m(r,2,"0")+":"+m(i,2,"0")},m:function t(e,n){if(e.date()<n.date())return-t(n,e);var r=12*(n.year()-e.year())+(n.month()-e.month()),i=e.clone().add(r,f),s=n-i<0,u=e.clone().add(r+(s?-1:1),f);return+(-(r+(n-i)/(s?i-u:u-i))||0)},a:function(t){return t<0?Math.ceil(t)||0:Math.floor(t)},p:function(t){return{M:f,y:c,w:o,d:a,D:d,h:u,m:s,s:i,ms:r,Q:h}[t]||String(t||"").toLowerCase().replace(/s$/,"")},u:function(t){return void 0===t}},g="en",D={};D[g]=M;var p=function(t){return t instanceof _},S=function t(e,n,r){var i;if(!e)return g;if("string"==typeof e){var s=e.toLowerCase();D[s]&&(i=s),n&&(D[s]=n,i=s);var u=e.split("-");if(!i&&u.length>1)return t(u[0])}else{var a=e.name;D[a]=e,i=a}return!r&&i&&(g=i),i||!r&&g},w=function(t,e){if(p(t))return t.clone();var n="object"==typeof e?e:{};return n.date=t,n.args=arguments,new _(n)},O=v;O.l=S,O.i=p,O.w=function(t,e){return w(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var _=function(){function M(t){this.$L=S(t.locale,null,!0),this.parse(t)}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(O.u(e))return new Date;if(e instanceof Date)return new Date(e);if("string"==typeof e&&!/Z$/i.test(e)){var r=e.match($);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.$x=t.x||{},this.init()},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},m.$utils=function(){return O},m.isValid=function(){return!(this.$d.toString()===l)},m.isSame=function(t,e){var n=w(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return w(t)<this.startOf(e)},m.isBefore=function(t,e){return this.endOf(e)<w(t)},m.$g=function(t,e,n){return O.u(t)?this[e]:this.set(n,t)},m.unix=function(){return Math.floor(this.valueOf()/1e3)},m.valueOf=function(){return this.$d.getTime()},m.startOf=function(t,e){var n=this,r=!!O.u(e)||e,h=O.p(t),l=function(t,e){var i=O.w(n.$u?Date.UTC(n.$y,e,t):new Date(n.$y,e,t),n);return r?i:i.endOf(a)},$=function(t,e){return O.w(n.toDate()[t].apply(n.toDate("s"),(r?[0,0,0,0]:[23,59,59,999]).slice(e)),n)},y=this.$W,M=this.$M,m=this.$D,v="set"+(this.$u?"UTC":"");switch(h){case c:return r?l(1,0):l(31,11);case f:return r?l(1,M):l(0,M+1);case o:var g=this.$locale().weekStart||0,D=(y<g?y+7:y)-g;return l(r?m-D:m+(6-D),M);case a:case d:return $(v+"Hours",0);case u:return $(v+"Minutes",1);case s:return $(v+"Seconds",2);case i:return $(v+"Milliseconds",3);default:return this.clone()}},m.endOf=function(t){return this.startOf(t,!1)},m.$set=function(t,e){var n,o=O.p(t),h="set"+(this.$u?"UTC":""),l=(n={},n[a]=h+"Date",n[d]=h+"Date",n[f]=h+"Month",n[c]=h+"FullYear",n[u]=h+"Hours",n[s]=h+"Minutes",n[i]=h+"Seconds",n[r]=h+"Milliseconds",n)[o],$=o===a?this.$D+(e-this.$W):e;if(o===f||o===c){var y=this.clone().set(d,1);y.$d[l]($),y.init(),this.$d=y.set(d,Math.min(this.$D,y.daysInMonth())).$d}else l&&this.$d[l]($);return this.init(),this},m.set=function(t,e){return this.clone().$set(t,e)},m.get=function(t){return this[O.p(t)]()},m.add=function(r,h){var d,l=this;r=Number(r);var $=O.p(h),y=function(t){var e=w(l);return O.w(e.date(e.date()+Math.round(t*r)),l)};if($===f)return this.set(f,this.$M+r);if($===c)return this.set(c,this.$y+r);if($===a)return y(1);if($===o)return y(7);var M=(d={},d[s]=e,d[u]=n,d[i]=t,d)[$]||1,m=this.$d.getTime()+r*M;return O.w(m,this)},m.subtract=function(t,e){return this.add(-1*t,e)},m.format=function(t){var e=this,n=this.$locale();if(!this.isValid())return n.invalidDate||l;var r=t||"YYYY-MM-DDTHH:mm:ssZ",i=O.z(this),s=this.$H,u=this.$m,a=this.$M,o=n.weekdays,f=n.months,h=function(t,n,i,s){return t&&(t[n]||t(e,r))||i[n].slice(0,s)},c=function(t){return O.s(s%12||12,t,"0")},d=n.meridiem||function(t,e,n){var r=t<12?"AM":"PM";return n?r.toLowerCase():r},$={YY:String(this.$y).slice(-2),YYYY:O.s(this.$y,4,"0"),M:a+1,MM:O.s(a+1,2,"0"),MMM:h(n.monthsShort,a,f,3),MMMM:h(f,a),D:this.$D,DD:O.s(this.$D,2,"0"),d:String(this.$W),dd:h(n.weekdaysMin,this.$W,o,2),ddd:h(n.weekdaysShort,this.$W,o,3),dddd:o[this.$W],H:String(s),HH:O.s(s,2,"0"),h:c(1),hh:c(2),a:d(s,u,!0),A:d(s,u,!1),m:String(u),mm:O.s(u,2,"0"),s:String(this.$s),ss:O.s(this.$s,2,"0"),SSS:O.s(this.$ms,3,"0"),Z:i};return r.replace(y,(function(t,e){return e||$[t]||i.replace(":","")}))},m.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},m.diff=function(r,d,l){var $,y=O.p(d),M=w(r),m=(M.utcOffset()-this.utcOffset())*e,v=this-M,g=O.m(this,M);return g=($={},$[c]=g/12,$[f]=g,$[h]=g/3,$[o]=(v-m)/6048e5,$[a]=(v-m)/864e5,$[u]=v/n,$[s]=v/e,$[i]=v/t,$)[y]||v,l?g:O.a(g)},m.daysInMonth=function(){return this.endOf(f).$D},m.$locale=function(){return D[this.$L]},m.locale=function(t,e){if(!t)return this.$L;var n=this.clone(),r=S(t,e,!0);return r&&(n.$L=r),n},m.clone=function(){return O.w(this.$d,this)},m.toDate=function(){return new Date(this.valueOf())},m.toJSON=function(){return this.isValid()?this.toISOString():null},m.toISOString=function(){return this.$d.toISOString()},m.toString=function(){return this.$d.toUTCString()},M}(),T=_.prototype;return w.prototype=T,[["$ms",r],["$s",i],["$m",s],["$H",u],["$W",a],["$M",f],["$y",c],["$D",d]].forEach((function(t){T[t[1]]=function(e){return this.$g(e,t[0],t[1])}})),w.extend=function(t,e){return t.$i||(t(e,_,w),t.$i=!0),w},w.locale=S,w.isDayjs=p,w.unix=function(t){return w(1e3*t)},w.en=D[g],w.Ls=D,w.p={},w}));
/***/ }),
/***/ 734:
/***/ (function(module) {
!function(e,t){ true?module.exports=t():0}(this,(function(){"use strict";return function(e,t){var r=t.prototype,n=r.format;r.format=function(e){var t=this,r=this.$locale();if(!this.isValid())return n.bind(this)(e);var s=this.$utils(),a=(e||"YYYY-MM-DDTHH:mm:ssZ").replace(/\[([^\]]+)]|Q|wo|ww|w|WW|W|zzz|z|gggg|GGGG|Do|X|x|k{1,2}|S/g,(function(e){switch(e){case"Q":return Math.ceil((t.$M+1)/3);case"Do":return r.ordinal(t.$D);case"gggg":return t.weekYear();case"GGGG":return t.isoWeekYear();case"wo":return r.ordinal(t.week(),"W");case"w":case"ww":return s.s(t.week(),"w"===e?1:2,"0");case"W":case"WW":return s.s(t.isoWeek(),"W"===e?1:2,"0");case"k":case"kk":return s.s(String(0===t.$H?24:t.$H),"k"===e?1:2,"0");case"X":return Math.floor(t.$d.getTime()/1e3);case"x":return t.$d.getTime();case"z":return"["+t.offsetName()+"]";case"zzz":return"["+t.offsetName("long")+"]";default:return e}}));return n.bind(this)(a)}}}));
/***/ }),
/***/ 856:
/***/ (function(module) {
/*! @license DOMPurify 2.4.5 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.4.5/LICENSE */
(function (global, factory) {
true ? module.exports = factory() :
0;
})(this, (function () { 'use strict';
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _construct(Parent, args, Class) {
if (_isNativeReflectConstruct()) {
_construct = Reflect.construct;
} else {
_construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) _setPrototypeOf(instance, Class.prototype);
return instance;
};
}
return _construct.apply(null, arguments);
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var hasOwnProperty = Object.hasOwnProperty,
setPrototypeOf = Object.setPrototypeOf,
isFrozen = Object.isFrozen,
getPrototypeOf = Object.getPrototypeOf,
getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var freeze = Object.freeze,
seal = Object.seal,
create = Object.create; // eslint-disable-line import/no-mutable-exports
var _ref = typeof Reflect !== 'undefined' && Reflect,
apply = _ref.apply,
construct = _ref.construct;
if (!apply) {
apply = function apply(fun, thisValue, args) {
return fun.apply(thisValue, args);
};
}
if (!freeze) {
freeze = function freeze(x) {
return x;
};
}
if (!seal) {
seal = function seal(x) {
return x;
};
}
if (!construct) {
construct = function construct(Func, args) {
return _construct(Func, _toConsumableArray(args));
};
}
var arrayForEach = unapply(Array.prototype.forEach);
var arrayPop = unapply(Array.prototype.pop);
var arrayPush = unapply(Array.prototype.push);
var stringToLowerCase = unapply(String.prototype.toLowerCase);
var stringToString = unapply(String.prototype.toString);
var stringMatch = unapply(String.prototype.match);
var stringReplace = unapply(String.prototype.replace);
var stringIndexOf = unapply(String.prototype.indexOf);
var stringTrim = unapply(String.prototype.trim);
var regExpTest = unapply(RegExp.prototype.test);
var typeErrorCreate = unconstruct(TypeError);
function unapply(func) {
return function (thisArg) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return apply(func, thisArg, args);
};
}
function unconstruct(func) {
return function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return construct(func, args);
};
}
/* Add properties to a lookup table */
function addToSet(set, array, transformCaseFunc) {
transformCaseFunc = transformCaseFunc ? transformCaseFunc : stringToLowerCase;
if (setPrototypeOf) {
// Make 'in' and truthy checks like Boolean(set.constructor)
// independent of any properties defined on Object.prototype.
// Prevent prototype setters from intercepting set as a this value.
setPrototypeOf(set, null);
}
var l = array.length;
while (l--) {
var element = array[l];
if (typeof element === 'string') {
var lcElement = transformCaseFunc(element);
if (lcElement !== element) {
// Config presets (e.g. tags.js, attrs.js) are immutable.
if (!isFrozen(array)) {
array[l] = lcElement;
}
element = lcElement;
}
}
set[element] = true;
}
return set;
}
/* Shallow clone an object */
function clone(object) {
var newObject = create(null);
var property;
for (property in object) {
if (apply(hasOwnProperty, object, [property]) === true) {
newObject[property] = object[property];
}
}
return newObject;
}
/* IE10 doesn't support __lookupGetter__ so lets'
* simulate it. It also automatically checks
* if the prop is function or getter and behaves
* accordingly. */
function lookupGetter(object, prop) {
while (object !== null) {
var desc = getOwnPropertyDescriptor(object, prop);
if (desc) {
if (desc.get) {
return unapply(desc.get);
}
if (typeof desc.value === 'function') {
return unapply(desc.value);
}
}
object = getPrototypeOf(object);
}
function fallbackValue(element) {
console.warn('fallback value for', element);
return null;
}
return fallbackValue;
}
var html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); // SVG
var svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
var svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); // List of SVG elements that are disallowed by default.
// We still need to know them so that we can do namespace
// checks properly in case one wants to add them to
// allow-list.
var svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'fedropshadow', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
var mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover']); // Similarly to SVG, we want to know all MathML elements,
// even those that we disallow by default.
var mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
var text = freeze(['#text']);
var html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']);
var svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
var mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
var xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
var TMPLIT_EXPR = seal(/\${[\w\W]*}/gm);
var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape
var ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
);
var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
);
var DOCTYPE_NAME = seal(/^html$/i);
var getGlobal = function getGlobal() {
return typeof window === 'undefined' ? null : window;
};
/**
* Creates a no-op policy for internal use only.
* Don't export this function outside this module!
* @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.
* @param {Document} document The document object (to determine policy name suffix)
* @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types
* are not supported).
*/
var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
if (_typeof(trustedTypes) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
return null;
} // Allow the callers to control the unique policy name
// by adding a data-tt-policy-suffix to the script element with the DOMPurify.
// Policy creation with duplicate names throws in Trusted Types.
var suffix = null;
var ATTR_NAME = 'data-tt-policy-suffix';
if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {
suffix = document.currentScript.getAttribute(ATTR_NAME);
}
var policyName = 'dompurify' + (suffix ? '#' + suffix : '');
try {
return trustedTypes.createPolicy(policyName, {
createHTML: function createHTML(html) {
return html;
},
createScriptURL: function createScriptURL(scriptUrl) {
return scriptUrl;
}
});
} catch (_) {
// Policy creation failed (most likely another DOMPurify script has
// already run). Skip creating the policy, as this will only cause errors
// if TT are enforced.
console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
return null;
}
};
function createDOMPurify() {
var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
var DOMPurify = function DOMPurify(root) {
return createDOMPurify(root);
};
/**
* Version label, exposed for easier checks
* if DOMPurify is up to date or not
*/
DOMPurify.version = '2.4.5';
/**
* Array of elements that DOMPurify removed during sanitation.
* Empty if nothing was removed.
*/
DOMPurify.removed = [];
if (!window || !window.document || window.document.nodeType !== 9) {
// Not running in a browser, provide a factory function
// so that you can pass your own Window
DOMPurify.isSupported = false;
return DOMPurify;
}
var originalDocument = window.document;
var document = window.document;
var DocumentFragment = window.DocumentFragment,
HTMLTemplateElement = window.HTMLTemplateElement,
Node = window.Node,
Element = window.Element,
NodeFilter = window.NodeFilter,
_window$NamedNodeMap = window.NamedNodeMap,
NamedNodeMap = _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap,
HTMLFormElement = window.HTMLFormElement,
DOMParser = window.DOMParser,
trustedTypes = window.trustedTypes;
var ElementPrototype = Element.prototype;
var cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
var getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
var getParentNode = lookupGetter(ElementPrototype, 'parentNode'); // As per issue #47, the web-components registry is inherited by a
// new document created via createHTMLDocument. As per the spec
// (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
// a new empty registry is used when creating a template contents owner
// document, so we use that as our parent document to ensure nothing
// is inherited.
if (typeof HTMLTemplateElement === 'function') {
var template = document.createElement('template');
if (template.content && template.content.ownerDocument) {
document = template.content.ownerDocument;
}
}
var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
var emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML('') : '';
var _document = document,
implementation = _document.implementation,
createNodeIterator = _document.createNodeIterator,
createDocumentFragment = _document.createDocumentFragment,
getElementsByTagName = _document.getElementsByTagName;
var importNode = originalDocument.importNode;
var documentMode = {};
try {
documentMode = clone(document).documentMode ? document.documentMode : {};
} catch (_) {}
var hooks = {};
/**
* Expose whether this browser supports running the full DOMPurify.
*/
DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9;
var MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
ERB_EXPR$1 = ERB_EXPR,
TMPLIT_EXPR$1 = TMPLIT_EXPR,
DATA_ATTR$1 = DATA_ATTR,
ARIA_ATTR$1 = ARIA_ATTR,
IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
ATTR_WHITESPACE$1 = ATTR_WHITESPACE;
var IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
/**
* We consider the elements and attributes below to be safe. Ideally
* don't add any new ones but feel free to remove unwanted ones.
*/
/* allowed element names */
var ALLOWED_TAGS = null;
var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray(html$1), _toConsumableArray(svg$1), _toConsumableArray(svgFilters), _toConsumableArray(mathMl$1), _toConsumableArray(text)));
/* Allowed attribute names */
var ALLOWED_ATTR = null;
var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray(html), _toConsumableArray(svg), _toConsumableArray(mathMl), _toConsumableArray(xml)));
/*
* Configure how DOMPUrify should handle custom elements and their attributes as well as customized built-in elements.
* @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
* @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
* @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
*/
var CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, {
tagNameCheck: {
writable: true,
configurable: false,
enumerable: true,
value: null
},
attributeNameCheck: {
writable: true,
configurable: false,
enumerable: true,
value: null
},
allowCustomizedBuiltInElements: {
writable: true,
configurable: false,
enumerable: true,
value: false
}
}));
/* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
var FORBID_TAGS = null;
/* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
var FORBID_ATTR = null;
/* Decide if ARIA attributes are okay */
var ALLOW_ARIA_ATTR = true;
/* Decide if custom data attributes are okay */
var ALLOW_DATA_ATTR = true;
/* Decide if unknown protocols are okay */
var ALLOW_UNKNOWN_PROTOCOLS = false;
/* Decide if self-closing tags in attributes are allowed.
* Usually removed due to a mXSS issue in jQuery 3.0 */
var ALLOW_SELF_CLOSE_IN_ATTR = true;
/* Output should be safe for common template engines.
* This means, DOMPurify removes data attributes, mustaches and ERB
*/
var SAFE_FOR_TEMPLATES = false;
/* Decide if document with <html>... should be returned */
var WHOLE_DOCUMENT = false;
/* Track whether config is already set on this instance of DOMPurify. */
var SET_CONFIG = false;
/* Decide if all elements (e.g. style, script) must be children of
* document.body. By default, browsers might move them to document.head */
var FORCE_BODY = false;
/* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
* string (or a TrustedHTML object if Trusted Types are supported).
* If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
*/
var RETURN_DOM = false;
/* Decide if a DOM `DocumentFragment` should be returned, instead of a html
* string (or a TrustedHTML object if Trusted Types are supported) */
var RETURN_DOM_FRAGMENT = false;
/* Try to return a Trusted Type object instead of a string, return a string in
* case Trusted Types are not supported */
var RETURN_TRUSTED_TYPE = false;
/* Output should be free from DOM clobbering attacks?
* This sanitizes markups named with colliding, clobberable built-in DOM APIs.
*/
var SANITIZE_DOM = true;
/* Achieve full DOM Clobbering protection by isolating the namespace of named
* properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
*
* HTML/DOM spec rules that enable DOM Clobbering:
* - Named Access on Window (§7.3.3)
* - DOM Tree Accessors (§3.1.5)
* - Form Element Parent-Child Relations (§4.10.3)
* - Iframe srcdoc / Nested WindowProxies (§4.8.5)
* - HTMLCollection (§4.2.10.2)
*
* Namespace isolation is implemented by prefixing `id` and `name` attributes
* with a constant string, i.e., `user-content-`
*/
var SANITIZE_NAMED_PROPS = false;
var SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
/* Keep element content when removing element? */
var KEEP_CONTENT = true;
/* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
* of importing it into a new Document and returning a sanitized copy */
var IN_PLACE = false;
/* Allow usage of profiles like html, svg and mathMl */
var USE_PROFILES = {};
/* Tags to ignore content of when KEEP_CONTENT is true */
var FORBID_CONTENTS = null;
var DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
/* Tags that are safe for data: URIs */
var DATA_URI_TAGS = null;
var DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
/* Attributes safe for values like "javascript:" */
var URI_SAFE_ATTRIBUTES = null;
var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
/* Document namespace */
var NAMESPACE = HTML_NAMESPACE;
var IS_EMPTY_INPUT = false;
/* Allowed XHTML+XML namespaces */
var ALLOWED_NAMESPACES = null;
var DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
/* Parsing of strict XHTML documents */
var PARSER_MEDIA_TYPE;
var SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
var DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
var transformCaseFunc;
/* Keep a reference to config to pass to hooks */
var CONFIG = null;
/* Ideally, do not touch anything below this line */
/* ______________________________________________ */
var formElement = document.createElement('form');
var isRegexOrFunction = function isRegexOrFunction(testValue) {
return testValue instanceof RegExp || testValue instanceof Function;
};
/**
* _parseConfig
*
* @param {Object} cfg optional config literal
*/
// eslint-disable-next-line complexity
var _parseConfig = function _parseConfig(cfg) {
if (CONFIG && CONFIG === cfg) {
return;
}
/* Shield configuration object from tampering */
if (!cfg || _typeof(cfg) !== 'object') {
cfg = {};
}
/* Shield configuration object from prototype pollution */
cfg = clone(cfg);
PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes
SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE; // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
/* Set configuration parameters */
ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
ALLOWED_NAMESPACES = 'ALLOWED_NAMESPACES' in cfg ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), // eslint-disable-line indent
cfg.ADD_URI_SAFE_ATTR, // eslint-disable-line indent
transformCaseFunc // eslint-disable-line indent
) // eslint-disable-line indent
: DEFAULT_URI_SAFE_ATTRIBUTES;
DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), // eslint-disable-line indent
cfg.ADD_DATA_URI_TAGS, // eslint-disable-line indent
transformCaseFunc // eslint-disable-line indent
) // eslint-disable-line indent
: DEFAULT_DATA_URI_TAGS;
FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {};
FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {};
USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
RETURN_DOM = cfg.RETURN_DOM || false; // Default false
RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
FORCE_BODY = cfg.FORCE_BODY || false; // Default false
SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
IN_PLACE = cfg.IN_PLACE || false; // Default false
IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$1;
NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
}
if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
}
if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
}
if (SAFE_FOR_TEMPLATES) {
ALLOW_DATA_ATTR = false;
}
if (RETURN_DOM_FRAGMENT) {
RETURN_DOM = true;
}
/* Parse profile info */
if (USE_PROFILES) {
ALLOWED_TAGS = addToSet({}, _toConsumableArray(text));
ALLOWED_ATTR = [];
if (USE_PROFILES.html === true) {
addToSet(ALLOWED_TAGS, html$1);
addToSet(ALLOWED_ATTR, html);
}
if (USE_PROFILES.svg === true) {
addToSet(ALLOWED_TAGS, svg$1);
addToSet(ALLOWED_ATTR, svg);
addToSet(ALLOWED_ATTR, xml);
}
if (USE_PROFILES.svgFilters === true) {
addToSet(ALLOWED_TAGS, svgFilters);
addToSet(ALLOWED_ATTR, svg);
addToSet(ALLOWED_ATTR, xml);
}
if (USE_PROFILES.mathMl === true) {
addToSet(ALLOWED_TAGS, mathMl$1);
addToSet(ALLOWED_ATTR, mathMl);
addToSet(ALLOWED_ATTR, xml);
}
}
/* Merge configuration parameters */
if (cfg.ADD_TAGS) {
if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
ALLOWED_TAGS = clone(ALLOWED_TAGS);
}
addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
}
if (cfg.ADD_ATTR) {
if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
ALLOWED_ATTR = clone(ALLOWED_ATTR);
}
addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
}
if (cfg.ADD_URI_SAFE_ATTR) {
addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
}
if (cfg.FORBID_CONTENTS) {
if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
FORBID_CONTENTS = clone(FORBID_CONTENTS);
}
addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
}
/* Add #text in case KEEP_CONTENT is set to true */
if (KEEP_CONTENT) {
ALLOWED_TAGS['#text'] = true;
}
/* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
if (WHOLE_DOCUMENT) {
addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
}
/* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
if (ALLOWED_TAGS.table) {
addToSet(ALLOWED_TAGS, ['tbody']);
delete FORBID_TAGS.tbody;
} // Prevent further manipulation of configuration.
// Not available in IE8, Safari 5, etc.
if (freeze) {
freeze(cfg);
}
CONFIG = cfg;
};
var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
var HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']); // Certain elements are allowed in both SVG and HTML
// namespace. We need to specify them explicitly
// so that they don't get erroneously deleted from
// HTML namespace.
var COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
/* Keep track of all possible SVG and MathML tags
* so that we can perform the namespace checks
* correctly. */
var ALL_SVG_TAGS = addToSet({}, svg$1);
addToSet(ALL_SVG_TAGS, svgFilters);
addToSet(ALL_SVG_TAGS, svgDisallowed);
var ALL_MATHML_TAGS = addToSet({}, mathMl$1);
addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
/**
*
*
* @param {Element} element a DOM element whose namespace is being checked
* @returns {boolean} Return false if the element has a
* namespace that a spec-compliant parser would never
* return. Return true otherwise.
*/
var _checkValidNamespace = function _checkValidNamespace(element) {
var parent = getParentNode(element); // In JSDOM, if we're inside shadow DOM, then parentNode
// can be null. We just simulate parent in this case.
if (!parent || !parent.tagName) {
parent = {
namespaceURI: NAMESPACE,
tagName: 'template'
};
}
var tagName = stringToLowerCase(element.tagName);
var parentTagName = stringToLowerCase(parent.tagName);
if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
return false;
}
if (element.namespaceURI === SVG_NAMESPACE) {
// The only way to switch from HTML namespace to SVG
// is via <svg>. If it happens via any other tag, then
// it should be killed.
if (parent.namespaceURI === HTML_NAMESPACE) {
return tagName === 'svg';
} // The only way to switch from MathML to SVG is via`
// svg if parent is either <annotation-xml> or MathML
// text integration points.
if (parent.namespaceURI === MATHML_NAMESPACE) {
return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
} // We only allow elements that are defined in SVG
// spec. All others are disallowed in SVG namespace.
return Boolean(ALL_SVG_TAGS[tagName]);
}
if (element.namespaceURI === MATHML_NAMESPACE) {
// The only way to switch from HTML namespace to MathML
// is via <math>. If it happens via any other tag, then
// it should be killed.
if (parent.namespaceURI === HTML_NAMESPACE) {
return tagName === 'math';
} // The only way to switch from SVG to MathML is via
// <math> and HTML integration points
if (parent.namespaceURI === SVG_NAMESPACE) {
return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
} // We only allow elements that are defined in MathML
// spec. All others are disallowed in MathML namespace.
return Boolean(ALL_MATHML_TAGS[tagName]);
}
if (element.namespaceURI === HTML_NAMESPACE) {
// The only way to switch from SVG to HTML is via
// HTML integration points, and from MathML to HTML
// is via MathML text integration points
if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
return false;
}
if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
return false;
} // We disallow tags that are specific for MathML
// or SVG and should never appear in HTML namespace
return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
} // For XHTML and XML documents that support custom namespaces
if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
return true;
} // The code should never reach this place (this means
// that the element somehow got namespace that is not
// HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
// Return false just in case.
return false;
};
/**
* _forceRemove
*
* @param {Node} node a DOM node
*/
var _forceRemove = function _forceRemove(node) {
arrayPush(DOMPurify.removed, {
element: node
});
try {
// eslint-disable-next-line unicorn/prefer-dom-node-remove
node.parentNode.removeChild(node);
} catch (_) {
try {
node.outerHTML = emptyHTML;
} catch (_) {
node.remove();
}
}
};
/**
* _removeAttribute
*
* @param {String} name an Attribute name
* @param {Node} node a DOM node
*/
var _removeAttribute = function _removeAttribute(name, node) {
try {
arrayPush(DOMPurify.removed, {
attribute: node.getAttributeNode(name),
from: node
});
} catch (_) {
arrayPush(DOMPurify.removed, {
attribute: null,
from: node
});
}
node.removeAttribute(name); // We void attribute values for unremovable "is"" attributes
if (name === 'is' && !ALLOWED_ATTR[name]) {
if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
try {
_forceRemove(node);
} catch (_) {}
} else {
try {
node.setAttribute(name, '');
} catch (_) {}
}
}
};
/**
* _initDocument
*
* @param {String} dirty a string of dirty markup
* @return {Document} a DOM, filled with the dirty markup
*/
var _initDocument = function _initDocument(dirty) {
/* Create a HTML document */
var doc;
var leadingWhitespace;
if (FORCE_BODY) {
dirty = '<remove></remove>' + dirty;
} else {
/* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
var matches = stringMatch(dirty, /^[\r\n\t ]+/);
leadingWhitespace = matches && matches[0];
}
if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
// Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
}
var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
/*
* Use the DOMParser API by default, fallback later if needs be
* DOMParser not work for svg when has multiple root element.
*/
if (NAMESPACE === HTML_NAMESPACE) {
try {
doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
} catch (_) {}
}
/* Use createHTMLDocument in case DOMParser is not available */
if (!doc || !doc.documentElement) {
doc = implementation.createDocument(NAMESPACE, 'template', null);
try {
doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
} catch (_) {// Syntax error if dirtyPayload is invalid xml
}
}
var body = doc.body || doc.documentElement;
if (dirty && leadingWhitespace) {
body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
}
/* Work on whole document or just its body */
if (NAMESPACE === HTML_NAMESPACE) {
return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
}
return WHOLE_DOCUMENT ? doc.documentElement : body;
};
/**
* _createIterator
*
* @param {Document} root document/fragment to create iterator for
* @return {Iterator} iterator instance
*/
var _createIterator = function _createIterator(root) {
return createNodeIterator.call(root.ownerDocument || root, root, // eslint-disable-next-line no-bitwise
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
};
/**
* _isClobbered
*
* @param {Node} elm element to check for clobbering attacks
* @return {Boolean} true if clobbered, false if safe
*/
var _isClobbered = function _isClobbered(elm) {
return elm instanceof HTMLFormElement && (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function' || typeof elm.hasChildNodes !== 'function');
};
/**
* _isNode
*
* @param {Node} obj object to check whether it's a DOM node
* @return {Boolean} true is object is a DOM node
*/
var _isNode = function _isNode(object) {
return _typeof(Node) === 'object' ? object instanceof Node : object && _typeof(object) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';
};
/**
* _executeHook
* Execute user configurable hooks
*
* @param {String} entryPoint Name of the hook's entry point
* @param {Node} currentNode node to work on with the hook
* @param {Object} data additional hook parameters
*/
var _executeHook = function _executeHook(entryPoint, currentNode, data) {
if (!hooks[entryPoint]) {
return;
}
arrayForEach(hooks[entryPoint], function (hook) {
hook.call(DOMPurify, currentNode, data, CONFIG);
});
};
/**
* _sanitizeElements
*
* @protect nodeName
* @protect textContent
* @protect removeChild
*
* @param {Node} currentNode to check for permission to exist
* @return {Boolean} true if node was killed, false if left alive
*/
var _sanitizeElements = function _sanitizeElements(currentNode) {
var content;
/* Execute a hook if present */
_executeHook('beforeSanitizeElements', currentNode, null);
/* Check if element is clobbered or can clobber */
if (_isClobbered(currentNode)) {
_forceRemove(currentNode);
return true;
}
/* Check if tagname contains Unicode */
if (regExpTest(/[\u0080-\uFFFF]/, currentNode.nodeName)) {
_forceRemove(currentNode);
return true;
}
/* Now let's check the element's type and name */
var tagName = transformCaseFunc(currentNode.nodeName);
/* Execute a hook if present */
_executeHook('uponSanitizeElement', currentNode, {
tagName: tagName,
allowedTags: ALLOWED_TAGS
});
/* Detect mXSS attempts abusing namespace confusion */
if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
_forceRemove(currentNode);
return true;
}
/* Mitigate a problem with templates inside select */
if (tagName === 'select' && regExpTest(/<template/i, currentNode.innerHTML)) {
_forceRemove(currentNode);
return true;
}
/* Remove element if anything forbids its presence */
if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
/* Check if we have a custom element to handle */
if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) {
if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) return false;
if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) return false;
}
/* Keep content except for bad-listed elements */
if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
var parentNode = getParentNode(currentNode) || currentNode.parentNode;
var childNodes = getChildNodes(currentNode) || currentNode.childNodes;
if (childNodes && parentNode) {
var childCount = childNodes.length;
for (var i = childCount - 1; i >= 0; --i) {
parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
}
}
}
_forceRemove(currentNode);
return true;
}
/* Check whether element has a valid namespace */
if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
_forceRemove(currentNode);
return true;
}
if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
_forceRemove(currentNode);
return true;
}
/* Sanitize element content to be template-safe */
if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
/* Get the element's text content */
content = currentNode.textContent;
content = stringReplace(content, MUSTACHE_EXPR$1, ' ');
content = stringReplace(content, ERB_EXPR$1, ' ');
content = stringReplace(content, TMPLIT_EXPR$1, ' ');
if (currentNode.textContent !== content) {
arrayPush(DOMPurify.removed, {
element: currentNode.cloneNode()
});
currentNode.textContent = content;
}
}
/* Execute a hook if present */
_executeHook('afterSanitizeElements', currentNode, null);
return false;
};
/**
* _isValidAttribute
*
* @param {string} lcTag Lowercase tag name of containing element.
* @param {string} lcName Lowercase attribute name.
* @param {string} value Attribute value.
* @return {Boolean} Returns true if `value` is valid, otherwise false.
*/
// eslint-disable-next-line complexity
var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
/* Make sure attribute cannot clobber */
if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
return false;
}
/* Allow valid data-* attributes: At least one character after "-"
(https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
We don't need to check the value; it's always URI safe. */
if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
if ( // First condition does a very basic check if a) it's basically a valid custom element tagname AND
// b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
// and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
_basicCustomElementTest(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || // Alternative, second condition checks if it's an `is`-attribute, AND
// the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {
return false;
}
/* Check value is safe. First, is attr inert? If so, is safe */
} else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (!value) ; else {
return false;
}
return true;
};
/**
* _basicCustomElementCheck
* checks if at least one dash is included in tagName, and it's not the first char
* for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
* @param {string} tagName name of the tag of the node to sanitize
*/
var _basicCustomElementTest = function _basicCustomElementTest(tagName) {
return tagName.indexOf('-') > 0;
};
/**
* _sanitizeAttributes
*
* @protect attributes
* @protect nodeName
* @protect removeAttribute
* @protect setAttribute
*
* @param {Node} currentNode to sanitize
*/
var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
var attr;
var value;
var lcName;
var l;
/* Execute a hook if present */
_executeHook('beforeSanitizeAttributes', currentNode, null);
var attributes = currentNode.attributes;
/* Check if we have attributes; if not we might have a text node */
if (!attributes) {
return;
}
var hookEvent = {
attrName: '',
attrValue: '',
keepAttr: true,
allowedAttributes: ALLOWED_ATTR
};
l = attributes.length;
/* Go backwards over all attributes; safely remove bad ones */
while (l--) {
attr = attributes[l];
var _attr = attr,
name = _attr.name,
namespaceURI = _attr.namespaceURI;
value = name === 'value' ? attr.value : stringTrim(attr.value);
lcName = transformCaseFunc(name);
/* Execute a hook if present */
hookEvent.attrName = lcName;
hookEvent.attrValue = value;
hookEvent.keepAttr = true;
hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
_executeHook('uponSanitizeAttribute', currentNode, hookEvent);
value = hookEvent.attrValue;
/* Did the hooks approve of the attribute? */
if (hookEvent.forceKeepAttr) {
continue;
}
/* Remove attribute */
_removeAttribute(name, currentNode);
/* Did the hooks approve of the attribute? */
if (!hookEvent.keepAttr) {
continue;
}
/* Work around a security issue in jQuery 3.0 */
if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
_removeAttribute(name, currentNode);
continue;
}
/* Sanitize attribute content to be template-safe */
if (SAFE_FOR_TEMPLATES) {
value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
value = stringReplace(value, ERB_EXPR$1, ' ');
value = stringReplace(value, TMPLIT_EXPR$1, ' ');
}
/* Is `value` valid for this attribute? */
var lcTag = transformCaseFunc(currentNode.nodeName);
if (!_isValidAttribute(lcTag, lcName, value)) {
continue;
}
/* Full DOM Clobbering protection via namespace isolation,
* Prefix id and name attributes with `user-content-`
*/
if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
// Remove the attribute with this value
_removeAttribute(name, currentNode); // Prefix the value and later re-create the attribute with the sanitized value
value = SANITIZE_NAMED_PROPS_PREFIX + value;
}
/* Handle attributes that require Trusted Types */
if (trustedTypesPolicy && _typeof(trustedTypes) === 'object' && typeof trustedTypes.getAttributeType === 'function') {
if (namespaceURI) ; else {
switch (trustedTypes.getAttributeType(lcTag, lcName)) {
case 'TrustedHTML':
value = trustedTypesPolicy.createHTML(value);
break;
case 'TrustedScriptURL':
value = trustedTypesPolicy.createScriptURL(value);
break;
}
}
}
/* Handle invalid data-* attribute set by try-catching it */
try {
if (namespaceURI) {
currentNode.setAttributeNS(namespaceURI, name, value);
} else {
/* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
currentNode.setAttribute(name, value);
}
arrayPop(DOMPurify.removed);
} catch (_) {}
}
/* Execute a hook if present */
_executeHook('afterSanitizeAttributes', currentNode, null);
};
/**
* _sanitizeShadowDOM
*
* @param {DocumentFragment} fragment to iterate over recursively
*/
var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
var shadowNode;
var shadowIterator = _createIterator(fragment);
/* Execute a hook if present */
_executeHook('beforeSanitizeShadowDOM', fragment, null);
while (shadowNode = shadowIterator.nextNode()) {
/* Execute a hook if present */
_executeHook('uponSanitizeShadowNode', shadowNode, null);
/* Sanitize tags and elements */
if (_sanitizeElements(shadowNode)) {
continue;
}
/* Deep shadow DOM detected */
if (shadowNode.content instanceof DocumentFragment) {
_sanitizeShadowDOM(shadowNode.content);
}
/* Check attributes, sanitize if necessary */
_sanitizeAttributes(shadowNode);
}
/* Execute a hook if present */
_executeHook('afterSanitizeShadowDOM', fragment, null);
};
/**
* Sanitize
* Public method providing core sanitation functionality
*
* @param {String|Node} dirty string or DOM node
* @param {Object} configuration object
*/
// eslint-disable-next-line complexity
DOMPurify.sanitize = function (dirty) {
var cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var body;
var importedNode;
var currentNode;
var oldNode;
var returnNode;
/* Make sure we have a string to sanitize.
DO NOT return early, as this will return the wrong type if
the user has requested a DOM object rather than a string */
IS_EMPTY_INPUT = !dirty;
if (IS_EMPTY_INPUT) {
dirty = '<!-->';
}
/* Stringify, in case dirty is an object */
if (typeof dirty !== 'string' && !_isNode(dirty)) {
// eslint-disable-next-line no-negated-condition
if (typeof dirty.toString !== 'function') {
throw typeErrorCreate('toString is not a function');
} else {
dirty = dirty.toString();
if (typeof dirty !== 'string') {
throw typeErrorCreate('dirty is not a string, aborting');
}
}
}
/* Check we can run. Otherwise fall back or ignore */
if (!DOMPurify.isSupported) {
if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {
if (typeof dirty === 'string') {
return window.toStaticHTML(dirty);
}
if (_isNode(dirty)) {
return window.toStaticHTML(dirty.outerHTML);
}
}
return dirty;
}
/* Assign config vars */
if (!SET_CONFIG) {
_parseConfig(cfg);
}
/* Clean up removed elements */
DOMPurify.removed = [];
/* Check if dirty is correctly typed for IN_PLACE */
if (typeof dirty === 'string') {
IN_PLACE = false;
}
if (IN_PLACE) {
/* Do some early pre-sanitization to avoid unsafe root nodes */
if (dirty.nodeName) {
var tagName = transformCaseFunc(dirty.nodeName);
if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
}
}
} else if (dirty instanceof Node) {
/* If dirty is a DOM element, append to an empty document to avoid
elements being stripped by the parser */
body = _initDocument('<!---->');
importedNode = body.ownerDocument.importNode(dirty, true);
if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
/* Node is already a body, use as is */
body = importedNode;
} else if (importedNode.nodeName === 'HTML') {
body = importedNode;
} else {
// eslint-disable-next-line unicorn/prefer-dom-node-append
body.appendChild(importedNode);
}
} else {
/* Exit directly if we have nothing to do */
if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes
dirty.indexOf('<') === -1) {
return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
}
/* Initialize the document to work on */
body = _initDocument(dirty);
/* Check we have a DOM node from the data */
if (!body) {
return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
}
}
/* Remove first element node (ours) if FORCE_BODY is set */
if (body && FORCE_BODY) {
_forceRemove(body.firstChild);
}
/* Get node iterator */
var nodeIterator = _createIterator(IN_PLACE ? dirty : body);
/* Now start iterating over the created document */
while (currentNode = nodeIterator.nextNode()) {
/* Fix IE's strange behavior with manipulated textNodes #89 */
if (currentNode.nodeType === 3 && currentNode === oldNode) {
continue;
}
/* Sanitize tags and elements */
if (_sanitizeElements(currentNode)) {
continue;
}
/* Shadow DOM detected, sanitize it */
if (currentNode.content instanceof DocumentFragment) {
_sanitizeShadowDOM(currentNode.content);
}
/* Check attributes, sanitize if necessary */
_sanitizeAttributes(currentNode);
oldNode = currentNode;
}
oldNode = null;
/* If we sanitized `dirty` in-place, return it. */
if (IN_PLACE) {
return dirty;
}
/* Return sanitized string or DOM */
if (RETURN_DOM) {
if (RETURN_DOM_FRAGMENT) {
returnNode = createDocumentFragment.call(body.ownerDocument);
while (body.firstChild) {
// eslint-disable-next-line unicorn/prefer-dom-node-append
returnNode.appendChild(body.firstChild);
}
} else {
returnNode = body;
}
if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmod) {
/*
AdoptNode() is not used because internal state is not reset
(e.g. the past names map of a HTMLFormElement), this is safe
in theory but we would rather not risk another attack vector.
The state that is cloned by importNode() is explicitly defined
by the specs.
*/
returnNode = importNode.call(originalDocument, returnNode, true);
}
return returnNode;
}
var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
/* Serialize doctype if allowed */
if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
}
/* Sanitize final string template-safe */
if (SAFE_FOR_TEMPLATES) {
serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$1, ' ');
serializedHTML = stringReplace(serializedHTML, ERB_EXPR$1, ' ');
serializedHTML = stringReplace(serializedHTML, TMPLIT_EXPR$1, ' ');
}
return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
};
/**
* Public method to set the configuration once
* setConfig
*
* @param {Object} cfg configuration object
*/
DOMPurify.setConfig = function (cfg) {
_parseConfig(cfg);
SET_CONFIG = true;
};
/**
* Public method to remove the configuration
* clearConfig
*
*/
DOMPurify.clearConfig = function () {
CONFIG = null;
SET_CONFIG = false;
};
/**
* Public method to check if an attribute value is valid.
* Uses last set config, if any. Otherwise, uses config defaults.
* isValidAttribute
*
* @param {string} tag Tag name of containing element.
* @param {string} attr Attribute name.
* @param {string} value Attribute value.
* @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.
*/
DOMPurify.isValidAttribute = function (tag, attr, value) {
/* Initialize shared config vars if necessary. */
if (!CONFIG) {
_parseConfig({});
}
var lcTag = transformCaseFunc(tag);
var lcName = transformCaseFunc(attr);
return _isValidAttribute(lcTag, lcName, value);
};
/**
* AddHook
* Public method to add DOMPurify hooks
*
* @param {String} entryPoint entry point for the hook to add
* @param {Function} hookFunction function to execute
*/
DOMPurify.addHook = function (entryPoint, hookFunction) {
if (typeof hookFunction !== 'function') {
return;
}
hooks[entryPoint] = hooks[entryPoint] || [];
arrayPush(hooks[entryPoint], hookFunction);
};
/**
* RemoveHook
* Public method to remove a DOMPurify hook at a given entryPoint
* (pops it from the stack of hooks if more are present)
*
* @param {String} entryPoint entry point for the hook to remove
* @return {Function} removed(popped) hook
*/
DOMPurify.removeHook = function (entryPoint) {
if (hooks[entryPoint]) {
return arrayPop(hooks[entryPoint]);
}
};
/**
* RemoveHooks
* Public method to remove all DOMPurify hooks at a given entryPoint
*
* @param {String} entryPoint entry point for the hooks to remove
*/
DOMPurify.removeHooks = function (entryPoint) {
if (hooks[entryPoint]) {
hooks[entryPoint] = [];
}
};
/**
* RemoveAllHooks
* Public method to remove all DOMPurify hooks
*
*/
DOMPurify.removeAllHooks = function () {
hooks = {};
};
return DOMPurify;
}
var purify = createDOMPurify();
return purify;
}));
//# sourceMappingURL=purify.js.map
/***/ }),
/***/ 705:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var Mutation = __webpack_require__.g.MutationObserver || __webpack_require__.g.WebKitMutationObserver;
var scheduleDrain;
{
if (Mutation) {
var called = 0;
var observer = new Mutation(nextTick);
var element = __webpack_require__.g.document.createTextNode('');
observer.observe(element, {
characterData: true
});
scheduleDrain = function () {
element.data = (called = ++called % 2);
};
} else if (!__webpack_require__.g.setImmediate && typeof __webpack_require__.g.MessageChannel !== 'undefined') {
var channel = new __webpack_require__.g.MessageChannel();
channel.port1.onmessage = nextTick;
scheduleDrain = function () {
channel.port2.postMessage(0);
};
} else if ('document' in __webpack_require__.g && 'onreadystatechange' in __webpack_require__.g.document.createElement('script')) {
scheduleDrain = function () {
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var scriptEl = __webpack_require__.g.document.createElement('script');
scriptEl.onreadystatechange = function () {
nextTick();
scriptEl.onreadystatechange = null;
scriptEl.parentNode.removeChild(scriptEl);
scriptEl = null;
};
__webpack_require__.g.document.documentElement.appendChild(scriptEl);
};
} else {
scheduleDrain = function () {
setTimeout(nextTick, 0);
};
}
}
var draining;
var queue = [];
//named nextTick for less confusing stack traces
function nextTick() {
draining = true;
var i, oldQueue;
var len = queue.length;
while (len) {
oldQueue = queue;
queue = [];
i = -1;
while (++i < len) {
oldQueue[i]();
}
len = queue.length;
}
draining = false;
}
module.exports = immediate;
function immediate(task) {
if (queue.push(task) === 1 && !draining) {
scheduleDrain();
}
}
/***/ }),
/***/ 389:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var immediate = __webpack_require__(705);
/* istanbul ignore next */
function INTERNAL() {}
var handlers = {};
var REJECTED = ['REJECTED'];
var FULFILLED = ['FULFILLED'];
var PENDING = ['PENDING'];
module.exports = Promise;
function Promise(resolver) {
if (typeof resolver !== 'function') {
throw new TypeError('resolver must be a function');
}
this.state = PENDING;
this.queue = [];
this.outcome = void 0;
if (resolver !== INTERNAL) {
safelyResolveThenable(this, resolver);
}
}
Promise.prototype["catch"] = function (onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.then = function (onFulfilled, onRejected) {
if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
typeof onRejected !== 'function' && this.state === REJECTED) {
return this;
}
var promise = new this.constructor(INTERNAL);
if (this.state !== PENDING) {
var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
unwrap(promise, resolver, this.outcome);
} else {
this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
}
return promise;
};
function QueueItem(promise, onFulfilled, onRejected) {
this.promise = promise;
if (typeof onFulfilled === 'function') {
this.onFulfilled = onFulfilled;
this.callFulfilled = this.otherCallFulfilled;
}
if (typeof onRejected === 'function') {
this.onRejected = onRejected;
this.callRejected = this.otherCallRejected;
}
}
QueueItem.prototype.callFulfilled = function (value) {
handlers.resolve(this.promise, value);
};
QueueItem.prototype.otherCallFulfilled = function (value) {
unwrap(this.promise, this.onFulfilled, value);
};
QueueItem.prototype.callRejected = function (value) {
handlers.reject(this.promise, value);
};
QueueItem.prototype.otherCallRejected = function (value) {
unwrap(this.promise, this.onRejected, value);
};
function unwrap(promise, func, value) {
immediate(function () {
var returnValue;
try {
returnValue = func(value);
} catch (e) {
return handlers.reject(promise, e);
}
if (returnValue === promise) {
handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
} else {
handlers.resolve(promise, returnValue);
}
});
}
handlers.resolve = function (self, value) {
var result = tryCatch(getThen, value);
if (result.status === 'error') {
return handlers.reject(self, result.value);
}
var thenable = result.value;
if (thenable) {
safelyResolveThenable(self, thenable);
} else {
self.state = FULFILLED;
self.outcome = value;
var i = -1;
var len = self.queue.length;
while (++i < len) {
self.queue[i].callFulfilled(value);
}
}
return self;
};
handlers.reject = function (self, error) {
self.state = REJECTED;
self.outcome = error;
var i = -1;
var len = self.queue.length;
while (++i < len) {
self.queue[i].callRejected(error);
}
return self;
};
function getThen(obj) {
// Make sure we only access the accessor once as required by the spec
var then = obj && obj.then;
if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
return function appyThen() {
then.apply(obj, arguments);
};
}
}
function safelyResolveThenable(self, thenable) {
// Either fulfill, reject or reject with error
var called = false;
function onError(value) {
if (called) {
return;
}
called = true;
handlers.reject(self, value);
}
function onSuccess(value) {
if (called) {
return;
}
called = true;
handlers.resolve(self, value);
}
function tryToUnwrap() {
thenable(onSuccess, onError);
}
var result = tryCatch(tryToUnwrap);
if (result.status === 'error') {
onError(result.value);
}
}
function tryCatch(func, value) {
var out = {};
try {
out.value = func(value);
out.status = 'success';
} catch (e) {
out.status = 'error';
out.value = e;
}
return out;
}
Promise.resolve = resolve;
function resolve(value) {
if (value instanceof this) {
return value;
}
return handlers.resolve(new this(INTERNAL), value);
}
Promise.reject = reject;
function reject(reason) {
var promise = new this(INTERNAL);
return handlers.reject(promise, reason);
}
Promise.all = all;
function all(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== '[object Array]') {
return this.reject(new TypeError('must be an array'));
}
var len = iterable.length;
var called = false;
if (!len) {
return this.resolve([]);
}
var values = new Array(len);
var resolved = 0;
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) {
allResolver(iterable[i], i);
}
return promise;
function allResolver(value, i) {
self.resolve(value).then(resolveFromAll, function (error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
});
function resolveFromAll(outValue) {
values[i] = outValue;
if (++resolved === len && !called) {
called = true;
handlers.resolve(promise, values);
}
}
}
}
Promise.race = race;
function race(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== '[object Array]') {
return this.reject(new TypeError('must be an array'));
}
var len = iterable.length;
var called = false;
if (!len) {
return this.resolve([]);
}
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) {
resolver(iterable[i]);
}
return promise;
function resolver(value) {
self.resolve(value).then(function (response) {
if (!called) {
called = true;
handlers.resolve(promise, response);
}
}, function (error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
});
}
}
/***/ }),
/***/ 236:
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
if (typeof __webpack_require__.g.Promise !== 'function') {
__webpack_require__.g.Promise = __webpack_require__(389);
}
/***/ }),
/***/ 245:
/***/ (function(__unused_webpack_module, exports) {
/*!
MIT License
Copyright (c) 2018 Arturas Molcanovas <a.molcanovas@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
(function (global, factory) {
true ? factory(exports) :
0;
}(typeof self !== 'undefined' ? self : this, function (exports) { 'use strict';
var _driver = 'localforage-driver-memory';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
function __values(o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
}
/*!
MIT License
Copyright (c) 2018 Arturas Molcanovas <a.molcanovas@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* Abstracts constructing a Blob object, so it also works in older
* browsers that don't support the native Blob constructor. (i.e.
* old QtWebKit versions, at least).
* Abstracts constructing a Blob object, so it also works in older
* browsers that don't support the native Blob constructor. (i.e.
* old QtWebKit versions, at least).
*
* @param parts
* @param properties
*/
function createBlob(parts, properties) {
/* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
}
catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
//tslint:disable-next-line:variable-name
var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder
: typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder
: typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder
: WebKitBlobBuilder;
var builder = new Builder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER_LENGTH = "__lfsc__:" /* SERIALIZED_MARKER */.length;
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + "arbf" /* TYPE_ARRAYBUFFER */.length;
//tslint:disable:no-magic-numbers no-bitwise prefer-switch no-unbound-method
var toString = Object.prototype.toString;
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (var i = 0, p = 0; i < len; i += 4) {
var encoded1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */.indexOf(serializedString[i]);
var encoded2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */.indexOf(serializedString[i + 1]);
var encoded3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */.indexOf(serializedString[i + 2]);
var encoded4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */.indexOf(serializedString[i + 3]);
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return buffer;
}
/**
* Converts a buffer to a string to store, serialized, in the backend
* storage library.
*/
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
for (var i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */[bytes[i] >> 2];
base64String += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64String +=
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64String += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */[bytes[i + 2] & 63];
}
if (bytes.length % 3 === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
}
else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
/**
* Serialize a value, afterwards executing a callback (which usually
* instructs the `setItem()` callback/promise to be executed). This is how
* we store binary data with localStorage.
* @param value
* @param callback
*/
function serialize(value, callback) {
var valueType = '';
if (value) {
valueType = toString.call(value);
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
if (value && (valueType === '[object ArrayBuffer]' ||
(value.buffer && toString.call(value.buffer) === '[object ArrayBuffer]'))) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer = void 0;
var marker = "__lfsc__:" /* SERIALIZED_MARKER */;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += "arbf" /* TYPE_ARRAYBUFFER */;
}
else {
buffer = value.buffer;
if (valueType === '[object Int8Array]') {
marker += "si08" /* TYPE_INT8ARRAY */;
}
else if (valueType === '[object Uint8Array]') {
marker += "ui08" /* TYPE_UINT8ARRAY */;
}
else if (valueType === '[object Uint8ClampedArray]') {
marker += "uic8" /* TYPE_UINT8CLAMPEDARRAY */;
}
else if (valueType === '[object Int16Array]') {
marker += "si16" /* TYPE_INT16ARRAY */;
}
else if (valueType === '[object Uint16Array]') {
marker += "ur16" /* TYPE_UINT16ARRAY */;
}
else if (valueType === '[object Int32Array]') {
marker += "si32" /* TYPE_INT32ARRAY */;
}
else if (valueType === '[object Uint32Array]') {
marker += "ui32" /* TYPE_UINT32ARRAY */;
}
else if (valueType === '[object Float32Array]') {
marker += "fl32" /* TYPE_FLOAT32ARRAY */;
}
else if (valueType === '[object Float64Array]') {
marker += "fl64" /* TYPE_FLOAT64ARRAY */;
}
else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
}
else if (valueType === '[object Blob]') {
// Convert the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function () {
// Backwards-compatible prefix for the blob type.
//tslint:disable-next-line:restrict-plus-operands
var str = "~~local_forage_type~" /* BLOB_TYPE_PREFIX */ + value.type + "~" + bufferToString(this.result);
callback("__lfsc__:" /* SERIALIZED_MARKER */ + "blob" /* TYPE_BLOB */ + str);
};
fileReader.readAsArrayBuffer(value);
}
else {
try {
callback(JSON.stringify(value));
}
catch (e) {
console.error('Couldn\'t convert value into a JSON string: ', value);
callback(null, e);
}
}
}
/**
* Deserialize data we've inserted into a value column/field. We place
* special markers into our strings to mark them as encoded; this isn't
* as nice as a meta field, but it's the only sane thing we can do whilst
* keeping localStorage support intact.
*
* Oftentimes this will just deserialize JSON content, but if we have a
* special marker (SERIALIZED_MARKER, defined above), we will extract
* some kind of arraybuffer/binary data/typed array out of the string.
* @param value
*/
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== "__lfsc__:" /* SERIALIZED_MARKER */) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === "blob" /* TYPE_BLOB */ && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case "arbf" /* TYPE_ARRAYBUFFER */:
return buffer;
case "blob" /* TYPE_BLOB */:
return createBlob([buffer], { type: blobType });
case "si08" /* TYPE_INT8ARRAY */:
return new Int8Array(buffer);
case "ui08" /* TYPE_UINT8ARRAY */:
return new Uint8Array(buffer);
case "uic8" /* TYPE_UINT8CLAMPEDARRAY */:
return new Uint8ClampedArray(buffer);
case "si16" /* TYPE_INT16ARRAY */:
return new Int16Array(buffer);
case "ur16" /* TYPE_UINT16ARRAY */:
return new Uint16Array(buffer);
case "si32" /* TYPE_INT32ARRAY */:
return new Int32Array(buffer);
case "ui32" /* TYPE_UINT32ARRAY */:
return new Uint32Array(buffer);
case "fl32" /* TYPE_FLOAT32ARRAY */:
return new Float32Array(buffer);
case "fl64" /* TYPE_FLOAT64ARRAY */:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
function clone(obj) {
var e_1, _a;
if (obj === null || typeof (obj) !== 'object' || 'isActiveClone' in obj) {
return obj;
}
var temp = obj instanceof Date ? new Date(obj) : (obj.constructor());
try {
for (var _b = __values(Object.keys(obj)), _c = _b.next(); !_c.done; _c = _b.next()) {
var key = _c.value;
if (Object.prototype.hasOwnProperty.call(obj, key)) {
obj['isActiveClone'] = null;
temp[key] = clone(obj[key]);
delete obj['isActiveClone'];
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
return temp;
}
function getKeyPrefix(options, defaultConfig) {
return (options.name || defaultConfig.name) + "/" + (options.storeName || defaultConfig.storeName) + "/";
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
function getCallback() {
var _args = [];
for (var _i = 0; _i < arguments.length; _i++) {
_args[_i] = arguments[_i];
}
if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
return arguments[arguments.length - 1];
}
}
//tslint:disable-next-line:no-ignored-initial-value
function dropInstanceCommon(options, callback) {
var _this = this;
callback = getCallback.apply(this, arguments);
options = (typeof options !== 'function' && options) || {};
if (!options.name) {
var currentConfig = this.config();
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var promise;
if (!options.name) {
promise = Promise.reject('Invalid arguments');
}
else {
promise = new Promise(function (resolve) {
if (!options.storeName) {
resolve(options.name + "/");
}
else {
resolve(getKeyPrefix(options, _this._defaultConfig));
}
});
}
return { promise: promise, callback: callback };
}
function normaliseKey(key) {
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
console.warn(key + " used as a key, but it is not a string.");
key = String(key);
}
return key;
}
var serialiser = {
bufferToString: bufferToString,
deserialize: deserialize,
serialize: serialize,
stringToBuffer: stringToBuffer
};
var stores = {};
/** @internal */
var Store = /** @class */ (function () {
function Store(kp) {
this.kp = kp;
this.data = {};
}
Store.resolve = function (kp) {
if (!stores[kp]) {
stores[kp] = new Store(kp);
}
return stores[kp];
};
Store.prototype.clear = function () {
this.data = {};
};
Store.prototype.drop = function () {
this.clear();
delete stores[this.kp];
};
Store.prototype.get = function (key) {
return this.data[key];
};
Store.prototype.key = function (idx) {
return this.keys()[idx];
};
Store.prototype.keys = function () {
return Object.keys(this.data);
};
Store.prototype.rm = function (k) {
delete this.data[k];
};
Store.prototype.set = function (k, v) {
this.data[k] = v;
};
return Store;
}());
function _initStorage(options) {
var opts = options ? clone(options) : {};
var kp = getKeyPrefix(opts, this._defaultConfig);
var store = Store.resolve(kp);
this._dbInfo = opts;
this._dbInfo.serializer = serialiser;
this._dbInfo.keyPrefix = kp;
this._dbInfo.mStore = store;
return Promise.resolve();
}
function clear(callback) {
var _this = this;
var promise = this.ready().then(function () {
_this._dbInfo.mStore.clear();
});
executeCallback(promise, callback);
return promise;
}
function dropInstance(_options, _cb) {
var _a = dropInstanceCommon.apply(this, arguments), promise = _a.promise, callback = _a.callback;
var outPromise = promise.then(function (keyPrefix) {
Store.resolve(keyPrefix).drop();
});
executeCallback(outPromise, callback);
return promise;
}
function getItem(key$, callback) {
var _this = this;
key$ = normaliseKey(key$);
var promise = this.ready().then(function () {
var result = _this._dbInfo.mStore.get(key$);
// Deserialise if the result is not null or undefined
return result == null ? null : _this._dbInfo.serializer.deserialize(result); //tslint:disable-line:triple-equals
});
executeCallback(promise, callback);
return promise;
}
function iterate(iterator, callback) {
var _this = this;
var promise = this.ready().then(function () {
var store = _this._dbInfo.mStore;
var keys = store.keys();
for (var i = 0; i < keys.length; i++) {
var value = store.get(keys[i]);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = _this._dbInfo.serializer.deserialize(value);
}
value = iterator(value, keys[i], i + 1);
if (value !== undefined) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
function key(idx, callback) {
var _this = this;
var promise = this.ready().then(function () {
var result;
try {
result = _this._dbInfo.mStore.key(idx);
if (result === undefined) {
result = null;
}
}
catch (_a) {
result = null;
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var _this = this;
var promise = this.ready().then(function () {
return _this._dbInfo.mStore.keys();
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var promise = this.keys().then(function (keys$) { return keys$.length; });
executeCallback(promise, callback);
return promise;
}
function removeItem(key$, callback) {
var _this = this;
key$ = normaliseKey(key$);
var promise = this.ready().then(function () {
_this._dbInfo.mStore.rm(key$);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key$, value, callback) {
var _this = this;
key$ = normaliseKey(key$);
var promise = this.ready().then(function () {
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise(function (resolve, reject) {
_this._dbInfo.serializer.serialize(value, function (value$, error) {
if (error) {
reject(error);
}
else {
try {
_this._dbInfo.mStore.set(key$, value$);
resolve(originalValue);
}
catch (e) {
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
var _support = true;
exports._support = _support;
exports._driver = _driver;
exports._initStorage = _initStorage;
exports.clear = clear;
exports.dropInstance = dropInstance;
exports.getItem = getItem;
exports.iterate = iterate;
exports.key = key;
exports.keys = keys;
exports.length = length;
exports.removeItem = removeItem;
exports.setItem = setItem;
Object.defineProperty(exports, '__esModule', { value: true });
}));
//# sourceMappingURL=umd.js.map
/***/ }),
/***/ 459:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
(function (global, factory) {
true ? factory(exports, __webpack_require__(483)) :
0;
}(this, (function (exports,localforage) { 'use strict';
localforage = 'default' in localforage ? localforage['default'] : localforage;
function getSerializerPromise(localForageInstance) {
if (getSerializerPromise.result) {
return getSerializerPromise.result;
}
if (!localForageInstance || typeof localForageInstance.getSerializer !== 'function') {
return Promise.reject(new Error('localforage.getSerializer() was not available! ' + 'localforage v1.4+ is required!'));
}
getSerializerPromise.result = localForageInstance.getSerializer();
return getSerializerPromise.result;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
function forEachItem(items, keyFn, valueFn, loopFn) {
function ensurePropGetterMethod(propFn, defaultPropName) {
var propName = propFn || defaultPropName;
if ((!propFn || typeof propFn !== 'function') && typeof propName === 'string') {
propFn = function propFn(item) {
return item[propName];
};
}
return propFn;
}
var result = [];
// http://stackoverflow.com/questions/4775722/check-if-object-is-array
if (Object.prototype.toString.call(items) === '[object Array]') {
keyFn = ensurePropGetterMethod(keyFn, 'key');
valueFn = ensurePropGetterMethod(valueFn, 'value');
for (var i = 0, len = items.length; i < len; i++) {
var item = items[i];
result.push(loopFn(keyFn(item), valueFn(item)));
}
} else {
for (var prop in items) {
if (items.hasOwnProperty(prop)) {
result.push(loopFn(prop, items[prop]));
}
}
}
return result;
}
function setItemsIndexedDB(items, keyFn, valueFn, callback) {
var localforageInstance = this;
var promise = localforageInstance.ready().then(function () {
return new Promise(function (resolve, reject) {
// Inspired from @lu4 PR mozilla/localForage#318
var dbInfo = localforageInstance._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
var lastError;
transaction.oncomplete = function () {
resolve(items);
};
transaction.onabort = transaction.onerror = function (event) {
reject(lastError || event.target);
};
function requestOnError(evt) {
var request = evt.target || this;
lastError = request.error || request.transaction.error;
reject(lastError);
}
forEachItem(items, keyFn, valueFn, function (key, value) {
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var request = store.put(value, key);
request.onerror = requestOnError;
});
});
});
executeCallback(promise, callback);
return promise;
}
function setItemsWebsql(items, keyFn, valueFn, callback) {
var localforageInstance = this;
var promise = new Promise(function (resolve, reject) {
localforageInstance.ready().then(function () {
return getSerializerPromise(localforageInstance);
}).then(function (serializer) {
// Inspired from @lu4 PR mozilla/localForage#318
var dbInfo = localforageInstance._dbInfo;
dbInfo.db.transaction(function (t) {
var query = 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)';
var itemPromises = forEachItem(items, keyFn, valueFn, function (key, value) {
return new Promise(function (resolve, reject) {
serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
t.executeSql(query, [key, value], function () {
resolve();
}, function (t, error) {
reject(error);
});
}
});
});
});
Promise.all(itemPromises).then(function () {
resolve(items);
}, reject);
}, function (sqlError) {
reject(sqlError);
} /*, function() {
if (resolving) {
resolve(items);
}
}*/);
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
function setItemsGeneric(items, keyFn, valueFn, callback) {
var localforageInstance = this;
var itemPromises = forEachItem(items, keyFn, valueFn, function (key, value) {
return localforageInstance.setItem(key, value);
});
var promise = Promise.all(itemPromises);
executeCallback(promise, callback);
return promise;
}
function localforageSetItems(items, keyFn, valueFn, callback) {
var localforageInstance = this;
var currentDriver = localforageInstance.driver();
if (currentDriver === localforageInstance.INDEXEDDB) {
return setItemsIndexedDB.call(localforageInstance, items, keyFn, valueFn, callback);
} else if (currentDriver === localforageInstance.WEBSQL) {
return setItemsWebsql.call(localforageInstance, items, keyFn, valueFn, callback);
} else {
return setItemsGeneric.call(localforageInstance, items, keyFn, valueFn, callback);
}
}
function extendPrototype(localforage$$1) {
var localforagePrototype = Object.getPrototypeOf(localforage$$1);
if (localforagePrototype) {
localforagePrototype.setItems = localforageSetItems;
localforagePrototype.setItems.indexedDB = function () {
return setItemsIndexedDB.apply(this, arguments);
};
localforagePrototype.setItems.websql = function () {
return setItemsWebsql.apply(this, arguments);
};
localforagePrototype.setItems.generic = function () {
return setItemsGeneric.apply(this, arguments);
};
}
}
var extendPrototypeResult = extendPrototype(localforage);
exports.setItemsGeneric = setItemsGeneric;
exports.localforageSetItems = localforageSetItems;
exports.extendPrototype = extendPrototype;
exports.extendPrototypeResult = extendPrototypeResult;
Object.defineProperty(exports, '__esModule', { value: true });
})));
/***/ }),
/***/ 715:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
var _interopRequireDefault = __webpack_require__(836);
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = createDriver;
var _regenerator = _interopRequireDefault(__webpack_require__(687));
var _defineProperty2 = _interopRequireDefault(__webpack_require__(416));
var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(156));
var _utils = __webpack_require__(639);
function createDriver(name, property) {
var storage = (0, _utils.getStorage)();
var support = !!(storage && storage[property]);
var driver = support ? storage[property] : {
clear: function clear() {},
get: function get() {},
remove: function remove() {},
set: function set() {}
};
var _clear = driver.clear.bind(driver);
var get = driver.get.bind(driver);
var remove = driver.remove.bind(driver);
var set = driver.set.bind(driver);
return {
_driver: name,
_support: support,
// eslint-disable-next-line no-underscore-dangle
_initStorage: function _initStorage() {
return Promise.resolve();
},
clear: function clear(callback) {
return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_clear();
if (callback) callback();
case 2:
case "end":
return _context.stop();
}
}
}, _callee);
}))();
},
iterate: function iterate(iterator, callback) {
return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
var items, keys;
return _regenerator["default"].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return (0, _utils.usePromise)(get, null);
case 2:
items = _context2.sent;
keys = Object.keys(items);
keys.forEach(function (key, i) {
return iterator(items[key], key, i);
});
if (callback) callback();
case 6:
case "end":
return _context2.stop();
}
}
}, _callee2);
}))();
},
getItem: function getItem(key, callback) {
return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() {
var result;
return _regenerator["default"].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.prev = 0;
_context3.next = 3;
return (0, _utils.usePromise)(get, key);
case 3:
result = _context3.sent;
result = typeof key === 'string' ? result[key] : result;
result = result === undefined ? null : result;
if (callback) callback(null, result);
return _context3.abrupt("return", result);
case 10:
_context3.prev = 10;
_context3.t0 = _context3["catch"](0);
if (callback) callback(_context3.t0);
throw _context3.t0;
case 14:
case "end":
return _context3.stop();
}
}
}, _callee3, null, [[0, 10]]);
}))();
},
key: function key(n, callback) {
return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() {
var results, key;
return _regenerator["default"].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return (0, _utils.usePromise)(get, null);
case 2:
results = _context4.sent;
key = Object.keys(results)[n];
if (callback) callback(key);
return _context4.abrupt("return", key);
case 6:
case "end":
return _context4.stop();
}
}
}, _callee4);
}))();
},
keys: function keys(callback) {
return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5() {
var results, keys;
return _regenerator["default"].wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_context5.next = 2;
return (0, _utils.usePromise)(get, null);
case 2:
results = _context5.sent;
keys = Object.keys(results);
if (callback) callback(keys);
return _context5.abrupt("return", keys);
case 6:
case "end":
return _context5.stop();
}
}
}, _callee5);
}))();
},
length: function length(callback) {
return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6() {
var results, _Object$keys, length;
return _regenerator["default"].wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
_context6.next = 2;
return (0, _utils.usePromise)(get, null);
case 2:
results = _context6.sent;
_Object$keys = Object.keys(results), length = _Object$keys.length;
if (callback) callback(length);
return _context6.abrupt("return", length);
case 6:
case "end":
return _context6.stop();
}
}
}, _callee6);
}))();
},
removeItem: function removeItem(key, callback) {
return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7() {
return _regenerator["default"].wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
_context7.next = 2;
return (0, _utils.usePromise)(remove, key);
case 2:
if (callback) callback();
case 3:
case "end":
return _context7.stop();
}
}
}, _callee7);
}))();
},
setItem: function setItem(key, value, callback) {
return (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8() {
return _regenerator["default"].wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
_context8.next = 2;
return (0, _utils.usePromise)(set, (0, _defineProperty2["default"])({}, key, value));
case 2:
if (callback) callback();
case 3:
case "end":
return _context8.stop();
}
}
}, _callee8);
}))();
}
};
}
/***/ }),
/***/ 2:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
var __webpack_unused_export__;
var _interopRequireDefault = __webpack_require__(836);
__webpack_unused_export__ = ({
value: true
});
exports.Z = void 0;
var _driver = _interopRequireDefault(__webpack_require__(715));
var _default = (0, _driver["default"])('webExtensionLocalStorage', 'local');
exports.Z = _default;
/***/ }),
/***/ 63:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
var __webpack_unused_export__;
var _interopRequireDefault = __webpack_require__(836);
__webpack_unused_export__ = ({
value: true
});
exports.Z = void 0;
var _driver = _interopRequireDefault(__webpack_require__(715));
var _default = (0, _driver["default"])('webExtensionSyncStorage', 'sync');
exports.Z = _default;
/***/ }),
/***/ 639:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.getStorage = getStorage;
exports.usePromise = usePromise;
/**
* Need to invoke a function at runtime instead of import-time to make tests
* pass with mocked browser and chrome objects
*/
function getStorage() {
return typeof browser !== 'undefined' && browser.storage || typeof chrome !== 'undefined' && chrome.storage;
}
/**
* Need to invoke a function at runtime instead of import-time to make tests
* pass with mocked browser and chrome objects
*/
function usesPromises() {
var storage = getStorage();
try {
return storage && storage.local.get && storage.local.get() && typeof storage.local.get().then === 'function';
} catch (e) {
return false;
}
}
/**
* Converts a callback-based API to a promise based API.
* For now we assume that there is only one arg in addition to the callback
*/
function usePromise(fn, arg) {
if (usesPromises()) {
return fn(arg);
}
return new Promise(function (resolve) {
fn(arg, function () {
resolve.apply(void 0, arguments);
});
});
}
/***/ }),
/***/ 483:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
/*!
localForage -- Offline Storage, Improved
Version 1.10.0
https://localforage.github.io/localForage
(c) 2013-2017 Mozilla, Apache License 2.0
*/
(function(f){if(true){module.exports=f()}else { var g; }})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=undefined;if(!u&&a)return require(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw (f.code="MODULE_NOT_FOUND", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=undefined;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
(function (global){
'use strict';
var Mutation = global.MutationObserver || global.WebKitMutationObserver;
var scheduleDrain;
{
if (Mutation) {
var called = 0;
var observer = new Mutation(nextTick);
var element = global.document.createTextNode('');
observer.observe(element, {
characterData: true
});
scheduleDrain = function () {
element.data = (called = ++called % 2);
};
} else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
var channel = new global.MessageChannel();
channel.port1.onmessage = nextTick;
scheduleDrain = function () {
channel.port2.postMessage(0);
};
} else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
scheduleDrain = function () {
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var scriptEl = global.document.createElement('script');
scriptEl.onreadystatechange = function () {
nextTick();
scriptEl.onreadystatechange = null;
scriptEl.parentNode.removeChild(scriptEl);
scriptEl = null;
};
global.document.documentElement.appendChild(scriptEl);
};
} else {
scheduleDrain = function () {
setTimeout(nextTick, 0);
};
}
}
var draining;
var queue = [];
//named nextTick for less confusing stack traces
function nextTick() {
draining = true;
var i, oldQueue;
var len = queue.length;
while (len) {
oldQueue = queue;
queue = [];
i = -1;
while (++i < len) {
oldQueue[i]();
}
len = queue.length;
}
draining = false;
}
module.exports = immediate;
function immediate(task) {
if (queue.push(task) === 1 && !draining) {
scheduleDrain();
}
}
}).call(this,typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],2:[function(_dereq_,module,exports){
'use strict';
var immediate = _dereq_(1);
/* istanbul ignore next */
function INTERNAL() {}
var handlers = {};
var REJECTED = ['REJECTED'];
var FULFILLED = ['FULFILLED'];
var PENDING = ['PENDING'];
module.exports = Promise;
function Promise(resolver) {
if (typeof resolver !== 'function') {
throw new TypeError('resolver must be a function');
}
this.state = PENDING;
this.queue = [];
this.outcome = void 0;
if (resolver !== INTERNAL) {
safelyResolveThenable(this, resolver);
}
}
Promise.prototype["catch"] = function (onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.then = function (onFulfilled, onRejected) {
if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
typeof onRejected !== 'function' && this.state === REJECTED) {
return this;
}
var promise = new this.constructor(INTERNAL);
if (this.state !== PENDING) {
var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
unwrap(promise, resolver, this.outcome);
} else {
this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
}
return promise;
};
function QueueItem(promise, onFulfilled, onRejected) {
this.promise = promise;
if (typeof onFulfilled === 'function') {
this.onFulfilled = onFulfilled;
this.callFulfilled = this.otherCallFulfilled;
}
if (typeof onRejected === 'function') {
this.onRejected = onRejected;
this.callRejected = this.otherCallRejected;
}
}
QueueItem.prototype.callFulfilled = function (value) {
handlers.resolve(this.promise, value);
};
QueueItem.prototype.otherCallFulfilled = function (value) {
unwrap(this.promise, this.onFulfilled, value);
};
QueueItem.prototype.callRejected = function (value) {
handlers.reject(this.promise, value);
};
QueueItem.prototype.otherCallRejected = function (value) {
unwrap(this.promise, this.onRejected, value);
};
function unwrap(promise, func, value) {
immediate(function () {
var returnValue;
try {
returnValue = func(value);
} catch (e) {
return handlers.reject(promise, e);
}
if (returnValue === promise) {
handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
} else {
handlers.resolve(promise, returnValue);
}
});
}
handlers.resolve = function (self, value) {
var result = tryCatch(getThen, value);
if (result.status === 'error') {
return handlers.reject(self, result.value);
}
var thenable = result.value;
if (thenable) {
safelyResolveThenable(self, thenable);
} else {
self.state = FULFILLED;
self.outcome = value;
var i = -1;
var len = self.queue.length;
while (++i < len) {
self.queue[i].callFulfilled(value);
}
}
return self;
};
handlers.reject = function (self, error) {
self.state = REJECTED;
self.outcome = error;
var i = -1;
var len = self.queue.length;
while (++i < len) {
self.queue[i].callRejected(error);
}
return self;
};
function getThen(obj) {
// Make sure we only access the accessor once as required by the spec
var then = obj && obj.then;
if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
return function appyThen() {
then.apply(obj, arguments);
};
}
}
function safelyResolveThenable(self, thenable) {
// Either fulfill, reject or reject with error
var called = false;
function onError(value) {
if (called) {
return;
}
called = true;
handlers.reject(self, value);
}
function onSuccess(value) {
if (called) {
return;
}
called = true;
handlers.resolve(self, value);
}
function tryToUnwrap() {
thenable(onSuccess, onError);
}
var result = tryCatch(tryToUnwrap);
if (result.status === 'error') {
onError(result.value);
}
}
function tryCatch(func, value) {
var out = {};
try {
out.value = func(value);
out.status = 'success';
} catch (e) {
out.status = 'error';
out.value = e;
}
return out;
}
Promise.resolve = resolve;
function resolve(value) {
if (value instanceof this) {
return value;
}
return handlers.resolve(new this(INTERNAL), value);
}
Promise.reject = reject;
function reject(reason) {
var promise = new this(INTERNAL);
return handlers.reject(promise, reason);
}
Promise.all = all;
function all(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== '[object Array]') {
return this.reject(new TypeError('must be an array'));
}
var len = iterable.length;
var called = false;
if (!len) {
return this.resolve([]);
}
var values = new Array(len);
var resolved = 0;
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) {
allResolver(iterable[i], i);
}
return promise;
function allResolver(value, i) {
self.resolve(value).then(resolveFromAll, function (error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
});
function resolveFromAll(outValue) {
values[i] = outValue;
if (++resolved === len && !called) {
called = true;
handlers.resolve(promise, values);
}
}
}
}
Promise.race = race;
function race(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== '[object Array]') {
return this.reject(new TypeError('must be an array'));
}
var len = iterable.length;
var called = false;
if (!len) {
return this.resolve([]);
}
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) {
resolver(iterable[i]);
}
return promise;
function resolver(value) {
self.resolve(value).then(function (response) {
if (!called) {
called = true;
handlers.resolve(promise, response);
}
}, function (error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
});
}
}
},{"1":1}],3:[function(_dereq_,module,exports){
(function (global){
'use strict';
if (typeof global.Promise !== 'function') {
global.Promise = _dereq_(2);
}
}).call(this,typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"2":2}],4:[function(_dereq_,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function getIDB() {
/* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */
try {
if (typeof indexedDB !== 'undefined') {
return indexedDB;
}
if (typeof webkitIndexedDB !== 'undefined') {
return webkitIndexedDB;
}
if (typeof mozIndexedDB !== 'undefined') {
return mozIndexedDB;
}
if (typeof OIndexedDB !== 'undefined') {
return OIndexedDB;
}
if (typeof msIndexedDB !== 'undefined') {
return msIndexedDB;
}
} catch (e) {
return;
}
}
var idb = getIDB();
function isIndexedDBValid() {
try {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
if (!idb || !idb.open) {
return false;
}
// We mimic PouchDB here;
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;
// Safari <10.1 does not meet our requirements for IDB support
// (see: https://github.com/pouchdb/pouchdb/issues/5572).
// Safari 10.1 shipped with fetch, we can use that to detect it.
// Note: this creates issues with `window.fetch` polyfills and
// overrides; see:
// https://github.com/localForage/localForage/issues/856
return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&
// some outdated implementations of IDB that appear on Samsung
// and HTC Android devices <4.4 are missing IDBKeyRange
// See: https://github.com/mozilla/localForage/issues/128
// See: https://github.com/mozilla/localForage/issues/272
typeof IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
}
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function createBlob(parts, properties) {
/* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
var builder = new Builder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// This is CommonJS because lie is an external dependency, so Rollup
// can just ignore it.
if (typeof Promise === 'undefined') {
// In the "nopromises" build this will just throw if you don't have
// a global promise object, but it would throw anyway later.
_dereq_(3);
}
var Promise$1 = Promise;
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
function executeTwoCallbacks(promise, callback, errorCallback) {
if (typeof callback === 'function') {
promise.then(callback);
}
if (typeof errorCallback === 'function') {
promise["catch"](errorCallback);
}
}
function normalizeKey(key) {
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
return key;
}
function getCallback() {
if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
return arguments[arguments.length - 1];
}
}
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs = void 0;
var dbContexts = {};
var toString = Object.prototype.toString;
// Transaction Modes
var READ_ONLY = 'readonly';
var READ_WRITE = 'readwrite';
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
//
// Blobs are not supported in all versions of IndexedDB, notably
// Chrome <37 and Android <5. In those versions, storing a blob will throw.
//
// Various other blob bugs exist in Chrome v37-42 (inclusive).
// Detecting them is expensive and confusing to users, and Chrome 37-42
// is at very low usage worldwide, so we do a hacky userAgent check instead.
//
// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
// Code borrowed from PouchDB. See:
// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise$1(function (resolve) {
var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
var blob = createBlob(['']);
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.onabort = function (e) {
// If the transaction aborts now its due to not being able to
// write to the database, likely due to the disk being full
e.preventDefault();
e.stopPropagation();
resolve(false);
};
txn.oncomplete = function () {
var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
var matchedEdge = navigator.userAgent.match(/Edge\//);
// MS Edge pretends to be Chrome 42:
// https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
};
})["catch"](function () {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return Promise$1.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function (value) {
supportsBlobs = value;
return supportsBlobs;
});
}
function _deferReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Create a deferred object representing the current database operation.
var deferredOperation = {};
deferredOperation.promise = new Promise$1(function (resolve, reject) {
deferredOperation.resolve = resolve;
deferredOperation.reject = reject;
});
// Enqueue the deferred operation.
dbContext.deferredOperations.push(deferredOperation);
// Chain its promise to the database readiness.
if (!dbContext.dbReady) {
dbContext.dbReady = deferredOperation.promise;
} else {
dbContext.dbReady = dbContext.dbReady.then(function () {
return deferredOperation.promise;
});
}
}
function _advanceReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Dequeue a deferred operation.
var deferredOperation = dbContext.deferredOperations.pop();
// Resolve its promise (which is part of the database readiness
// chain of promises).
if (deferredOperation) {
deferredOperation.resolve();
return deferredOperation.promise;
}
}
function _rejectReadiness(dbInfo, err) {
var dbContext = dbContexts[dbInfo.name];
// Dequeue a deferred operation.
var deferredOperation = dbContext.deferredOperations.pop();
// Reject its promise (which is part of the database readiness
// chain of promises).
if (deferredOperation) {
deferredOperation.reject(err);
return deferredOperation.promise;
}
}
function _getConnection(dbInfo, upgradeNeeded) {
return new Promise$1(function (resolve, reject) {
dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
if (dbInfo.db) {
if (upgradeNeeded) {
_deferReadiness(dbInfo);
dbInfo.db.close();
} else {
return resolve(dbInfo.db);
}
}
var dbArgs = [dbInfo.name];
if (upgradeNeeded) {
dbArgs.push(dbInfo.version);
}
var openreq = idb.open.apply(idb, dbArgs);
if (upgradeNeeded) {
openreq.onupgradeneeded = function (e) {
var db = openreq.result;
try {
db.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// Added when support for blob shims was added
db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
} catch (ex) {
if (ex.name === 'ConstraintError') {
console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
} else {
throw ex;
}
}
};
}
openreq.onerror = function (e) {
e.preventDefault();
reject(openreq.error);
};
openreq.onsuccess = function () {
var db = openreq.result;
db.onversionchange = function (e) {
// Triggered when the database is modified (e.g. adding an objectStore) or
// deleted (even when initiated by other sessions in different tabs).
// Closing the connection here prevents those operations from being blocked.
// If the database is accessed again later by this instance, the connection
// will be reopened or the database recreated as needed.
e.target.close();
};
resolve(db);
_advanceReadiness(dbInfo);
};
});
}
function _getOriginalConnection(dbInfo) {
return _getConnection(dbInfo, false);
}
function _getUpgradedConnection(dbInfo) {
return _getConnection(dbInfo, true);
}
function _isUpgradeNeeded(dbInfo, defaultVersion) {
if (!dbInfo.db) {
return true;
}
var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
var isDowngrade = dbInfo.version < dbInfo.db.version;
var isUpgrade = dbInfo.version > dbInfo.db.version;
if (isDowngrade) {
// If the version is not the default one
// then warn for impossible downgrade.
if (dbInfo.version !== defaultVersion) {
console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
}
// Align the versions to prevent errors.
dbInfo.version = dbInfo.db.version;
}
if (isUpgrade || isNewStore) {
// If the store is new then increment the version (if needed).
// This will trigger an "upgradeneeded" event which is required
// for creating a store.
if (isNewStore) {
var incVersion = dbInfo.db.version + 1;
if (incVersion > dbInfo.version) {
dbInfo.version = incVersion;
}
}
return true;
}
return false;
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise$1(function (resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function (e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return createBlob([arrayBuff], { type: encodedBlob.type });
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Specialize the default `ready()` function by making it dependent
// on the current database operations. Thus, the driver will be actually
// ready when it's been initialized (default) *and* there are no pending
// operations on the database (initiated by some other instances).
function _fullyReady(callback) {
var self = this;
var promise = self._initReady().then(function () {
var dbContext = dbContexts[self._dbInfo.name];
if (dbContext && dbContext.dbReady) {
return dbContext.dbReady;
}
});
executeTwoCallbacks(promise, callback, callback);
return promise;
}
// Try to establish a new db connection to replace the
// current one which is broken (i.e. experiencing
// InvalidStateError while creating a transaction).
function _tryReconnect(dbInfo) {
_deferReadiness(dbInfo);
var dbContext = dbContexts[dbInfo.name];
var forages = dbContext.forages;
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
if (forage._dbInfo.db) {
forage._dbInfo.db.close();
forage._dbInfo.db = null;
}
}
dbInfo.db = null;
return _getOriginalConnection(dbInfo).then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
}).then(function (db) {
// store the latest db reference
// in case the db was upgraded
dbInfo.db = dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
forages[i]._dbInfo.db = db;
}
})["catch"](function (err) {
_rejectReadiness(dbInfo, err);
throw err;
});
}
// FF doesn't like Promises (micro-tasks) and IDDB store operations,
// so we have to do it with callbacks
function createTransaction(dbInfo, mode, callback, retries) {
if (retries === undefined) {
retries = 1;
}
try {
var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
callback(null, tx);
} catch (err) {
if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {
return Promise$1.resolve().then(function () {
if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
// increase the db version, to create the new ObjectStore
if (dbInfo.db) {
dbInfo.version = dbInfo.db.version + 1;
}
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
}).then(function () {
return _tryReconnect(dbInfo).then(function () {
createTransaction(dbInfo, mode, callback, retries - 1);
});
})["catch"](callback);
}
callback(err);
}
}
function createDbContext() {
return {
// Running localForages sharing a database.
forages: [],
// Shared database.
db: null,
// Database readiness (promise).
dbReady: null,
// Deferred operations on the database.
deferredOperations: []
};
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
// Get the current context of the database;
var dbContext = dbContexts[dbInfo.name];
// ...or create a new context.
if (!dbContext) {
dbContext = createDbContext();
// Register the new context in the global container.
dbContexts[dbInfo.name] = dbContext;
}
// Register itself as a running localForage in the current context.
dbContext.forages.push(self);
// Replace the default `ready()` function with the specialized one.
if (!self._initReady) {
self._initReady = self.ready;
self.ready = _fullyReady;
}
// Create an array of initialization states of the related localForages.
var initPromises = [];
function ignoreErrors() {
// Don't handle errors here,
// just makes sure related localForages aren't pending.
return Promise$1.resolve();
}
for (var j = 0; j < dbContext.forages.length; j++) {
var forage = dbContext.forages[j];
if (forage !== self) {
// Don't wait for itself...
initPromises.push(forage._initReady()["catch"](ignoreErrors));
}
}
// Take a snapshot of the related localForages.
var forages = dbContext.forages.slice(0);
// Initialize the connection process only when
// all the related localForages aren't pending.
return Promise$1.all(initPromises).then(function () {
dbInfo.db = dbContext.db;
// Get the connection or open a new one without upgrade.
return _getOriginalConnection(dbInfo);
}).then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
}).then(function (db) {
dbInfo.db = dbContext.db = db;
self._dbInfo = dbInfo;
// Share the final connection amongst related localForages.
for (var k = 0; k < forages.length; k++) {
var forage = forages[k];
if (forage !== self) {
// Self is already up-to-date.
forage._dbInfo.db = dbInfo.db;
forage._dbInfo.version = dbInfo.version;
}
}
});
}
function getItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function () {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function () {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
// when the iterator callback returns any
// (non-`undefined`) value, then we stop
// the iteration immediately
if (result !== void 0) {
resolve(result);
} else {
cursor["continue"]();
}
} else {
resolve();
}
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
var dbInfo;
self.ready().then(function () {
dbInfo = self._dbInfo;
if (toString.call(value) === '[object Blob]') {
return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
if (blobSupport) {
return value;
}
return _encodeBlob(value);
});
}
return value;
}).then(function (value) {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
transaction.oncomplete = function () {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `.delete()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store["delete"](key);
transaction.oncomplete = function () {
resolve();
};
transaction.onerror = function () {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function () {
resolve();
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.count();
req.onsuccess = function () {
resolve(req.result);
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var advanced = false;
var req = store.openKeyCursor();
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.openKeyCursor();
var keys = [];
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor["continue"]();
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function dropInstance(options, callback) {
callback = getCallback.apply(this, arguments);
var currentConfig = this.config();
options = typeof options !== 'function' && options || {};
if (!options.name) {
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = Promise$1.reject('Invalid arguments');
} else {
var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;
var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
forages[i]._dbInfo.db = db;
}
return db;
});
if (!options.storeName) {
promise = dbPromise.then(function (db) {
_deferReadiness(options);
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
db.close();
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
forage._dbInfo.db = null;
}
var dropDBPromise = new Promise$1(function (resolve, reject) {
var req = idb.deleteDatabase(options.name);
req.onerror = function () {
var db = req.result;
if (db) {
db.close();
}
reject(req.error);
};
req.onblocked = function () {
// Closing all open connections in onversionchange handler should prevent this situation, but if
// we do get here, it just means the request remains pending - eventually it will succeed or error
console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed');
};
req.onsuccess = function () {
var db = req.result;
if (db) {
db.close();
}
resolve(db);
};
});
return dropDBPromise.then(function (db) {
dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
var _forage = forages[i];
_advanceReadiness(_forage._dbInfo);
}
})["catch"](function (err) {
(_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
throw err;
});
});
} else {
promise = dbPromise.then(function (db) {
if (!db.objectStoreNames.contains(options.storeName)) {
return;
}
var newVersion = db.version + 1;
_deferReadiness(options);
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
db.close();
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
forage._dbInfo.db = null;
forage._dbInfo.version = newVersion;
}
var dropObjectPromise = new Promise$1(function (resolve, reject) {
var req = idb.open(options.name, newVersion);
req.onerror = function (err) {
var db = req.result;
db.close();
reject(err);
};
req.onupgradeneeded = function () {
var db = req.result;
db.deleteObjectStore(options.storeName);
};
req.onsuccess = function () {
var db = req.result;
db.close();
resolve(db);
};
});
return dropObjectPromise.then(function (db) {
dbContext.db = db;
for (var j = 0; j < forages.length; j++) {
var _forage2 = forages[j];
_forage2._dbInfo.db = db;
_advanceReadiness(_forage2._dbInfo);
}
})["catch"](function (err) {
(_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
throw err;
});
});
}
}
executeCallback(promise, callback);
return promise;
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
_support: isIndexedDBValid(),
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys,
dropInstance: dropInstance
};
function isWebSQLValid() {
return typeof openDatabase === 'function';
}
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
var toString$1 = Object.prototype.toString;
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i += 4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
/*jslint bitwise: true */
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if (bytes.length % 3 === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueType = '';
if (value) {
valueType = toString$1.call(value);
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueType === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueType === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueType === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueType === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueType === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueType === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueType === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueType === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueType === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueType === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function () {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ", value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return createBlob([buffer], { type: blobType });
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
function createDbTable(t, dbInfo, callback, errorCallback) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage$1(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
}
}
var dbInfoPromise = new Promise$1(function (resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
} catch (e) {
return reject(e);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function (t) {
createDbTable(t, dbInfo, function () {
self._dbInfo = dbInfo;
resolve();
}, function (t, error) {
reject(error);
});
}, reject);
});
dbInfo.serializer = localforageSerializer;
return dbInfoPromise;
}
function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {
t.executeSql(sqlStatement, args, callback, function (t, error) {
if (error.code === error.SYNTAX_ERR) {
t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [dbInfo.storeName], function (t, results) {
if (!results.rows.length) {
// if the table is missing (was deleted)
// re-create it table and retry
createDbTable(t, dbInfo, function () {
t.executeSql(sqlStatement, args, callback, errorCallback);
}, errorCallback);
} else {
errorCallback(t, error);
}
}, errorCallback);
} else {
errorCallback(t, error);
}
}, errorCallback);
}
function getItem$1(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
var result = results.rows.length ? results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
resolve(result);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate$1(iterator, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void 0) {
resolve(result);
return;
}
}
resolve();
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function _setItem(key, value, callback, retriesLeft) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {
resolve(originalValue);
}, function (t, error) {
reject(error);
});
}, function (sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// Try to re-run the transaction.
if (retriesLeft > 0) {
resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));
return;
}
reject(sqlError);
}
});
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem$1(key, value, callback) {
return _setItem.apply(this, [key, value, callback, 1]);
}
function removeItem$1(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear$1(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length$1(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
// Ahhh, SQL makes this one soooooo easy.
tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key$1(n, callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
var result = results.rows.length ? results.rows.item(0).key : null;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys$1(callback) {
var self = this;
var promise = new Promise$1(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function (t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
// https://www.w3.org/TR/webdatabase/#databases
// > There is no way to enumerate or delete the databases available for an origin from this API.
function getAllStoreNames(db) {
return new Promise$1(function (resolve, reject) {
db.transaction(function (t) {
t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) {
var storeNames = [];
for (var i = 0; i < results.rows.length; i++) {
storeNames.push(results.rows.item(i).name);
}
resolve({
db: db,
storeNames: storeNames
});
}, function (t, error) {
reject(error);
});
}, function (sqlError) {
reject(sqlError);
});
});
}
function dropInstance$1(options, callback) {
callback = getCallback.apply(this, arguments);
var currentConfig = this.config();
options = typeof options !== 'function' && options || {};
if (!options.name) {
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = Promise$1.reject('Invalid arguments');
} else {
promise = new Promise$1(function (resolve) {
var db;
if (options.name === currentConfig.name) {
// use the db reference of the current instance
db = self._dbInfo.db;
} else {
db = openDatabase(options.name, '', '', 0);
}
if (!options.storeName) {
// drop all database tables
resolve(getAllStoreNames(db));
} else {
resolve({
db: db,
storeNames: [options.storeName]
});
}
}).then(function (operationInfo) {
return new Promise$1(function (resolve, reject) {
operationInfo.db.transaction(function (t) {
function dropTable(storeName) {
return new Promise$1(function (resolve, reject) {
t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
}
var operations = [];
for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {
operations.push(dropTable(operationInfo.storeNames[i]));
}
Promise$1.all(operations).then(function () {
resolve();
})["catch"](function (e) {
reject(e);
});
}, function (sqlError) {
reject(sqlError);
});
});
});
}
executeCallback(promise, callback);
return promise;
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage$1,
_support: isWebSQLValid(),
iterate: iterate$1,
getItem: getItem$1,
setItem: setItem$1,
removeItem: removeItem$1,
clear: clear$1,
length: length$1,
key: key$1,
keys: keys$1,
dropInstance: dropInstance$1
};
function isLocalStorageValid() {
try {
return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&
// in IE8 typeof localStorage.setItem === 'object'
!!localStorage.setItem;
} catch (e) {
return false;
}
}
function _getKeyPrefix(options, defaultConfig) {
var keyPrefix = options.name + '/';
if (options.storeName !== defaultConfig.storeName) {
keyPrefix += options.storeName + '/';
}
return keyPrefix;
}
// Check if localStorage throws when saving an item
function checkIfLocalStorageThrows() {
var localStorageTestKey = '_localforage_support_test';
try {
localStorage.setItem(localStorageTestKey, true);
localStorage.removeItem(localStorageTestKey);
return false;
} catch (e) {
return true;
}
}
// Check if localStorage is usable and allows to save an item
// This method checks if localStorage is usable in Safari Private Browsing
// mode, or in any other case where the available quota for localStorage
// is 0 and there wasn't any saved items yet.
function _isLocalStorageUsable() {
return !checkIfLocalStorageThrows() || localStorage.length > 0;
}
// Config the localStorage backend, using options set in the config.
function _initStorage$2(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);
if (!_isLocalStorageUsable()) {
return Promise$1.reject();
}
self._dbInfo = dbInfo;
dbInfo.serializer = localforageSerializer;
return Promise$1.resolve();
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear$2(callback) {
var self = this;
var promise = self.ready().then(function () {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem$2(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate$2(iterator, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var keyPrefix = dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
// We use a dedicated iterator instead of the `i` variable below
// so other keys we fetch in localStorage aren't counted in
// the `iterationNumber` argument passed to the `iterate()`
// callback.
//
// See: github.com/mozilla/localForage/pull/435#discussion_r38061530
var iterationNumber = 1;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) !== 0) {
continue;
}
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = dbInfo.serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
if (value !== void 0) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key$2(n, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys$2(callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
var itemKey = localStorage.key(i);
if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
keys.push(itemKey.substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length$2(callback) {
var self = this;
var promise = self.keys().then(function (keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem$2(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem$2(key, value, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise$1(function (resolve, reject) {
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
try {
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function dropInstance$2(options, callback) {
callback = getCallback.apply(this, arguments);
options = typeof options !== 'function' && options || {};
if (!options.name) {
var currentConfig = this.config();
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = Promise$1.reject('Invalid arguments');
} else {
promise = new Promise$1(function (resolve) {
if (!options.storeName) {
resolve(options.name + '/');
} else {
resolve(_getKeyPrefix(options, self._defaultConfig));
}
}).then(function (keyPrefix) {
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
}
executeCallback(promise, callback);
return promise;
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage$2,
_support: isLocalStorageValid(),
iterate: iterate$2,
getItem: getItem$2,
setItem: setItem$2,
removeItem: removeItem$2,
clear: clear$2,
length: length$2,
key: key$2,
keys: keys$2,
dropInstance: dropInstance$2
};
var sameValue = function sameValue(x, y) {
return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);
};
var includes = function includes(array, searchElement) {
var len = array.length;
var i = 0;
while (i < len) {
if (sameValue(array[i], searchElement)) {
return true;
}
i++;
}
return false;
};
var isArray = Array.isArray || function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
// Drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var DefinedDrivers = {};
var DriverSupport = {};
var DefaultDrivers = {
INDEXEDDB: asyncStorage,
WEBSQL: webSQLStorage,
LOCALSTORAGE: localStorageWrapper
};
var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];
var OptionalDriverMethods = ['dropInstance'];
var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function () {
var _args = arguments;
return localForageInstance.ready().then(function () {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var _key in arg) {
if (arg.hasOwnProperty(_key)) {
if (isArray(arg[_key])) {
arguments[0][_key] = arg[_key].slice();
} else {
arguments[0][_key] = arg[_key];
}
}
}
}
}
return arguments[0];
}
var LocalForage = function () {
function LocalForage(options) {
_classCallCheck(this, LocalForage);
for (var driverTypeKey in DefaultDrivers) {
if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
var driver = DefaultDrivers[driverTypeKey];
var driverName = driver._driver;
this[driverTypeKey] = driverName;
if (!DefinedDrivers[driverName]) {
// we don't need to wait for the promise,
// since the default drivers can be defined
// in a blocking manner
this.defineDriver(driver);
}
}
}
this._defaultConfig = extend({}, DefaultConfig);
this._config = extend({}, this._defaultConfig, options);
this._driverSet = null;
this._initDriver = null;
this._ready = false;
this._dbInfo = null;
this._wrapLibraryMethodsWithReady();
this.setDriver(this._config.driver)["catch"](function () {});
}
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function config(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " + 'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
if (i === 'version' && typeof options[i] !== 'number') {
return new Error('Database version must be a number.');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
return this.setDriver(this._config.driver);
}
return true;
} else if (typeof options === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
var promise = new Promise$1(function (resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
var driverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0, len = driverMethods.length; i < len; i++) {
var driverMethodName = driverMethods[i];
// when the property is there,
// it should be a method even when optional
var isRequired = !includes(OptionalDriverMethods, driverMethodName);
if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {
reject(complianceError);
return;
}
}
var configureMissingMethods = function configureMissingMethods() {
var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {
return function () {
var error = new Error('Method ' + methodName + ' is not implemented by the current driver');
var promise = Promise$1.reject(error);
executeCallback(promise, arguments[arguments.length - 1]);
return promise;
};
};
for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
var optionalDriverMethod = OptionalDriverMethods[_i];
if (!driverObject[optionalDriverMethod]) {
driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
}
}
};
configureMissingMethods();
var setDriverSupport = function setDriverSupport(support) {
if (DefinedDrivers[driverName]) {
console.info('Redefining LocalForage driver: ' + driverName);
}
DefinedDrivers[driverName] = driverObject;
DriverSupport[driverName] = support;
// don't use a then, so that we can define
// drivers that have simple _support methods
// in a blocking manner
resolve();
};
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
driverObject._support().then(setDriverSupport, reject);
} else {
setDriverSupport(!!driverObject._support);
}
} else {
setDriverSupport(true);
}
} catch (e) {
reject(e);
}
});
executeTwoCallbacks(promise, callback, errorCallback);
return promise;
};
LocalForage.prototype.driver = function driver() {
return this._driver || null;
};
LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));
executeTwoCallbacks(getDriverPromise, callback, errorCallback);
return getDriverPromise;
};
LocalForage.prototype.getSerializer = function getSerializer(callback) {
var serializerPromise = Promise$1.resolve(localforageSerializer);
executeTwoCallbacks(serializerPromise, callback);
return serializerPromise;
};
LocalForage.prototype.ready = function ready(callback) {
var self = this;
var promise = self._driverSet.then(function () {
if (self._ready === null) {
self._ready = self._initDriver();
}
return self._ready;
});
executeTwoCallbacks(promise, callback, callback);
return promise;
};
LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
var self = this;
if (!isArray(drivers)) {
drivers = [drivers];
}
var supportedDrivers = this._getSupportedDrivers(drivers);
function setDriverToConfig() {
self._config.driver = self.driver();
}
function extendSelfWithDriver(driver) {
self._extend(driver);
setDriverToConfig();
self._ready = self._initStorage(self._config);
return self._ready;
}
function initDriver(supportedDrivers) {
return function () {
var currentDriverIndex = 0;
function driverPromiseLoop() {
while (currentDriverIndex < supportedDrivers.length) {
var driverName = supportedDrivers[currentDriverIndex];
currentDriverIndex++;
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop);
}
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise$1.reject(error);
return self._driverSet;
}
return driverPromiseLoop();
};
}
// There might be a driver initialization in progress
// so wait for it to finish in order to avoid a possible
// race condition to set _dbInfo
var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () {
return Promise$1.resolve();
}) : Promise$1.resolve();
this._driverSet = oldDriverSetDone.then(function () {
var driverName = supportedDrivers[0];
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function (driver) {
self._driver = driver._driver;
setDriverToConfig();
self._wrapLibraryMethodsWithReady();
self._initDriver = initDriver(supportedDrivers);
});
})["catch"](function () {
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise$1.reject(error);
return self._driverSet;
});
executeTwoCallbacks(this._driverSet, callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function supports(driverName) {
return !!DriverSupport[driverName];
};
LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
var supportedDrivers = [];
for (var i = 0, len = drivers.length; i < len; i++) {
var driverName = drivers[i];
if (this.supports(driverName)) {
supportedDrivers.push(driverName);
}
}
return supportedDrivers;
};
LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0, len = LibraryMethods.length; i < len; i++) {
callWhenReady(this, LibraryMethods[i]);
}
};
LocalForage.prototype.createInstance = function createInstance(options) {
return new LocalForage(options);
};
return LocalForage;
}();
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
var localforage_js = new LocalForage();
module.exports = localforage_js;
},{"3":3}]},{},[4])(4)
});
/***/ }),
/***/ 271:
/***/ ((module, exports, __webpack_require__) => {
var __WEBPACK_AMD_DEFINE_RESULT__;/*!
* Sizzle CSS Selector Engine v2.3.10
* https://sizzlejs.com/
*
* Copyright JS Foundation and other contributors
* Released under the MIT license
* https://js.foundation/
*
* Date: 2023-02-14
*/
( function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + 1 * new Date(),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
nonnativeSelectorCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// Instance methods
hasOwn = ( {} ).hasOwnProperty,
arr = [],
pop = arr.pop,
pushNative = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf as it's faster than native
// https://jsperf.com/thor-indexof-vs-for/5
indexOf = function( list, elem ) {
var i = 0,
len = list.length;
for ( ; i < len; i++ ) {
if ( list[ i ] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" +
"ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// https://www.w3.org/TR/css-syntax-3/#ident-token-diagram
identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace +
"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5]
// or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" +
whitespace + "*\\]",
pseudos = ":(" + identifier + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = new RegExp( whitespace + "+", "g" ),
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" +
whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rleadingCombinator = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace +
"*" ),
rdescend = new RegExp( whitespace + "|>" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + identifier + ")" ),
"CLASS": new RegExp( "^\\.(" + identifier + ")" ),
"TAG": new RegExp( "^(" + identifier + "|[*])" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" +
whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" +
whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace +
"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
"*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rhtml = /HTML$/i,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
// CSS escapes
// http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ),
funescape = function( escape, nonHex ) {
var high = "0x" + escape.slice( 1 ) - 0x10000;
return nonHex ?
// Strip the backslash prefix from a non-hex escape sequence
nonHex :
// Replace a hexadecimal escape sequence with the encoded Unicode code point
// Support: IE <=11+
// For values outside the Basic Multilingual Plane (BMP), manually construct a
// surrogate pair
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
},
// CSS string/identifier serialization
// https://drafts.csswg.org/cssom/#common-serializing-idioms
rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,
fcssescape = function( ch, asCodePoint ) {
if ( asCodePoint ) {
// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
if ( ch === "\0" ) {
return "\uFFFD";
}
// Control characters and (dependent upon position) numbers get escaped as code points
return ch.slice( 0, -1 ) + "\\" +
ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
}
// Other potentially-special ASCII characters get backslash-escaped
return "\\" + ch;
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
},
inDisabledFieldset = addCombinator(
function( elem ) {
return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset";
},
{ dir: "parentNode", next: "legend" }
);
// Optimize for push.apply( _, NodeList )
try {
push.apply(
( arr = slice.call( preferredDoc.childNodes ) ),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
// eslint-disable-next-line no-unused-expressions
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
pushNative.apply( target, slice.call( els ) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( ( target[ j++ ] = els[ i++ ] ) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var m, i, elem, nid, match, groups, newSelector,
newContext = context && context.ownerDocument,
// nodeType defaults to 9, since context defaults to document
nodeType = context ? context.nodeType : 9;
results = results || [];
// Return early from calls with invalid selector or context
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
// Try to shortcut find operations (as opposed to filters) in HTML documents
if ( !seed ) {
setDocument( context );
context = context || document;
if ( documentIsHTML ) {
// If the selector is sufficiently simple, try using a "get*By*" DOM method
// (excepting DocumentFragment context, where the methods don't exist)
if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) {
// ID selector
if ( ( m = match[ 1 ] ) ) {
// Document context
if ( nodeType === 9 ) {
if ( ( elem = context.getElementById( m ) ) ) {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
// Element context
} else {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( newContext && ( elem = newContext.getElementById( m ) ) &&
contains( context, elem ) &&
elem.id === m ) {
results.push( elem );
return results;
}
}
// Type selector
} else if ( match[ 2 ] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Class selector
} else if ( ( m = match[ 3 ] ) && support.getElementsByClassName &&
context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// Take advantage of querySelectorAll
if ( support.qsa &&
!nonnativeSelectorCache[ selector + " " ] &&
( !rbuggyQSA || !rbuggyQSA.test( selector ) ) &&
// Support: IE 8 only
// Exclude object elements
( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) {
newSelector = selector;
newContext = context;
// qSA considers elements outside a scoping root when evaluating child or
// descendant combinators, which is not what we want.
// In such cases, we work around the behavior by prefixing every selector in the
// list with an ID selector referencing the scope context.
// The technique has to be used as well when a leading combinator is used
// as such selectors are not recognized by querySelectorAll.
// Thanks to Andrew Dupont for this technique.
if ( nodeType === 1 &&
( rdescend.test( selector ) || rleadingCombinator.test( selector ) ) ) {
// Expand context for sibling selectors
newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
context;
// We can use :scope instead of the ID hack if the browser
// supports it & if we're not changing the context.
if ( newContext !== context || !support.scope ) {
// Capture the context ID, setting it first if necessary
if ( ( nid = context.getAttribute( "id" ) ) ) {
nid = nid.replace( rcssescape, fcssescape );
} else {
context.setAttribute( "id", ( nid = expando ) );
}
}
// Prefix every selector in the list
groups = tokenize( selector );
i = groups.length;
while ( i-- ) {
groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " +
toSelector( groups[ i ] );
}
newSelector = groups.join( "," );
}
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch ( qsaError ) {
nonnativeSelectorCache( selector, true );
} finally {
if ( nid === expando ) {
context.removeAttribute( "id" );
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {function(string, object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return ( cache[ key + " " ] = value );
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created element and returns a boolean result
*/
function assert( fn ) {
var el = document.createElement( "fieldset" );
try {
return !!fn( el );
} catch ( e ) {
return false;
} finally {
// Remove from its parent by default
if ( el.parentNode ) {
el.parentNode.removeChild( el );
}
// release memory in IE
el = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split( "|" ),
i = arr.length;
while ( i-- ) {
Expr.attrHandle[ arr[ i ] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
a.sourceIndex - b.sourceIndex;
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( ( cur = cur.nextSibling ) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return ( name === "input" || name === "button" ) && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for :enabled/:disabled
* @param {Boolean} disabled true for :disabled; false for :enabled
*/
function createDisabledPseudo( disabled ) {
// Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
return function( elem ) {
// Only certain elements can match :enabled or :disabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
if ( "form" in elem ) {
// Check for inherited disabledness on relevant non-disabled elements:
// * listed form-associated elements in a disabled fieldset
// https://html.spec.whatwg.org/multipage/forms.html#category-listed
// https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
// * option elements in a disabled optgroup
// https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
// All such elements have a "form" property.
if ( elem.parentNode && elem.disabled === false ) {
// Option elements defer to a parent optgroup if present
if ( "label" in elem ) {
if ( "label" in elem.parentNode ) {
return elem.parentNode.disabled === disabled;
} else {
return elem.disabled === disabled;
}
}
// Support: IE 6 - 11
// Use the isDisabled shortcut property to check for disabled fieldset ancestors
return elem.isDisabled === disabled ||
// Where there is no isDisabled, check manually
/* jshint -W018 */
elem.isDisabled !== !disabled &&
inDisabledFieldset( elem ) === disabled;
}
return elem.disabled === disabled;
// Try to winnow out elements that can't be disabled before trusting the disabled property.
// Some victims get caught in our net (label, legend, menu, track), but it shouldn't
// even exist on them, let alone have a boolean value.
} else if ( "label" in elem ) {
return elem.disabled === disabled;
}
// Remaining elements are neither :enabled nor :disabled
return false;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction( function( argument ) {
argument = +argument;
return markFunction( function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ ( j = matchIndexes[ i ] ) ] ) {
seed[ j ] = !( matches[ j ] = seed[ j ] );
}
}
} );
} );
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== "undefined" && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
var namespace = elem && elem.namespaceURI,
docElem = elem && ( elem.ownerDocument || elem ).documentElement;
// Support: IE <=8
// Assume HTML when documentElement doesn't yet exist, such as inside loading iframes
// https://bugs.jquery.com/ticket/4833
return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" );
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare, subWindow,
doc = node ? node.ownerDocument || node : preferredDoc;
// Return early if doc is invalid or already selected
// Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
// eslint-disable-next-line eqeqeq
if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Update global variables
document = doc;
docElem = document.documentElement;
documentIsHTML = !isXML( document );
// Support: IE 9 - 11+, Edge 12 - 18+
// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
// Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
// eslint-disable-next-line eqeqeq
if ( preferredDoc != document &&
( subWindow = document.defaultView ) && subWindow.top !== subWindow ) {
// Support: IE 11, Edge
if ( subWindow.addEventListener ) {
subWindow.addEventListener( "unload", unloadHandler, false );
// Support: IE 9 - 10 only
} else if ( subWindow.attachEvent ) {
subWindow.attachEvent( "onunload", unloadHandler );
}
}
// Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only,
// Safari 4 - 5 only, Opera <=11.6 - 12.x only
// IE/Edge & older browsers don't support the :scope pseudo-class.
// Support: Safari 6.0 only
// Safari 6.0 supports :scope but it's an alias of :root there.
support.scope = assert( function( el ) {
docElem.appendChild( el ).appendChild( document.createElement( "div" ) );
return typeof el.querySelectorAll !== "undefined" &&
!el.querySelectorAll( ":scope fieldset div" ).length;
} );
// Support: Chrome 105 - 110+, Safari 15.4 - 16.3+
// Make sure the the `:has()` argument is parsed unforgivingly.
// We include `*` in the test to detect buggy implementations that are
// _selectively_ forgiving (specifically when the list includes at least
// one valid selector).
// Note that we treat complete lack of support for `:has()` as if it were
// spec-compliant support, which is fine because use of `:has()` in such
// environments will fail in the qSA path and fall back to jQuery traversal
// anyway.
support.cssHas = assert( function() {
try {
document.querySelector( ":has(*,:jqfake)" );
return false;
} catch ( e ) {
return true;
}
} );
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert( function( el ) {
el.className = "i";
return !el.getAttribute( "className" );
} );
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert( function( el ) {
el.appendChild( document.createComment( "" ) );
return !el.getElementsByTagName( "*" ).length;
} );
// Support: IE<9
support.getElementsByClassName = rnative.test( document.getElementsByClassName );
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programmatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert( function( el ) {
docElem.appendChild( el ).id = expando;
return !document.getElementsByName || !document.getElementsByName( expando ).length;
} );
// ID filter and find
if ( support.getById ) {
Expr.filter[ "ID" ] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute( "id" ) === attrId;
};
};
Expr.find[ "ID" ] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var elem = context.getElementById( id );
return elem ? [ elem ] : [];
}
};
} else {
Expr.filter[ "ID" ] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== "undefined" &&
elem.getAttributeNode( "id" );
return node && node.value === attrId;
};
};
// Support: IE 6 - 7 only
// getElementById is not reliable as a find shortcut
Expr.find[ "ID" ] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var node, i, elems,
elem = context.getElementById( id );
if ( elem ) {
// Verify the id attribute
node = elem.getAttributeNode( "id" );
if ( node && node.value === id ) {
return [ elem ];
}
// Fall back on getElementsByName
elems = context.getElementsByName( id );
i = 0;
while ( ( elem = elems[ i++ ] ) ) {
node = elem.getAttributeNode( "id" );
if ( node && node.value === id ) {
return [ elem ];
}
}
}
return [];
}
};
}
// Tag
Expr.find[ "TAG" ] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( tag );
// DocumentFragment nodes don't have gEBTN
} else if ( support.qsa ) {
return context.querySelectorAll( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( ( elem = results[ i++ ] ) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See https://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert( function( el ) {
var input;
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// https://bugs.jquery.com/ticket/12359
docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\r\\' msallowcapture=''>" +
"<option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !el.querySelectorAll( "[selected]" ).length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
rbuggyQSA.push( "~=" );
}
// Support: IE 11+, Edge 15 - 18+
// IE 11/Edge don't find elements on a `[name='']` query in some cases.
// Adding a temporary attribute to the document before the selection works
// around the issue.
// Interestingly, IE 10 & older don't seem to have the issue.
input = document.createElement( "input" );
input.setAttribute( "name", "" );
el.appendChild( input );
if ( !el.querySelectorAll( "[name='']" ).length ) {
rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" +
whitespace + "*(?:''|\"\")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !el.querySelectorAll( ":checked" ).length ) {
rbuggyQSA.push( ":checked" );
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibling-combinator selector` fails
if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push( ".#.+[+~]" );
}
// Support: Firefox <=3.6 - 5 only
// Old Firefox doesn't throw on a badly-escaped identifier.
el.querySelectorAll( "\\\f" );
rbuggyQSA.push( "[\\r\\n\\f]" );
} );
assert( function( el ) {
el.innerHTML = "<a href='' disabled='disabled'></a>" +
"<select disabled='disabled'><option/></select>";
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = document.createElement( "input" );
input.setAttribute( "type", "hidden" );
el.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( el.querySelectorAll( "[name=d]" ).length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( el.querySelectorAll( ":enabled" ).length !== 2 ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Support: IE9-11+
// IE's :disabled selector does not pick up the children of disabled fieldsets
docElem.appendChild( el ).disabled = true;
if ( el.querySelectorAll( ":disabled" ).length !== 2 ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Support: Opera 10 - 11 only
// Opera 10-11 does not throw on post-comma invalid pseudos
el.querySelectorAll( "*,:x" );
rbuggyQSA.push( ",.*:" );
} );
}
if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector ) ) ) ) {
assert( function( el ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( el, "*" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( el, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
} );
}
if ( !support.cssHas ) {
// Support: Chrome 105 - 110+, Safari 15.4 - 16.3+
// Our regular `try-catch` mechanism fails to detect natively-unsupported
// pseudo-classes inside `:has()` (such as `:has(:contains("Foo"))`)
// in browsers that parse the `:has()` argument as a forgiving selector list.
// https://drafts.csswg.org/selectors/#relational now requires the argument
// to be parsed unforgivingly, but browsers have not yet fully adjusted.
rbuggyQSA.push( ":has" );
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully self-exclusive
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
// Support: IE <9 only
// IE doesn't have `contains` on `document` so we need to check for
// `documentElement` presence.
// We need to fall back to `a` when `documentElement` is missing
// as `ownerDocument` of elements within `<template/>` may have
// a null one - a default behavior of all modern browsers.
var adown = a.nodeType === 9 && a.documentElement || a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
) );
} :
function( a, b ) {
if ( b ) {
while ( ( b = b.parentNode ) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
// Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
// eslint-disable-next-line eqeqeq
compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) {
// Choose the first element that is related to our preferred document
// Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
// eslint-disable-next-line eqeqeq
if ( a == document || a.ownerDocument == preferredDoc &&
contains( preferredDoc, a ) ) {
return -1;
}
// Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
// eslint-disable-next-line eqeqeq
if ( b == document || b.ownerDocument == preferredDoc &&
contains( preferredDoc, b ) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
// Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
/* eslint-disable eqeqeq */
return a == document ? -1 :
b == document ? 1 :
/* eslint-enable eqeqeq */
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( ( cur = cur.parentNode ) ) {
ap.unshift( cur );
}
cur = b;
while ( ( cur = cur.parentNode ) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[ i ] === bp[ i ] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[ i ], bp[ i ] ) :
// Otherwise nodes in our document sort first
// Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
/* eslint-disable eqeqeq */
ap[ i ] == preferredDoc ? -1 :
bp[ i ] == preferredDoc ? 1 :
/* eslint-enable eqeqeq */
0;
};
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
setDocument( elem );
if ( support.matchesSelector && documentIsHTML &&
!nonnativeSelectorCache[ expr + " " ] &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch ( e ) {
nonnativeSelectorCache( expr, true );
}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
// Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
// eslint-disable-next-line eqeqeq
if ( ( context.ownerDocument || context ) != document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
// Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
// eslint-disable-next-line eqeqeq
if ( ( elem.ownerDocument || elem ) != document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
( val = elem.getAttributeNode( name ) ) && val.specified ?
val.value :
null;
};
Sizzle.escape = function( sel ) {
return ( sel + "" ).replace( rcssescape, fcssescape );
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( ( elem = results[ i++ ] ) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( ( node = elem[ i++ ] ) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[ 1 ] = match[ 1 ].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[ 3 ] = ( match[ 3 ] || match[ 4 ] ||
match[ 5 ] || "" ).replace( runescape, funescape );
if ( match[ 2 ] === "~=" ) {
match[ 3 ] = " " + match[ 3 ] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[ 1 ] = match[ 1 ].toLowerCase();
if ( match[ 1 ].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[ 3 ] ) {
Sizzle.error( match[ 0 ] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[ 4 ] = +( match[ 4 ] ?
match[ 5 ] + ( match[ 6 ] || 1 ) :
2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) );
match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" );
// other types prohibit arguments
} else if ( match[ 3 ] ) {
Sizzle.error( match[ 0 ] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[ 6 ] && match[ 2 ];
if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[ 3 ] ) {
match[ 2 ] = match[ 4 ] || match[ 5 ] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
( excess = tokenize( unquoted, true ) ) &&
// advance to the next closing parenthesis
( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) {
// excess is a negative index
match[ 0 ] = match[ 0 ].slice( 0, excess );
match[ 2 ] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() {
return true;
} :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
( pattern = new RegExp( "(^|" + whitespace +
")" + className + "(" + whitespace + "|$)" ) ) && classCache(
className, function( elem ) {
return pattern.test(
typeof elem.className === "string" && elem.className ||
typeof elem.getAttribute !== "undefined" &&
elem.getAttribute( "class" ) ||
""
);
} );
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
/* eslint-disable max-len */
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
/* eslint-enable max-len */
};
},
"CHILD": function( type, what, _argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, _context, xml ) {
var cache, uniqueCache, outerCache, node, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType,
diff = false;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( ( node = node[ dir ] ) ) {
if ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
// ...in a gzip-friendly way
node = parent;
outerCache = node[ expando ] || ( node[ expando ] = {} );
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
( outerCache[ node.uniqueID ] = {} );
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex && cache[ 2 ];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( ( node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
( diff = nodeIndex = 0 ) || start.pop() ) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
} else {
// Use previously-cached element index if available
if ( useCache ) {
// ...in a gzip-friendly way
node = elem;
outerCache = node[ expando ] || ( node[ expando ] = {} );
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
( outerCache[ node.uniqueID ] = {} );
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex;
}
// xml :nth-child(...)
// or :nth-last-child(...) or :nth(-last)?-of-type(...)
if ( diff === false ) {
// Use the same loop as above to seek `elem` from the start
while ( ( node = ++nodeIndex && node && node[ dir ] ||
( diff = nodeIndex = 0 ) || start.pop() ) ) {
if ( ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) &&
++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
outerCache = node[ expando ] ||
( node[ expando ] = {} );
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
( outerCache[ node.uniqueID ] = {} );
uniqueCache[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction( function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf( seed, matched[ i ] );
seed[ idx ] = !( matches[ idx ] = matched[ i ] );
}
} ) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction( function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction( function( seed, matches, _context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( ( elem = unmatched[ i ] ) ) {
seed[ i ] = !( matches[ i ] = elem );
}
}
} ) :
function( elem, _context, xml ) {
input[ 0 ] = elem;
matcher( input, null, xml, results );
// Don't keep the element (issue #299)
input[ 0 ] = null;
return !results.pop();
};
} ),
"has": markFunction( function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
} ),
"contains": markFunction( function( text ) {
text = text.replace( runescape, funescape );
return function( elem ) {
return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1;
};
} ),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test( lang || "" ) ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( ( elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( ( elem = elem.parentNode ) && elem.nodeType === 1 );
return false;
};
} ),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement &&
( !document.hasFocus || document.hasFocus() ) &&
!!( elem.type || elem.href || ~elem.tabIndex );
},
// Boolean properties
"enabled": createDisabledPseudo( false ),
"disabled": createDisabledPseudo( true ),
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return ( nodeName === "input" && !!elem.checked ) ||
( nodeName === "option" && !!elem.selected );
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
// eslint-disable-next-line no-unused-expressions
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos[ "empty" ]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE <10 only
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( ( attr = elem.getAttribute( "type" ) ) == null ||
attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo( function() {
return [ 0 ];
} ),
"last": createPositionalPseudo( function( _matchIndexes, length ) {
return [ length - 1 ];
} ),
"eq": createPositionalPseudo( function( _matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
} ),
"even": createPositionalPseudo( function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
} ),
"odd": createPositionalPseudo( function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
} ),
"lt": createPositionalPseudo( function( matchIndexes, length, argument ) {
var i = argument < 0 ?
argument + length :
argument > length ?
length :
argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
} ),
"gt": createPositionalPseudo( function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
} )
}
};
Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || ( match = rcomma.exec( soFar ) ) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[ 0 ].length ) || soFar;
}
groups.push( ( tokens = [] ) );
}
matched = false;
// Combinators
if ( ( match = rleadingCombinator.exec( soFar ) ) ) {
matched = match.shift();
tokens.push( {
value: matched,
// Cast descendant combinators to space
type: match[ 0 ].replace( rtrim, " " )
} );
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] ||
( match = preFilters[ type ]( match ) ) ) ) {
matched = match.shift();
tokens.push( {
value: matched,
type: type,
matches: match
} );
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
};
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[ i ].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
skip = combinator.next,
key = skip || dir,
checkNonElements = base && key === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( ( elem = elem[ dir ] ) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
return false;
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, uniqueCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
if ( xml ) {
while ( ( elem = elem[ dir ] ) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( ( elem = elem[ dir ] ) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || ( elem[ expando ] = {} );
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ elem.uniqueID ] ||
( outerCache[ elem.uniqueID ] = {} );
if ( skip && skip === elem.nodeName.toLowerCase() ) {
elem = elem[ dir ] || elem;
} else if ( ( oldCache = uniqueCache[ key ] ) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return ( newCache[ 2 ] = oldCache[ 2 ] );
} else {
// Reuse newcache so results back-propagate to previous elements
uniqueCache[ key ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) {
return true;
}
}
}
}
}
return false;
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[ i ]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[ 0 ];
}
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[ i ], results );
}
return results;
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( ( elem = unmatched[ i ] ) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction( function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts(
selector || "*",
context.nodeType ? [ context ] : context,
[]
),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( ( elem = temp[ i ] ) ) {
matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem );
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( ( elem = matcherOut[ i ] ) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( ( matcherIn[ i ] = elem ) );
}
}
postFinder( null, ( matcherOut = [] ), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( ( elem = matcherOut[ i ] ) &&
( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) {
seed[ temp ] = !( results[ temp ] = elem );
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
} );
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[ 0 ].type ],
implicitRelative = leadingRelative || Expr.relative[ " " ],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
( checkContext = context ).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
// Avoid hanging onto element (issue #299)
checkContext = null;
return ret;
} ];
for ( ; i < len; i++ ) {
if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) {
matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
} else {
matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[ j ].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens
.slice( 0, i - 1 )
.concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } )
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ),
len = elems.length;
if ( outermost ) {
// Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
// eslint-disable-next-line eqeqeq
outermostContext = context == document || context || outermost;
}
// Add elements passing elementMatchers directly to results
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
// Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
// eslint-disable-next-line eqeqeq
if ( !context && elem.ownerDocument != document ) {
setDocument( elem );
xml = !documentIsHTML;
}
while ( ( matcher = elementMatchers[ j++ ] ) ) {
if ( matcher( elem, context || document, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( ( elem = !matcher && elem ) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// `i` is now the count of elements visited above, and adding it to `matchedCount`
// makes the latter nonnegative.
matchedCount += i;
// Apply set filters to unmatched elements
// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
// no element matchers and no seed.
// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
// case, which will result in a "00" `matchedCount` that differs from `i` but is also
// numerically zero.
if ( bySet && i !== matchedCount ) {
j = 0;
while ( ( matcher = setMatchers[ j++ ] ) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !( unmatched[ i ] || setMatched[ i ] ) ) {
setMatched[ i ] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[ i ] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache(
selector,
matcherFromGroupMatchers( elementMatchers, setMatchers )
);
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( ( selector = compiled.selector || selector ) );
results = results || [];
// Try to minimize operations if there is only one selector in the list and no seed
// (the latter of which guarantees us context)
if ( match.length === 1 ) {
// Reduce context if the leading compound selector is an ID
tokens = match[ 0 ] = match[ 0 ].slice( 0 );
if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" &&
context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) {
context = ( Expr.find[ "ID" ]( token.matches[ 0 ]
.replace( runescape, funescape ), context ) || [] )[ 0 ];
if ( !context ) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[ i ];
// Abort if we hit a combinator
if ( Expr.relative[ ( type = token.type ) ] ) {
break;
}
if ( ( find = Expr.find[ type ] ) ) {
// Search, expanding context for leading sibling combinators
if ( ( seed = find(
token.matches[ 0 ].replace( runescape, funescape ),
rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) ||
context
) ) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
!context || rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando;
// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert( function( el ) {
// Should return 1, but returns 4 (following)
return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1;
} );
// Support: IE<8
// Prevent attribute/property "interpolation"
// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert( function( el ) {
el.innerHTML = "<a href='#'></a>";
return el.firstChild.getAttribute( "href" ) === "#";
} ) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
} );
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert( function( el ) {
el.innerHTML = "<input/>";
el.firstChild.setAttribute( "value", "" );
return el.firstChild.getAttribute( "value" ) === "";
} ) ) {
addHandle( "value", function( elem, _name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
} );
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert( function( el ) {
return el.getAttribute( "disabled" ) == null;
} ) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
( val = elem.getAttributeNode( name ) ) && val.specified ?
val.value :
null;
}
} );
}
// EXPOSE
var _sizzle = window.Sizzle;
Sizzle.noConflict = function() {
if ( window.Sizzle === Sizzle ) {
window.Sizzle = _sizzle;
}
return Sizzle;
};
if ( true ) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
return Sizzle;
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
// Sizzle requires that there be a global window in Common-JS like environments
} else {}
// EXPOSE
} )( window );
/***/ }),
/***/ 156:
/***/ ((module) => {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/***/ 416:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
var toPropertyKey = __webpack_require__(62);
function _defineProperty(obj, key, value) {
key = toPropertyKey(key);
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/***/ 836:
/***/ ((module) => {
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/***/ 61:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
var _typeof = (__webpack_require__(698)["default"]);
function _regeneratorRuntime() {
"use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
return exports;
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
var exports = {},
Op = Object.prototype,
hasOwn = Op.hasOwnProperty,
defineProperty = Object.defineProperty || function (obj, key, desc) {
obj[key] = desc.value;
},
$Symbol = "function" == typeof Symbol ? Symbol : {},
iteratorSymbol = $Symbol.iterator || "@@iterator",
asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
return Object.defineProperty(obj, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}), obj[key];
}
try {
define({}, "");
} catch (err) {
define = function define(obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
generator = Object.create(protoGenerator.prototype),
context = new Context(tryLocsList || []);
return defineProperty(generator, "_invoke", {
value: makeInvokeMethod(innerFn, self, context)
}), generator;
}
function tryCatch(fn, obj, arg) {
try {
return {
type: "normal",
arg: fn.call(obj, arg)
};
} catch (err) {
return {
type: "throw",
arg: err
};
}
}
exports.wrap = wrap;
var ContinueSentinel = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var IteratorPrototype = {};
define(IteratorPrototype, iteratorSymbol, function () {
return this;
});
var getProto = Object.getPrototypeOf,
NativeIteratorPrototype = getProto && getProto(getProto(values([])));
NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function (method) {
define(prototype, method, function (arg) {
return this._invoke(method, arg);
});
});
}
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if ("throw" !== record.type) {
var result = record.arg,
value = result.value;
return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
invoke("next", value, resolve, reject);
}, function (err) {
invoke("throw", err, resolve, reject);
}) : PromiseImpl.resolve(value).then(function (unwrapped) {
result.value = unwrapped, resolve(result);
}, function (error) {
return invoke("throw", error, resolve, reject);
});
}
reject(record.arg);
}
var previousPromise;
defineProperty(this, "_invoke", {
value: function value(method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function (resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
}
});
}
function makeInvokeMethod(innerFn, self, context) {
var state = "suspendedStart";
return function (method, arg) {
if ("executing" === state) throw new Error("Generator is already running");
if ("completed" === state) {
if ("throw" === method) throw arg;
return doneResult();
}
for (context.method = method, context.arg = arg;;) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
if ("suspendedStart" === state) throw state = "completed", context.arg;
context.dispatchException(context.arg);
} else "return" === context.method && context.abrupt("return", context.arg);
state = "executing";
var record = tryCatch(innerFn, self, context);
if ("normal" === record.type) {
if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
return {
value: record.arg,
done: context.done
};
}
"throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
}
};
}
function maybeInvokeDelegate(delegate, context) {
var methodName = context.method,
method = delegate.iterator[methodName];
if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel;
var record = tryCatch(method, delegate.iterator, context.arg);
if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
var info = record.arg;
return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
}
function pushTryEntry(locs) {
var entry = {
tryLoc: locs[0]
};
1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal", delete record.arg, entry.completion = record;
}
function Context(tryLocsList) {
this.tryEntries = [{
tryLoc: "root"
}], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
}
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) return iteratorMethod.call(iterable);
if ("function" == typeof iterable.next) return iterable;
if (!isNaN(iterable.length)) {
var i = -1,
next = function next() {
for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
return next.value = undefined, next.done = !0, next;
};
return next.next = next;
}
}
return {
next: doneResult
};
}
function doneResult() {
return {
value: undefined,
done: !0
};
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
value: GeneratorFunctionPrototype,
configurable: !0
}), defineProperty(GeneratorFunctionPrototype, "constructor", {
value: GeneratorFunction,
configurable: !0
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
var ctor = "function" == typeof genFun && genFun.constructor;
return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
}, exports.mark = function (genFun) {
return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
}, exports.awrap = function (arg) {
return {
__await: arg
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
return this;
}), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
void 0 === PromiseImpl && (PromiseImpl = Promise);
var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
return result.done ? result.value : iter.next();
});
}, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
return this;
}), define(Gp, "toString", function () {
return "[object Generator]";
}), exports.keys = function (val) {
var object = Object(val),
keys = [];
for (var key in object) keys.push(key);
return keys.reverse(), function next() {
for (; keys.length;) {
var key = keys.pop();
if (key in object) return next.value = key, next.done = !1, next;
}
return next.done = !0, next;
};
}, exports.values = values, Context.prototype = {
constructor: Context,
reset: function reset(skipTempReset) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
},
stop: function stop() {
this.done = !0;
var rootRecord = this.tryEntries[0].completion;
if ("throw" === rootRecord.type) throw rootRecord.arg;
return this.rval;
},
dispatchException: function dispatchException(exception) {
if (this.done) throw exception;
var context = this;
function handle(loc, caught) {
return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i],
record = entry.completion;
if ("root" === entry.tryLoc) return handle("end");
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc"),
hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
} else if (hasCatch) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
} else {
if (!hasFinally) throw new Error("try statement without catch or finally");
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
}
}
}
},
abrupt: function abrupt(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
var record = finallyEntry ? finallyEntry.completion : {};
return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
},
complete: function complete(record, afterLoc) {
if ("throw" === record.type) throw record.arg;
return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
},
finish: function finish(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
}
},
"catch": function _catch(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if ("throw" === record.type) {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
throw new Error("illegal catch attempt");
},
delegateYield: function delegateYield(iterable, resultName, nextLoc) {
return this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
}, "next" === this.method && (this.arg = undefined), ContinueSentinel;
}
}, exports;
}
module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/***/ 36:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
var _typeof = (__webpack_require__(698)["default"]);
function _toPrimitive(input, hint) {
if (_typeof(input) !== "object" || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || "default");
if (_typeof(res) !== "object") return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
module.exports = _toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/***/ 62:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
var _typeof = (__webpack_require__(698)["default"]);
var toPrimitive = __webpack_require__(36);
function _toPropertyKey(arg) {
var key = toPrimitive(arg, "string");
return _typeof(key) === "symbol" ? key : String(key);
}
module.exports = _toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/***/ 698:
/***/ ((module) => {
function _typeof(obj) {
"@babel/helpers - typeof";
return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj);
}
module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/***/ 687:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
// TODO(Babel 8): Remove this file.
var runtime = __webpack_require__(61)();
module.exports = runtime;
// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
if (typeof globalThis === "object") {
globalThis.regeneratorRuntime = runtime;
} else {
Function("r", "regeneratorRuntime = r")(runtime);
}
}
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ id: moduleId,
/******/ loaded: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = __webpack_modules__;
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ (() => {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = (module) => {
/******/ var getter = module && module.__esModule ?
/******/ () => (module['default']) :
/******/ () => (module);
/******/ __webpack_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/create fake namespace object */
/******/ (() => {
/******/ var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);
/******/ var leafPrototypes;
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 16: return value when it's Promise-like
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = this(value);
/******/ if(mode & 8) return value;
/******/ if(typeof value === 'object' && value) {
/******/ if((mode & 4) && value.__esModule) return value;
/******/ if((mode & 16) && typeof value.then === 'function') return value;
/******/ }
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ var def = {};
/******/ leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];
/******/ for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {
/******/ Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));
/******/ }
/******/ def['default'] = () => (value);
/******/ __webpack_require__.d(ns, def);
/******/ return ns;
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/ensure chunk */
/******/ (() => {
/******/ __webpack_require__.f = {};
/******/ // This file contains only the entry chunk.
/******/ // The chunk loading function for additional chunks
/******/ __webpack_require__.e = (chunkId) => {
/******/ return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {
/******/ __webpack_require__.f[key](chunkId, promises);
/******/ return promises;
/******/ }, []));
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/get javascript chunk filename */
/******/ (() => {
/******/ // This function allow to reference async chunks
/******/ __webpack_require__.u = (chunkId) => {
/******/ // return url for filenames based on template
/******/ return "" + "emojis" + ".js";
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/global */
/******/ (() => {
/******/ __webpack_require__.g = (function() {
/******/ if (typeof globalThis === 'object') return globalThis;
/******/ try {
/******/ return this || new Function('return this')();
/******/ } catch (e) {
/******/ if (typeof window === 'object') return window;
/******/ }
/******/ })();
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/load script */
/******/ (() => {
/******/ var inProgress = {};
/******/ var dataWebpackPrefix = "converse:";
/******/ // loadScript function to load a script via script tag
/******/ __webpack_require__.l = (url, done, key, chunkId) => {
/******/ if(inProgress[url]) { inProgress[url].push(done); return; }
/******/ var script, needAttach;
/******/ if(key !== undefined) {
/******/ var scripts = document.getElementsByTagName("script");
/******/ for(var i = 0; i < scripts.length; i++) {
/******/ var s = scripts[i];
/******/ if(s.getAttribute("src") == url || s.getAttribute("data-webpack") == dataWebpackPrefix + key) { script = s; break; }
/******/ }
/******/ }
/******/ if(!script) {
/******/ needAttach = true;
/******/ script = document.createElement('script');
/******/
/******/ script.charset = 'utf-8';
/******/ script.timeout = 120;
/******/ if (__webpack_require__.nc) {
/******/ script.setAttribute("nonce", __webpack_require__.nc);
/******/ }
/******/ script.setAttribute("data-webpack", dataWebpackPrefix + key);
/******/
/******/ script.src = url;
/******/ }
/******/ inProgress[url] = [done];
/******/ var onScriptComplete = (prev, event) => {
/******/ // avoid mem leaks in IE.
/******/ script.onerror = script.onload = null;
/******/ clearTimeout(timeout);
/******/ var doneFns = inProgress[url];
/******/ delete inProgress[url];
/******/ script.parentNode && script.parentNode.removeChild(script);
/******/ doneFns && doneFns.forEach((fn) => (fn(event)));
/******/ if(prev) return prev(event);
/******/ }
/******/ var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);
/******/ script.onerror = onScriptComplete.bind(null, script.onerror);
/******/ script.onload = onScriptComplete.bind(null, script.onload);
/******/ needAttach && document.head.appendChild(script);
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/node module decorator */
/******/ (() => {
/******/ __webpack_require__.nmd = (module) => {
/******/ module.paths = [];
/******/ if (!module.children) module.children = [];
/******/ return module;
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/publicPath */
/******/ (() => {
/******/ __webpack_require__.p = "";
/******/ })();
/******/
/******/ /* webpack/runtime/jsonp chunk loading */
/******/ (() => {
/******/ // no baseURI
/******/
/******/ // object to store loaded and loading chunks
/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
/******/ var installedChunks = {
/******/ 729: 0,
/******/ 267: 0
/******/ };
/******/
/******/ __webpack_require__.f.j = (chunkId, promises) => {
/******/ // JSONP chunk loading for javascript
/******/ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;
/******/ if(installedChunkData !== 0) { // 0 means "already installed".
/******/
/******/ // a Promise means "currently loading".
/******/ if(installedChunkData) {
/******/ promises.push(installedChunkData[2]);
/******/ } else {
/******/ if(true) { // all chunks have JS
/******/ // setup Promise in chunk cache
/******/ var promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));
/******/ promises.push(installedChunkData[2] = promise);
/******/
/******/ // start chunk loading
/******/ var url = __webpack_require__.p + __webpack_require__.u(chunkId);
/******/ // create error before stack unwound to get useful stacktrace later
/******/ var error = new Error();
/******/ var loadingEnded = (event) => {
/******/ if(__webpack_require__.o(installedChunks, chunkId)) {
/******/ installedChunkData = installedChunks[chunkId];
/******/ if(installedChunkData !== 0) installedChunks[chunkId] = undefined;
/******/ if(installedChunkData) {
/******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type);
/******/ var realSrc = event && event.target && event.target.src;
/******/ error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')';
/******/ error.name = 'ChunkLoadError';
/******/ error.type = errorType;
/******/ error.request = realSrc;
/******/ installedChunkData[1](error);
/******/ }
/******/ }
/******/ };
/******/ __webpack_require__.l(url, loadingEnded, "chunk-" + chunkId, chunkId);
/******/ }
/******/ }
/******/ }
/******/ };
/******/
/******/ // no prefetching
/******/
/******/ // no preloaded
/******/
/******/ // no HMR
/******/
/******/ // no HMR manifest
/******/
/******/ // no on chunks loaded
/******/
/******/ // install a JSONP callback for chunk loading
/******/ var webpackJsonpCallback = (parentChunkLoadingFunction, data) => {
/******/ var [chunkIds, moreModules, runtime] = data;
/******/ // add "moreModules" to the modules object,
/******/ // then flag all "chunkIds" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0;
/******/ if(chunkIds.some((id) => (installedChunks[id] !== 0))) {
/******/ for(moduleId in moreModules) {
/******/ if(__webpack_require__.o(moreModules, moduleId)) {
/******/ __webpack_require__.m[moduleId] = moreModules[moduleId];
/******/ }
/******/ }
/******/ if(runtime) var result = runtime(__webpack_require__);
/******/ }
/******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);
/******/ for(;i < chunkIds.length; i++) {
/******/ chunkId = chunkIds[i];
/******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ installedChunks[chunkId][0]();
/******/ }
/******/ installedChunks[chunkId] = 0;
/******/ }
/******/
/******/ }
/******/
/******/ var chunkLoadingGlobal = this["webpackChunkconverse"] = this["webpackChunkconverse"] || [];
/******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));
/******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"default": () => (/* binding */ headless)
});
// NAMESPACE OBJECT: ./src/strophe-shims.js
var strophe_shims_namespaceObject = {};
__webpack_require__.r(strophe_shims_namespaceObject);
__webpack_require__.d(strophe_shims_namespaceObject, {
DOMParser: () => (DOMParser),
WebSocket: () => (WebSocket),
getDummyXMLDOMDocument: () => (getDummyXMLDOMDocument)
});
// NAMESPACE OBJECT: ./node_modules/strophe.js/src/utils.js
var utils_namespaceObject = {};
__webpack_require__.r(utils_namespaceObject);
__webpack_require__.d(utils_namespaceObject, {
addCookies: () => (addCookies),
arrayBufToBase64: () => (arrayBufToBase64),
base64ToArrayBuf: () => (base64ToArrayBuf),
copyElement: () => (copyElement),
createHtml: () => (createHtml),
"default": () => (utils),
escapeNode: () => (escapeNode),
forEachChild: () => (forEachChild),
getBareJidFromJid: () => (getBareJidFromJid),
getDomainFromJid: () => (getDomainFromJid),
getNodeFromJid: () => (getNodeFromJid),
getResourceFromJid: () => (getResourceFromJid),
getText: () => (getText),
isTagEqual: () => (isTagEqual),
serialize: () => (serialize),
stringToArrayBuf: () => (stringToArrayBuf),
unescapeNode: () => (unescapeNode),
utf16to8: () => (utf16to8),
validAttribute: () => (validAttribute),
validCSS: () => (validCSS),
validTag: () => (validTag),
xmlElement: () => (xmlElement),
xmlGenerator: () => (xmlGenerator),
xmlHtmlNode: () => (xmlHtmlNode),
xmlTextNode: () => (xmlTextNode),
xmlescape: () => (xmlescape),
xmlunescape: () => (xmlunescape),
xorArrayBuffers: () => (xorArrayBuffers)
});
;// CONCATENATED MODULE: ./node_modules/lodash-es/_freeGlobal.js
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
/* harmony default export */ const _freeGlobal = (freeGlobal);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_root.js
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = _freeGlobal || freeSelf || Function('return this')();
/* harmony default export */ const _root = (root);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_Symbol.js
/** Built-in value references. */
var _Symbol_Symbol = _root.Symbol;
/* harmony default export */ const _Symbol = (_Symbol_Symbol);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getRawTag.js
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var _getRawTag_hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = _getRawTag_hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
/* harmony default export */ const _getRawTag = (getRawTag);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_objectToString.js
/** Used for built-in method references. */
var _objectToString_objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var _objectToString_nativeObjectToString = _objectToString_objectProto.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return _objectToString_nativeObjectToString.call(value);
}
/* harmony default export */ const _objectToString = (objectToString);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseGetTag.js
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var _baseGetTag_symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (_baseGetTag_symToStringTag && _baseGetTag_symToStringTag in Object(value))
? _getRawTag(value)
: _objectToString(value);
}
/* harmony default export */ const _baseGetTag = (baseGetTag);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isObject.js
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
/* harmony default export */ const lodash_es_isObject = (isObject);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isFunction.js
/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
proxyTag = '[object Proxy]';
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!lodash_es_isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = _baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
/* harmony default export */ const lodash_es_isFunction = (isFunction);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_coreJsData.js
/** Used to detect overreaching core-js shims. */
var coreJsData = _root['__core-js_shared__'];
/* harmony default export */ const _coreJsData = (coreJsData);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isMasked.js
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
/* harmony default export */ const _isMasked = (isMasked);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_toSource.js
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/* harmony default export */ const _toSource = (toSource);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsNative.js
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var _baseIsNative_funcProto = Function.prototype,
_baseIsNative_objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var _baseIsNative_funcToString = _baseIsNative_funcProto.toString;
/** Used to check objects for own properties. */
var _baseIsNative_hasOwnProperty = _baseIsNative_objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
_baseIsNative_funcToString.call(_baseIsNative_hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!lodash_es_isObject(value) || _isMasked(value)) {
return false;
}
var pattern = lodash_es_isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(_toSource(value));
}
/* harmony default export */ const _baseIsNative = (baseIsNative);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getValue.js
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
/* harmony default export */ const _getValue = (getValue);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getNative.js
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = _getValue(object, key);
return _baseIsNative(value) ? value : undefined;
}
/* harmony default export */ const _getNative = (getNative);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_defineProperty.js
var defineProperty = (function() {
try {
var func = _getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
/* harmony default export */ const _defineProperty = (defineProperty);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseAssignValue.js
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && _defineProperty) {
_defineProperty(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
/* harmony default export */ const _baseAssignValue = (baseAssignValue);
;// CONCATENATED MODULE: ./node_modules/lodash-es/eq.js
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/* harmony default export */ const lodash_es_eq = (eq);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_assignValue.js
/** Used for built-in method references. */
var _assignValue_objectProto = Object.prototype;
/** Used to check objects for own properties. */
var _assignValue_hasOwnProperty = _assignValue_objectProto.hasOwnProperty;
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(_assignValue_hasOwnProperty.call(object, key) && lodash_es_eq(objValue, value)) ||
(value === undefined && !(key in object))) {
_baseAssignValue(object, key, value);
}
}
/* harmony default export */ const _assignValue = (assignValue);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_copyObject.js
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
_baseAssignValue(object, key, newValue);
} else {
_assignValue(object, key, newValue);
}
}
return object;
}
/* harmony default export */ const _copyObject = (copyObject);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseTimes.js
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/* harmony default export */ const _baseTimes = (baseTimes);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isObjectLike.js
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
/* harmony default export */ const lodash_es_isObjectLike = (isObjectLike);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsArguments.js
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return lodash_es_isObjectLike(value) && _baseGetTag(value) == argsTag;
}
/* harmony default export */ const _baseIsArguments = (baseIsArguments);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isArguments.js
/** Used for built-in method references. */
var isArguments_objectProto = Object.prototype;
/** Used to check objects for own properties. */
var isArguments_hasOwnProperty = isArguments_objectProto.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = isArguments_objectProto.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
return lodash_es_isObjectLike(value) && isArguments_hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
/* harmony default export */ const lodash_es_isArguments = (isArguments);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isArray.js
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/* harmony default export */ const lodash_es_isArray = (isArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/stubFalse.js
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
/* harmony default export */ const lodash_es_stubFalse = (stubFalse);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isBuffer.js
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? _root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || lodash_es_stubFalse;
/* harmony default export */ const lodash_es_isBuffer = (isBuffer);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isIndex.js
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
var type = typeof value;
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(type == 'number' ||
(type != 'symbol' && reIsUint.test(value))) &&
(value > -1 && value % 1 == 0 && value < length);
}
/* harmony default export */ const _isIndex = (isIndex);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isLength.js
/** Used as references for various `Number` constants. */
var isLength_MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= isLength_MAX_SAFE_INTEGER;
}
/* harmony default export */ const lodash_es_isLength = (isLength);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsTypedArray.js
/** `Object#toString` result references. */
var _baseIsTypedArray_argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
_baseIsTypedArray_funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[_baseIsTypedArray_argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[_baseIsTypedArray_funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return lodash_es_isObjectLike(value) &&
lodash_es_isLength(value.length) && !!typedArrayTags[_baseGetTag(value)];
}
/* harmony default export */ const _baseIsTypedArray = (baseIsTypedArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseUnary.js
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
/* harmony default export */ const _baseUnary = (baseUnary);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_nodeUtil.js
/** Detect free variable `exports`. */
var _nodeUtil_freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var _nodeUtil_freeModule = _nodeUtil_freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var _nodeUtil_moduleExports = _nodeUtil_freeModule && _nodeUtil_freeModule.exports === _nodeUtil_freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = _nodeUtil_moduleExports && _freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
// Use `util.types` for Node.js 10+.
var types = _nodeUtil_freeModule && _nodeUtil_freeModule.require && _nodeUtil_freeModule.require('util').types;
if (types) {
return types;
}
// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
/* harmony default export */ const _nodeUtil = (nodeUtil);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isTypedArray.js
/* Node.js helper references. */
var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
/* harmony default export */ const lodash_es_isTypedArray = (isTypedArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayLikeKeys.js
/** Used for built-in method references. */
var _arrayLikeKeys_objectProto = Object.prototype;
/** Used to check objects for own properties. */
var _arrayLikeKeys_hasOwnProperty = _arrayLikeKeys_objectProto.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = lodash_es_isArray(value),
isArg = !isArr && lodash_es_isArguments(value),
isBuff = !isArr && !isArg && lodash_es_isBuffer(value),
isType = !isArr && !isArg && !isBuff && lodash_es_isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? _baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || _arrayLikeKeys_hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
_isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
/* harmony default export */ const _arrayLikeKeys = (arrayLikeKeys);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isPrototype.js
/** Used for built-in method references. */
var _isPrototype_objectProto = Object.prototype;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || _isPrototype_objectProto;
return value === proto;
}
/* harmony default export */ const _isPrototype = (isPrototype);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_overArg.js
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/* harmony default export */ const _overArg = (overArg);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_nativeKeys.js
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = _overArg(Object.keys, Object);
/* harmony default export */ const _nativeKeys = (nativeKeys);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseKeys.js
/** Used for built-in method references. */
var _baseKeys_objectProto = Object.prototype;
/** Used to check objects for own properties. */
var _baseKeys_hasOwnProperty = _baseKeys_objectProto.hasOwnProperty;
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!_isPrototype(object)) {
return _nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (_baseKeys_hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/* harmony default export */ const _baseKeys = (baseKeys);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isArrayLike.js
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && lodash_es_isLength(value.length) && !lodash_es_isFunction(value);
}
/* harmony default export */ const lodash_es_isArrayLike = (isArrayLike);
;// CONCATENATED MODULE: ./node_modules/lodash-es/keys.js
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return lodash_es_isArrayLike(object) ? _arrayLikeKeys(object) : _baseKeys(object);
}
/* harmony default export */ const lodash_es_keys = (keys);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseAssign.js
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && _copyObject(source, lodash_es_keys(source), object);
}
/* harmony default export */ const _baseAssign = (baseAssign);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseCreate.js
/** Built-in value references. */
var objectCreate = Object.create;
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!lodash_es_isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
/* harmony default export */ const _baseCreate = (baseCreate);
;// CONCATENATED MODULE: ./node_modules/lodash-es/create.js
/**
* Creates an object that inherits from the `prototype` object. If a
* `properties` object is given, its own enumerable string keyed properties
* are assigned to the created object.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Object
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @returns {Object} Returns the new object.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* function Circle() {
* Shape.call(this);
* }
*
* Circle.prototype = _.create(Shape.prototype, {
* 'constructor': Circle
* });
*
* var circle = new Circle;
* circle instanceof Circle;
* // => true
*
* circle instanceof Shape;
* // => true
*/
function create(prototype, properties) {
var result = _baseCreate(prototype);
return properties == null ? result : _baseAssign(result, properties);
}
/* harmony default export */ const lodash_es_create = (create);
;// CONCATENATED MODULE: ./node_modules/lodash-es/identity.js
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
/* harmony default export */ const lodash_es_identity = (identity);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_apply.js
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
/* harmony default export */ const _apply = (apply);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_overRest.js
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return _apply(func, this, otherArgs);
};
}
/* harmony default export */ const _overRest = (overRest);
;// CONCATENATED MODULE: ./node_modules/lodash-es/constant.js
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
/* harmony default export */ const lodash_es_constant = (constant);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSetToString.js
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !_defineProperty ? lodash_es_identity : function(func, string) {
return _defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': lodash_es_constant(string),
'writable': true
});
};
/* harmony default export */ const _baseSetToString = (baseSetToString);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_shortOut.js
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
/* harmony default export */ const _shortOut = (shortOut);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_setToString.js
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = _shortOut(_baseSetToString);
/* harmony default export */ const _setToString = (setToString);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseRest.js
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return _setToString(_overRest(func, start, lodash_es_identity), func + '');
}
/* harmony default export */ const _baseRest = (baseRest);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isIterateeCall.js
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!lodash_es_isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (lodash_es_isArrayLike(object) && _isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return lodash_es_eq(object[index], value);
}
return false;
}
/* harmony default export */ const _isIterateeCall = (isIterateeCall);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_createAssigner.js
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return _baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && _isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
/* harmony default export */ const _createAssigner = (createAssigner);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_nativeKeysIn.js
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
/* harmony default export */ const _nativeKeysIn = (nativeKeysIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseKeysIn.js
/** Used for built-in method references. */
var _baseKeysIn_objectProto = Object.prototype;
/** Used to check objects for own properties. */
var _baseKeysIn_hasOwnProperty = _baseKeysIn_objectProto.hasOwnProperty;
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!lodash_es_isObject(object)) {
return _nativeKeysIn(object);
}
var isProto = _isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !_baseKeysIn_hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
/* harmony default export */ const _baseKeysIn = (baseKeysIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/keysIn.js
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
return lodash_es_isArrayLike(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
}
/* harmony default export */ const lodash_es_keysIn = (keysIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/assignIn.js
/**
* This method is like `_.assign` except that it iterates over own and
* inherited source properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extend
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assign
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assignIn({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
*/
var assignIn = _createAssigner(function(object, source) {
_copyObject(source, lodash_es_keysIn(source), object);
});
/* harmony default export */ const lodash_es_assignIn = (assignIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseHas.js
/** Used for built-in method references. */
var _baseHas_objectProto = Object.prototype;
/** Used to check objects for own properties. */
var _baseHas_hasOwnProperty = _baseHas_objectProto.hasOwnProperty;
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
return object != null && _baseHas_hasOwnProperty.call(object, key);
}
/* harmony default export */ const _baseHas = (baseHas);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isSymbol.js
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(lodash_es_isObjectLike(value) && _baseGetTag(value) == symbolTag);
}
/* harmony default export */ const lodash_es_isSymbol = (isSymbol);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isKey.js
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/;
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (lodash_es_isArray(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || lodash_es_isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
/* harmony default export */ const _isKey = (isKey);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_nativeCreate.js
/* Built-in method references that are verified to be native. */
var nativeCreate = _getNative(Object, 'create');
/* harmony default export */ const _nativeCreate = (nativeCreate);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_hashClear.js
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
this.size = 0;
}
/* harmony default export */ const _hashClear = (hashClear);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_hashDelete.js
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
/* harmony default export */ const _hashDelete = (hashDelete);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_hashGet.js
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var _hashGet_objectProto = Object.prototype;
/** Used to check objects for own properties. */
var _hashGet_hasOwnProperty = _hashGet_objectProto.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (_nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return _hashGet_hasOwnProperty.call(data, key) ? data[key] : undefined;
}
/* harmony default export */ const _hashGet = (hashGet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_hashHas.js
/** Used for built-in method references. */
var _hashHas_objectProto = Object.prototype;
/** Used to check objects for own properties. */
var _hashHas_hasOwnProperty = _hashHas_objectProto.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return _nativeCreate ? (data[key] !== undefined) : _hashHas_hasOwnProperty.call(data, key);
}
/* harmony default export */ const _hashHas = (hashHas);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_hashSet.js
/** Used to stand-in for `undefined` hash values. */
var _hashSet_HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (_nativeCreate && value === undefined) ? _hashSet_HASH_UNDEFINED : value;
return this;
}
/* harmony default export */ const _hashSet = (hashSet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_Hash.js
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash.prototype.clear = _hashClear;
Hash.prototype['delete'] = _hashDelete;
Hash.prototype.get = _hashGet;
Hash.prototype.has = _hashHas;
Hash.prototype.set = _hashSet;
/* harmony default export */ const _Hash = (Hash);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheClear.js
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
/* harmony default export */ const _listCacheClear = (listCacheClear);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_assocIndexOf.js
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (lodash_es_eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/* harmony default export */ const _assocIndexOf = (assocIndexOf);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheDelete.js
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = _assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
/* harmony default export */ const _listCacheDelete = (listCacheDelete);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheGet.js
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = _assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
/* harmony default export */ const _listCacheGet = (listCacheGet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheHas.js
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return _assocIndexOf(this.__data__, key) > -1;
}
/* harmony default export */ const _listCacheHas = (listCacheHas);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheSet.js
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = _assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
/* harmony default export */ const _listCacheSet = (listCacheSet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_ListCache.js
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = _listCacheClear;
ListCache.prototype['delete'] = _listCacheDelete;
ListCache.prototype.get = _listCacheGet;
ListCache.prototype.has = _listCacheHas;
ListCache.prototype.set = _listCacheSet;
/* harmony default export */ const _ListCache = (ListCache);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_Map.js
/* Built-in method references that are verified to be native. */
var _Map_Map = _getNative(_root, 'Map');
/* harmony default export */ const _Map = (_Map_Map);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheClear.js
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new _Hash,
'map': new (_Map || _ListCache),
'string': new _Hash
};
}
/* harmony default export */ const _mapCacheClear = (mapCacheClear);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isKeyable.js
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
/* harmony default export */ const _isKeyable = (isKeyable);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getMapData.js
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return _isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
/* harmony default export */ const _getMapData = (getMapData);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheDelete.js
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = _getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
/* harmony default export */ const _mapCacheDelete = (mapCacheDelete);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheGet.js
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return _getMapData(this, key).get(key);
}
/* harmony default export */ const _mapCacheGet = (mapCacheGet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheHas.js
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return _getMapData(this, key).has(key);
}
/* harmony default export */ const _mapCacheHas = (mapCacheHas);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheSet.js
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = _getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
/* harmony default export */ const _mapCacheSet = (mapCacheSet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_MapCache.js
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache.prototype.clear = _mapCacheClear;
MapCache.prototype['delete'] = _mapCacheDelete;
MapCache.prototype.get = _mapCacheGet;
MapCache.prototype.has = _mapCacheHas;
MapCache.prototype.set = _mapCacheSet;
/* harmony default export */ const _MapCache = (MapCache);
;// CONCATENATED MODULE: ./node_modules/lodash-es/memoize.js
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize.Cache || _MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = _MapCache;
/* harmony default export */ const lodash_es_memoize = (memoize);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_memoizeCapped.js
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = lodash_es_memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
/* harmony default export */ const _memoizeCapped = (memoizeCapped);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_stringToPath.js
/** Used to match property names within property paths. */
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = _memoizeCapped(function(string) {
var result = [];
if (string.charCodeAt(0) === 46 /* . */) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, subString) {
result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
/* harmony default export */ const _stringToPath = (stringToPath);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayMap.js
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
/* harmony default export */ const _arrayMap = (arrayMap);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseToString.js
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto = _Symbol ? _Symbol.prototype : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (lodash_es_isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return _arrayMap(value, baseToString) + '';
}
if (lodash_es_isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
/* harmony default export */ const _baseToString = (baseToString);
;// CONCATENATED MODULE: ./node_modules/lodash-es/toString.js
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString_toString(value) {
return value == null ? '' : _baseToString(value);
}
/* harmony default export */ const lodash_es_toString = (toString_toString);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_castPath.js
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value, object) {
if (lodash_es_isArray(value)) {
return value;
}
return _isKey(value, object) ? [value] : _stringToPath(lodash_es_toString(value));
}
/* harmony default export */ const _castPath = (castPath);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_toKey.js
/** Used as references for various `Number` constants. */
var _toKey_INFINITY = 1 / 0;
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || lodash_es_isSymbol(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -_toKey_INFINITY) ? '-0' : result;
}
/* harmony default export */ const _toKey = (toKey);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_hasPath.js
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = _castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = _toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && lodash_es_isLength(length) && _isIndex(key, length) &&
(lodash_es_isArray(object) || lodash_es_isArguments(object));
}
/* harmony default export */ const _hasPath = (hasPath);
;// CONCATENATED MODULE: ./node_modules/lodash-es/has.js
/**
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
*/
function has(object, path) {
return object != null && _hasPath(object, path, _baseHas);
}
/* harmony default export */ const lodash_es_has = (has);
;// CONCATENATED MODULE: ./node_modules/lodash-es/result.js
/**
* This method is like `_.get` except that if the resolved value is a
* function it's invoked with the `this` binding of its parent object and
* its result is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to resolve.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
*
* _.result(object, 'a[0].b.c1');
* // => 3
*
* _.result(object, 'a[0].b.c2');
* // => 4
*
* _.result(object, 'a[0].b.c3', 'default');
* // => 'default'
*
* _.result(object, 'a[0].b.c3', _.constant('default'));
* // => 'default'
*/
function result(object, path, defaultValue) {
path = _castPath(path, object);
var index = -1,
length = path.length;
// Ensure the loop is entered when path is empty.
if (!length) {
length = 1;
object = undefined;
}
while (++index < length) {
var value = object == null ? undefined : object[_toKey(path[index])];
if (value === undefined) {
index = length;
value = defaultValue;
}
object = lodash_es_isFunction(value) ? value.call(object) : value;
}
return object;
}
/* harmony default export */ const lodash_es_result = (result);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/helpers.js
// (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
/**
* Custom error for indicating timeouts
* @namespace _converse
*/
class NotImplementedError extends (/* unused pure expression or super */ null && (Error)) {}
function S4() {
// Generate four random hex digits.
return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);
}
function guid() {
// Generate a pseudo-GUID by concatenating random hexadecimal.
return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4();
}
// Helpers
// -------
// Helper function to correctly set up the prototype chain for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
//
function inherits(protoProps, staticProps) {
const parent = this;
let child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent constructor.
if (protoProps && lodash_es_has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function () {
return parent.apply(this, arguments);
};
}
// Add static properties to the constructor function, if supplied.
lodash_es_assignIn(child, parent, staticProps);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function and add the prototype properties.
child.prototype = lodash_es_create(parent.prototype, protoProps);
child.prototype.constructor = child;
// Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
}
function getResolveablePromise() {
const wrapper = {
isResolved: false,
isPending: true,
isRejected: false
};
const promise = new Promise((resolve, reject) => {
wrapper.resolve = resolve;
wrapper.reject = reject;
});
Object.assign(promise, wrapper);
promise.then(function (v) {
promise.isResolved = true;
promise.isPending = false;
promise.isRejected = false;
return v;
}, function (e) {
promise.isResolved = false;
promise.isPending = false;
promise.isRejected = true;
throw e;
});
return promise;
}
// Throw an error when a URL is needed, and none is supplied.
function urlError() {
throw new Error('A "url" property or function must be specified');
}
// Wrap an optional error callback with a fallback error event.
function wrapError(model, options) {
const error = options.error;
options.error = function (resp) {
if (error) error.call(options.context, model, resp, options);
model.trigger('error', model, resp, options);
};
}
// Map from CRUD to HTTP for our default `sync` implementation.
const methodMap = {
create: 'POST',
update: 'PUT',
patch: 'PATCH',
delete: 'DELETE',
read: 'GET'
};
function getSyncMethod(model) {
const store = lodash_es_result(model, 'browserStorage') || lodash_es_result(model.collection, 'browserStorage');
return store ? store.sync() : sync;
}
// sync
// ----
// Override this function to change the manner in which Backbone persists
// models to the server. You will be passed the type of request, and the
// model in question. By default, makes a RESTful Ajax request
// to the model's `url()`. Some possible customizations could be:
//
// * Use `setTimeout` to batch rapid-fire updates into a single request.
// * Send up the models as XML instead of JSON.
// * Persist models via WebSockets instead of Ajax.
//
function sync(method, model) {
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const type = methodMap[method];
// Default JSON-request options.
const params = {
type: type,
dataType: 'json'
};
// Ensure that we have a URL.
if (!options.url) {
params.url = lodash_es_result(model, 'url') || urlError();
}
// Ensure that we have the appropriate request data.
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
params.contentType = 'application/json';
params.data = JSON.stringify(options.attrs || model.toJSON(options));
}
// Don't process data on a non-GET request.
if (params.type !== 'GET') {
params.processData = false;
}
// Pass along `textStatus` and `errorThrown` from jQuery.
const error = options.error;
options.error = function (xhr, textStatus, errorThrown) {
options.textStatus = textStatus;
options.errorThrown = errorThrown;
if (error) error.call(options.context, xhr, textStatus, errorThrown);
};
// Make the request, allowing the user to override any Ajax options.
const xhr = options.xhr = ajax(lodash_es_assignIn(params, options));
model.trigger('request', model, xhr, options);
return xhr;
}
function ajax() {
return fetch.apply(this, arguments);
}
;// CONCATENATED MODULE: ./node_modules/lodash-es/_DataView.js
/* Built-in method references that are verified to be native. */
var DataView = _getNative(_root, 'DataView');
/* harmony default export */ const _DataView = (DataView);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_Promise.js
/* Built-in method references that are verified to be native. */
var _Promise_Promise = _getNative(_root, 'Promise');
/* harmony default export */ const _Promise = (_Promise_Promise);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_Set.js
/* Built-in method references that are verified to be native. */
var _Set_Set = _getNative(_root, 'Set');
/* harmony default export */ const _Set = (_Set_Set);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_WeakMap.js
/* Built-in method references that are verified to be native. */
var _WeakMap_WeakMap = _getNative(_root, 'WeakMap');
/* harmony default export */ const _WeakMap = (_WeakMap_WeakMap);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getTag.js
/** `Object#toString` result references. */
var _getTag_mapTag = '[object Map]',
_getTag_objectTag = '[object Object]',
promiseTag = '[object Promise]',
_getTag_setTag = '[object Set]',
_getTag_weakMapTag = '[object WeakMap]';
var _getTag_dataViewTag = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = _toSource(_DataView),
mapCtorString = _toSource(_Map),
promiseCtorString = _toSource(_Promise),
setCtorString = _toSource(_Set),
weakMapCtorString = _toSource(_WeakMap);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = _baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != _getTag_dataViewTag) ||
(_Map && getTag(new _Map) != _getTag_mapTag) ||
(_Promise && getTag(_Promise.resolve()) != promiseTag) ||
(_Set && getTag(new _Set) != _getTag_setTag) ||
(_WeakMap && getTag(new _WeakMap) != _getTag_weakMapTag)) {
getTag = function(value) {
var result = _baseGetTag(value),
Ctor = result == _getTag_objectTag ? value.constructor : undefined,
ctorString = Ctor ? _toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return _getTag_dataViewTag;
case mapCtorString: return _getTag_mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return _getTag_setTag;
case weakMapCtorString: return _getTag_weakMapTag;
}
}
return result;
};
}
/* harmony default export */ const _getTag = (getTag);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isEmpty.js
/** `Object#toString` result references. */
var isEmpty_mapTag = '[object Map]',
isEmpty_setTag = '[object Set]';
/** Used for built-in method references. */
var isEmpty_objectProto = Object.prototype;
/** Used to check objects for own properties. */
var isEmpty_hasOwnProperty = isEmpty_objectProto.hasOwnProperty;
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
if (lodash_es_isArrayLike(value) &&
(lodash_es_isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
lodash_es_isBuffer(value) || lodash_es_isTypedArray(value) || lodash_es_isArguments(value))) {
return !value.length;
}
var tag = _getTag(value);
if (tag == isEmpty_mapTag || tag == isEmpty_setTag) {
return !value.size;
}
if (_isPrototype(value)) {
return !_baseKeys(value).length;
}
for (var key in value) {
if (isEmpty_hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
/* harmony default export */ const lodash_es_isEmpty = (isEmpty);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_trimmedEndIndex.js
/** Used to match a single whitespace character. */
var reWhitespace = /\s/;
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
* character of `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the index of the last non-whitespace character.
*/
function trimmedEndIndex(string) {
var index = string.length;
while (index-- && reWhitespace.test(string.charAt(index))) {}
return index;
}
/* harmony default export */ const _trimmedEndIndex = (trimmedEndIndex);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseTrim.js
/** Used to match leading whitespace. */
var reTrimStart = /^\s+/;
/**
* The base implementation of `_.trim`.
*
* @private
* @param {string} string The string to trim.
* @returns {string} Returns the trimmed string.
*/
function baseTrim(string) {
return string
? string.slice(0, _trimmedEndIndex(string) + 1).replace(reTrimStart, '')
: string;
}
/* harmony default export */ const _baseTrim = (baseTrim);
;// CONCATENATED MODULE: ./node_modules/lodash-es/toNumber.js
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (lodash_es_isSymbol(value)) {
return NAN;
}
if (lodash_es_isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = lodash_es_isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = _baseTrim(value);
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
/* harmony default export */ const lodash_es_toNumber = (toNumber);
;// CONCATENATED MODULE: ./node_modules/lodash-es/toFinite.js
/** Used as references for various `Number` constants. */
var toFinite_INFINITY = 1 / 0,
MAX_INTEGER = 1.7976931348623157e+308;
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = lodash_es_toNumber(value);
if (value === toFinite_INFINITY || value === -toFinite_INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
/* harmony default export */ const lodash_es_toFinite = (toFinite);
;// CONCATENATED MODULE: ./node_modules/lodash-es/toInteger.js
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = lodash_es_toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
/* harmony default export */ const lodash_es_toInteger = (toInteger);
;// CONCATENATED MODULE: ./node_modules/lodash-es/before.js
/** Error message constants. */
var before_FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that invokes `func`, with the `this` binding and arguments
* of the created function, while it's called less than `n` times. Subsequent
* calls to the created function return the result of the last `func` invocation.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {number} n The number of calls at which `func` is no longer invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* jQuery(element).on('click', _.before(5, addContactToList));
* // => Allows adding up to 4 contacts to the list.
*/
function before(n, func) {
var result;
if (typeof func != 'function') {
throw new TypeError(before_FUNC_ERROR_TEXT);
}
n = lodash_es_toInteger(n);
return function() {
if (--n > 0) {
result = func.apply(this, arguments);
}
if (n <= 1) {
func = undefined;
}
return result;
};
}
/* harmony default export */ const lodash_es_before = (before);
;// CONCATENATED MODULE: ./node_modules/lodash-es/once.js
/**
* Creates a function that is restricted to invoking `func` once. Repeat calls
* to the function return the value of the first invocation. The `func` is
* invoked with the `this` binding and arguments of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // => `createApplication` is invoked once
*/
function once(func) {
return lodash_es_before(2, func);
}
/* harmony default export */ const lodash_es_once = (once);
;// CONCATENATED MODULE: ./node_modules/lodash-es/uniqueId.js
/** Used to generate unique IDs. */
var idCounter = 0;
/**
* Generates a unique ID. If `prefix` is given, the ID is appended to it.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {string} [prefix=''] The value to prefix the ID with.
* @returns {string} Returns the unique ID.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*
* _.uniqueId();
* // => '105'
*/
function uniqueId(prefix) {
var id = ++idCounter;
return lodash_es_toString(prefix) + id;
}
/* harmony default export */ const lodash_es_uniqueId = (uniqueId);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/events.js
// Backbone.js 1.4.0
// (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
// Backbone may be freely distributed under the MIT license.
// Events
// ------
// A module that can be mixed in to *any object* in order to provide it with
// a custom event channel. You may bind a callback to an event with `on` or
// remove with `off`; `trigger`-ing an event fires all callbacks in
// succession.
//
// let object = {};
// extend(object, Backbone.Events);
// object.on('expand', function(){ alert('expanded'); });
// object.trigger('expand');
//
const Events = {};
// Regular expression used to split event strings.
const eventSplitter = /\s+/;
// A private global variable to share between listeners and listenees.
let _listening;
// Iterates over the standard `event, callback` (as well as the fancy multiple
// space-separated events `"change blur", callback` and jQuery-style event
// maps `{event: callback}`).
const eventsApi = function (iteratee, events, name, callback, opts) {
let i = 0,
names;
if (name && typeof name === 'object') {
// Handle event maps.
if (callback !== undefined && 'context' in opts && opts.context === undefined) opts.context = callback;
for (names = lodash_es_keys(name); i < names.length; i++) {
events = eventsApi(iteratee, events, names[i], name[names[i]], opts);
}
} else if (name && eventSplitter.test(name)) {
// Handle space-separated event names by delegating them individually.
for (names = name.split(eventSplitter); i < names.length; i++) {
events = iteratee(events, names[i], callback, opts);
}
} else {
// Finally, standard events.
events = iteratee(events, name, callback, opts);
}
return events;
};
// Bind an event to a `callback` function. Passing `"all"` will bind
// the callback to all events fired.
Events.on = function (name, callback, context) {
this._events = eventsApi(onApi, this._events || {}, name, callback, {
context: context,
ctx: this,
listening: _listening
});
if (_listening) {
const listeners = this._listeners || (this._listeners = {});
listeners[_listening.id] = _listening;
// Allow the listening to use a counter, instead of tracking
// callbacks for library interop
_listening.interop = false;
}
return this;
};
// Inversion-of-control versions of `on`. Tell *this* object to listen to
// an event in another object... keeping track of what it's listening to
// for easier unbinding later.
Events.listenTo = function (obj, name, callback) {
if (!obj) return this;
const id = obj._listenId || (obj._listenId = lodash_es_uniqueId('l'));
const listeningTo = this._listeningTo || (this._listeningTo = {});
let listening = _listening = listeningTo[id];
// This object is not listening to any other events on `obj` yet.
// Setup the necessary references to track the listening callbacks.
if (!listening) {
this._listenId || (this._listenId = lodash_es_uniqueId('l'));
listening = _listening = listeningTo[id] = new Listening(this, obj);
}
// Bind callbacks on obj.
const error = tryCatchOn(obj, name, callback, this);
_listening = undefined;
if (error) throw error;
// If the target obj is not Backbone.Events, track events manually.
if (listening.interop) listening.on(name, callback);
return this;
};
// The reducing API that adds a callback to the `events` object.
const onApi = function (events, name, callback, options) {
if (callback) {
const handlers = events[name] || (events[name] = []);
const context = options.context,
ctx = options.ctx,
listening = options.listening;
if (listening) listening.count++;
handlers.push({
callback: callback,
context: context,
ctx: context || ctx,
listening: listening
});
}
return events;
};
// An try-catch guarded #on function, to prevent poisoning the global
// `_listening` variable.
const tryCatchOn = function (obj, name, callback, context) {
try {
obj.on(name, callback, context);
} catch (e) {
return e;
}
};
// Remove one or many callbacks. If `context` is null, removes all
// callbacks with that function. If `callback` is null, removes all
// callbacks for the event. If `name` is null, removes all bound
// callbacks for all events.
Events.off = function (name, callback, context) {
if (!this._events) return this;
this._events = eventsApi(offApi, this._events, name, callback, {
context: context,
listeners: this._listeners
});
return this;
};
// Tell this object to stop listening to either specific events ... or
// to every object it's currently listening to.
Events.stopListening = function (obj, name, callback) {
const listeningTo = this._listeningTo;
if (!listeningTo) return this;
const ids = obj ? [obj._listenId] : lodash_es_keys(listeningTo);
for (let i = 0; i < ids.length; i++) {
const listening = listeningTo[ids[i]];
// If listening doesn't exist, this object is not currently
// listening to obj. Break out early.
if (!listening) break;
listening.obj.off(name, callback, this);
if (listening.interop) listening.off(name, callback);
}
if (lodash_es_isEmpty(listeningTo)) this._listeningTo = undefined;
return this;
};
// The reducing API that removes a callback from the `events` object.
const offApi = function (events, name, callback, options) {
if (!events) return;
const context = options.context,
listeners = options.listeners;
let i = 0,
names;
// Delete all event listeners and "drop" events.
if (!name && !context && !callback) {
for (names = lodash_es_keys(listeners); i < names.length; i++) {
listeners[names[i]].cleanup();
}
return;
}
names = name ? [name] : lodash_es_keys(events);
for (; i < names.length; i++) {
name = names[i];
const handlers = events[name];
// Bail out if there are no events stored.
if (!handlers) {
break;
}
// Find any remaining events.
const remaining = [];
for (let j = 0; j < handlers.length; j++) {
const handler = handlers[j];
if (callback && callback !== handler.callback && callback !== handler.callback._callback || context && context !== handler.context) {
remaining.push(handler);
} else {
const listening = handler.listening;
if (listening) listening.off(name, callback);
}
}
// Replace events if there are any remaining. Otherwise, clean up.
if (remaining.length) {
events[name] = remaining;
} else {
delete events[name];
}
}
return events;
};
// Bind an event to only be triggered a single time. After the first time
// the callback is invoked, its listener will be removed. If multiple events
// are passed in using the space-separated syntax, the handler will fire
// once for each event, not once for a combination of all events.
Events.once = function (name, callback, context) {
// Map the event into a `{event: once}` object.
const events = eventsApi(onceMap, {}, name, callback, this.off.bind(this));
if (typeof name === 'string' && (context === null || context === undefined)) callback = undefined;
return this.on(events, callback, context);
};
// Inversion-of-control versions of `once`.
Events.listenToOnce = function (obj, name, callback) {
// Map the event into a `{event: once}` object.
const events = eventsApi(onceMap, {}, name, callback, this.stopListening.bind(this, obj));
return this.listenTo(obj, events);
};
// Reduces the event callbacks into a map of `{event: onceWrapper}`.
// `offer` unbinds the `onceWrapper` after it has been called.
const onceMap = function (map, name, callback, offer) {
if (callback) {
const _once = map[name] = lodash_es_once(function () {
offer(name, _once);
callback.apply(this, arguments);
});
_once._callback = callback;
}
return map;
};
// Trigger one or many events, firing all bound callbacks. Callbacks are
// passed the same arguments as `trigger` is, apart from the event name
// (unless you're listening on `"all"`, which will cause your callback to
// receive the true name of the event as the first argument).
Events.trigger = function (name) {
if (!this._events) return this;
const length = Math.max(0, arguments.length - 1);
const args = Array(length);
for (let i = 0; i < length; i++) args[i] = arguments[i + 1];
eventsApi(triggerApi, this._events, name, undefined, args);
return this;
};
// Handles triggering the appropriate event callbacks.
const triggerApi = function (objEvents, name, callback, args) {
if (objEvents) {
const events = objEvents[name];
let allEvents = objEvents.all;
if (events && allEvents) allEvents = allEvents.slice();
if (events) triggerEvents(events, args);
if (allEvents) triggerEvents(allEvents, [name].concat(args));
}
return objEvents;
};
// A difficult-to-believe, but optimized internal dispatch function for
// triggering events. Tries to keep the usual cases speedy (most internal
// Backbone events have 3 arguments).
const triggerEvents = function (events, args) {
let ev,
i = -1;
const l = events.length,
a1 = args[0],
a2 = args[1],
a3 = args[2];
switch (args.length) {
case 0:
while (++i < l) (ev = events[i]).callback.call(ev.ctx);
return;
case 1:
while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1);
return;
case 2:
while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2);
return;
case 3:
while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3);
return;
default:
while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
return;
}
};
// A listening class that tracks and cleans up memory bindings
// when all callbacks have been offed.
const Listening = function (listener, obj) {
this.id = listener._listenId;
this.listener = listener;
this.obj = obj;
this.interop = true;
this.count = 0;
this._events = undefined;
};
Listening.prototype.on = Events.on;
// Offs a callback (or several).
// Uses an optimized counter if the listenee uses Backbone.Events.
// Otherwise, falls back to manual tracking to support events
// library interop.
Listening.prototype.off = function (name, callback) {
let cleanup;
if (this.interop) {
this._events = eventsApi(offApi, this._events, name, callback, {
context: undefined,
listeners: undefined
});
cleanup = !this._events;
} else {
this.count--;
cleanup = this.count === 0;
}
if (cleanup) this.cleanup();
};
// Cleans up memory bindings between the listener and the listenee.
Listening.prototype.cleanup = function () {
delete this.listener._listeningTo[this.obj._listenId];
if (!this.interop) delete this.obj._listeners[this.id];
};
// Aliases for backwards compatibility.
Events.bind = Events.on;
Events.unbind = Events.off;
;// CONCATENATED MODULE: ./node_modules/lodash-es/_stackClear.js
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new _ListCache;
this.size = 0;
}
/* harmony default export */ const _stackClear = (stackClear);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_stackDelete.js
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
/* harmony default export */ const _stackDelete = (stackDelete);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_stackGet.js
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
/* harmony default export */ const _stackGet = (stackGet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_stackHas.js
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
/* harmony default export */ const _stackHas = (stackHas);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_stackSet.js
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof _ListCache) {
var pairs = data.__data__;
if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new _MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
/* harmony default export */ const _stackSet = (stackSet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_Stack.js
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new _ListCache(entries);
this.size = data.size;
}
// Add methods to `Stack`.
Stack.prototype.clear = _stackClear;
Stack.prototype['delete'] = _stackDelete;
Stack.prototype.get = _stackGet;
Stack.prototype.has = _stackHas;
Stack.prototype.set = _stackSet;
/* harmony default export */ const _Stack = (Stack);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayEach.js
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
/* harmony default export */ const _arrayEach = (arrayEach);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseAssignIn.js
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && _copyObject(source, lodash_es_keysIn(source), object);
}
/* harmony default export */ const _baseAssignIn = (baseAssignIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneBuffer.js
/** Detect free variable `exports`. */
var _cloneBuffer_freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var _cloneBuffer_freeModule = _cloneBuffer_freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var _cloneBuffer_moduleExports = _cloneBuffer_freeModule && _cloneBuffer_freeModule.exports === _cloneBuffer_freeExports;
/** Built-in value references. */
var _cloneBuffer_Buffer = _cloneBuffer_moduleExports ? _root.Buffer : undefined,
allocUnsafe = _cloneBuffer_Buffer ? _cloneBuffer_Buffer.allocUnsafe : undefined;
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
/* harmony default export */ const _cloneBuffer = (cloneBuffer);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_copyArray.js
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
/* harmony default export */ const _copyArray = (copyArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayFilter.js
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
/* harmony default export */ const _arrayFilter = (arrayFilter);
;// CONCATENATED MODULE: ./node_modules/lodash-es/stubArray.js
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
/* harmony default export */ const lodash_es_stubArray = (stubArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getSymbols.js
/** Used for built-in method references. */
var _getSymbols_objectProto = Object.prototype;
/** Built-in value references. */
var _getSymbols_propertyIsEnumerable = _getSymbols_objectProto.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? lodash_es_stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return _arrayFilter(nativeGetSymbols(object), function(symbol) {
return _getSymbols_propertyIsEnumerable.call(object, symbol);
});
};
/* harmony default export */ const _getSymbols = (getSymbols);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_copySymbols.js
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return _copyObject(source, _getSymbols(source), object);
}
/* harmony default export */ const _copySymbols = (copySymbols);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayPush.js
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
/* harmony default export */ const _arrayPush = (arrayPush);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getPrototype.js
/** Built-in value references. */
var getPrototype = _overArg(Object.getPrototypeOf, Object);
/* harmony default export */ const _getPrototype = (getPrototype);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getSymbolsIn.js
/* Built-in method references for those with the same name as other `lodash` methods. */
var _getSymbolsIn_nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !_getSymbolsIn_nativeGetSymbols ? lodash_es_stubArray : function(object) {
var result = [];
while (object) {
_arrayPush(result, _getSymbols(object));
object = _getPrototype(object);
}
return result;
};
/* harmony default export */ const _getSymbolsIn = (getSymbolsIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_copySymbolsIn.js
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return _copyObject(source, _getSymbolsIn(source), object);
}
/* harmony default export */ const _copySymbolsIn = (copySymbolsIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseGetAllKeys.js
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return lodash_es_isArray(object) ? result : _arrayPush(result, symbolsFunc(object));
}
/* harmony default export */ const _baseGetAllKeys = (baseGetAllKeys);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getAllKeys.js
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return _baseGetAllKeys(object, lodash_es_keys, _getSymbols);
}
/* harmony default export */ const _getAllKeys = (getAllKeys);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getAllKeysIn.js
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return _baseGetAllKeys(object, lodash_es_keysIn, _getSymbolsIn);
}
/* harmony default export */ const _getAllKeysIn = (getAllKeysIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_initCloneArray.js
/** Used for built-in method references. */
var _initCloneArray_objectProto = Object.prototype;
/** Used to check objects for own properties. */
var _initCloneArray_hasOwnProperty = _initCloneArray_objectProto.hasOwnProperty;
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && _initCloneArray_hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
/* harmony default export */ const _initCloneArray = (initCloneArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_Uint8Array.js
/** Built-in value references. */
var _Uint8Array_Uint8Array = _root.Uint8Array;
/* harmony default export */ const _Uint8Array = (_Uint8Array_Uint8Array);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneArrayBuffer.js
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
return result;
}
/* harmony default export */ const _cloneArrayBuffer = (cloneArrayBuffer);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneDataView.js
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
/* harmony default export */ const _cloneDataView = (cloneDataView);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneRegExp.js
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
/* harmony default export */ const _cloneRegExp = (cloneRegExp);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneSymbol.js
/** Used to convert symbols to primitives and strings. */
var _cloneSymbol_symbolProto = _Symbol ? _Symbol.prototype : undefined,
symbolValueOf = _cloneSymbol_symbolProto ? _cloneSymbol_symbolProto.valueOf : undefined;
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
/* harmony default export */ const _cloneSymbol = (cloneSymbol);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_cloneTypedArray.js
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
/* harmony default export */ const _cloneTypedArray = (cloneTypedArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_initCloneByTag.js
/** `Object#toString` result references. */
var _initCloneByTag_boolTag = '[object Boolean]',
_initCloneByTag_dateTag = '[object Date]',
_initCloneByTag_mapTag = '[object Map]',
_initCloneByTag_numberTag = '[object Number]',
_initCloneByTag_regexpTag = '[object RegExp]',
_initCloneByTag_setTag = '[object Set]',
_initCloneByTag_stringTag = '[object String]',
_initCloneByTag_symbolTag = '[object Symbol]';
var _initCloneByTag_arrayBufferTag = '[object ArrayBuffer]',
_initCloneByTag_dataViewTag = '[object DataView]',
_initCloneByTag_float32Tag = '[object Float32Array]',
_initCloneByTag_float64Tag = '[object Float64Array]',
_initCloneByTag_int8Tag = '[object Int8Array]',
_initCloneByTag_int16Tag = '[object Int16Array]',
_initCloneByTag_int32Tag = '[object Int32Array]',
_initCloneByTag_uint8Tag = '[object Uint8Array]',
_initCloneByTag_uint8ClampedTag = '[object Uint8ClampedArray]',
_initCloneByTag_uint16Tag = '[object Uint16Array]',
_initCloneByTag_uint32Tag = '[object Uint32Array]';
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case _initCloneByTag_arrayBufferTag:
return _cloneArrayBuffer(object);
case _initCloneByTag_boolTag:
case _initCloneByTag_dateTag:
return new Ctor(+object);
case _initCloneByTag_dataViewTag:
return _cloneDataView(object, isDeep);
case _initCloneByTag_float32Tag: case _initCloneByTag_float64Tag:
case _initCloneByTag_int8Tag: case _initCloneByTag_int16Tag: case _initCloneByTag_int32Tag:
case _initCloneByTag_uint8Tag: case _initCloneByTag_uint8ClampedTag: case _initCloneByTag_uint16Tag: case _initCloneByTag_uint32Tag:
return _cloneTypedArray(object, isDeep);
case _initCloneByTag_mapTag:
return new Ctor;
case _initCloneByTag_numberTag:
case _initCloneByTag_stringTag:
return new Ctor(object);
case _initCloneByTag_regexpTag:
return _cloneRegExp(object);
case _initCloneByTag_setTag:
return new Ctor;
case _initCloneByTag_symbolTag:
return _cloneSymbol(object);
}
}
/* harmony default export */ const _initCloneByTag = (initCloneByTag);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_initCloneObject.js
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !_isPrototype(object))
? _baseCreate(_getPrototype(object))
: {};
}
/* harmony default export */ const _initCloneObject = (initCloneObject);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsMap.js
/** `Object#toString` result references. */
var _baseIsMap_mapTag = '[object Map]';
/**
* The base implementation of `_.isMap` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
*/
function baseIsMap(value) {
return lodash_es_isObjectLike(value) && _getTag(value) == _baseIsMap_mapTag;
}
/* harmony default export */ const _baseIsMap = (baseIsMap);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isMap.js
/* Node.js helper references. */
var nodeIsMap = _nodeUtil && _nodeUtil.isMap;
/**
* Checks if `value` is classified as a `Map` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
* @example
*
* _.isMap(new Map);
* // => true
*
* _.isMap(new WeakMap);
* // => false
*/
var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap;
/* harmony default export */ const lodash_es_isMap = (isMap);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsSet.js
/** `Object#toString` result references. */
var _baseIsSet_setTag = '[object Set]';
/**
* The base implementation of `_.isSet` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
*/
function baseIsSet(value) {
return lodash_es_isObjectLike(value) && _getTag(value) == _baseIsSet_setTag;
}
/* harmony default export */ const _baseIsSet = (baseIsSet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isSet.js
/* Node.js helper references. */
var nodeIsSet = _nodeUtil && _nodeUtil.isSet;
/**
* Checks if `value` is classified as a `Set` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
* @example
*
* _.isSet(new Set);
* // => true
*
* _.isSet(new WeakSet);
* // => false
*/
var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet;
/* harmony default export */ const lodash_es_isSet = (isSet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseClone.js
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** `Object#toString` result references. */
var _baseClone_argsTag = '[object Arguments]',
_baseClone_arrayTag = '[object Array]',
_baseClone_boolTag = '[object Boolean]',
_baseClone_dateTag = '[object Date]',
_baseClone_errorTag = '[object Error]',
_baseClone_funcTag = '[object Function]',
_baseClone_genTag = '[object GeneratorFunction]',
_baseClone_mapTag = '[object Map]',
_baseClone_numberTag = '[object Number]',
_baseClone_objectTag = '[object Object]',
_baseClone_regexpTag = '[object RegExp]',
_baseClone_setTag = '[object Set]',
_baseClone_stringTag = '[object String]',
_baseClone_symbolTag = '[object Symbol]',
_baseClone_weakMapTag = '[object WeakMap]';
var _baseClone_arrayBufferTag = '[object ArrayBuffer]',
_baseClone_dataViewTag = '[object DataView]',
_baseClone_float32Tag = '[object Float32Array]',
_baseClone_float64Tag = '[object Float64Array]',
_baseClone_int8Tag = '[object Int8Array]',
_baseClone_int16Tag = '[object Int16Array]',
_baseClone_int32Tag = '[object Int32Array]',
_baseClone_uint8Tag = '[object Uint8Array]',
_baseClone_uint8ClampedTag = '[object Uint8ClampedArray]',
_baseClone_uint16Tag = '[object Uint16Array]',
_baseClone_uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[_baseClone_argsTag] = cloneableTags[_baseClone_arrayTag] =
cloneableTags[_baseClone_arrayBufferTag] = cloneableTags[_baseClone_dataViewTag] =
cloneableTags[_baseClone_boolTag] = cloneableTags[_baseClone_dateTag] =
cloneableTags[_baseClone_float32Tag] = cloneableTags[_baseClone_float64Tag] =
cloneableTags[_baseClone_int8Tag] = cloneableTags[_baseClone_int16Tag] =
cloneableTags[_baseClone_int32Tag] = cloneableTags[_baseClone_mapTag] =
cloneableTags[_baseClone_numberTag] = cloneableTags[_baseClone_objectTag] =
cloneableTags[_baseClone_regexpTag] = cloneableTags[_baseClone_setTag] =
cloneableTags[_baseClone_stringTag] = cloneableTags[_baseClone_symbolTag] =
cloneableTags[_baseClone_uint8Tag] = cloneableTags[_baseClone_uint8ClampedTag] =
cloneableTags[_baseClone_uint16Tag] = cloneableTags[_baseClone_uint32Tag] = true;
cloneableTags[_baseClone_errorTag] = cloneableTags[_baseClone_funcTag] =
cloneableTags[_baseClone_weakMapTag] = false;
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!lodash_es_isObject(value)) {
return value;
}
var isArr = lodash_es_isArray(value);
if (isArr) {
result = _initCloneArray(value);
if (!isDeep) {
return _copyArray(value, result);
}
} else {
var tag = _getTag(value),
isFunc = tag == _baseClone_funcTag || tag == _baseClone_genTag;
if (lodash_es_isBuffer(value)) {
return _cloneBuffer(value, isDeep);
}
if (tag == _baseClone_objectTag || tag == _baseClone_argsTag || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : _initCloneObject(value);
if (!isDeep) {
return isFlat
? _copySymbolsIn(value, _baseAssignIn(result, value))
: _copySymbols(value, _baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = _initCloneByTag(value, tag, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new _Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (lodash_es_isSet(value)) {
value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
});
} else if (lodash_es_isMap(value)) {
value.forEach(function(subValue, key) {
result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
}
var keysFunc = isFull
? (isFlat ? _getAllKeysIn : _getAllKeys)
: (isFlat ? lodash_es_keysIn : lodash_es_keys);
var props = isArr ? undefined : keysFunc(value);
_arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
_assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
/* harmony default export */ const _baseClone = (baseClone);
;// CONCATENATED MODULE: ./node_modules/lodash-es/clone.js
/** Used to compose bitmasks for cloning. */
var clone_CLONE_SYMBOLS_FLAG = 4;
/**
* Creates a shallow clone of `value`.
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
* and supports cloning arrays, array buffers, booleans, date objects, maps,
* numbers, `Object` objects, regexes, sets, strings, symbols, and typed
* arrays. The own enumerable properties of `arguments` objects are cloned
* as plain objects. An empty object is returned for uncloneable values such
* as error objects, functions, DOM nodes, and WeakMaps.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to clone.
* @returns {*} Returns the cloned value.
* @see _.cloneDeep
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var shallow = _.clone(objects);
* console.log(shallow[0] === objects[0]);
* // => true
*/
function clone(value) {
return _baseClone(value, clone_CLONE_SYMBOLS_FLAG);
}
/* harmony default export */ const lodash_es_clone = (clone);
;// CONCATENATED MODULE: ./node_modules/lodash-es/defaults.js
/** Used for built-in method references. */
var defaults_objectProto = Object.prototype;
/** Used to check objects for own properties. */
var defaults_hasOwnProperty = defaults_objectProto.hasOwnProperty;
/**
* Assigns own and inherited enumerable string keyed properties of source
* objects to the destination object for all destination properties that
* resolve to `undefined`. Source objects are applied from left to right.
* Once a property is set, additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaultsDeep
* @example
*
* _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var defaults = _baseRest(function(object, sources) {
object = Object(object);
var index = -1;
var length = sources.length;
var guard = length > 2 ? sources[2] : undefined;
if (guard && _isIterateeCall(sources[0], sources[1], guard)) {
length = 1;
}
while (++index < length) {
var source = sources[index];
var props = lodash_es_keysIn(source);
var propsIndex = -1;
var propsLength = props.length;
while (++propsIndex < propsLength) {
var key = props[propsIndex];
var value = object[key];
if (value === undefined ||
(lodash_es_eq(value, defaults_objectProto[key]) && !defaults_hasOwnProperty.call(object, key))) {
object[key] = source[key];
}
}
}
return object;
});
/* harmony default export */ const lodash_es_defaults = (defaults);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseDelay.js
/** Error message constants. */
var _baseDelay_FUNC_ERROR_TEXT = 'Expected a function';
/**
* The base implementation of `_.delay` and `_.defer` which accepts `args`
* to provide to `func`.
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {Array} args The arguments to provide to `func`.
* @returns {number|Object} Returns the timer id or timeout object.
*/
function baseDelay(func, wait, args) {
if (typeof func != 'function') {
throw new TypeError(_baseDelay_FUNC_ERROR_TEXT);
}
return setTimeout(function() { func.apply(undefined, args); }, wait);
}
/* harmony default export */ const _baseDelay = (baseDelay);
;// CONCATENATED MODULE: ./node_modules/lodash-es/defer.js
/**
* Defers invoking the `func` until the current call stack has cleared. Any
* additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to defer.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* _.defer(function(text) {
* console.log(text);
* }, 'deferred');
* // => Logs 'deferred' after one millisecond.
*/
var defer = _baseRest(function(func, args) {
return _baseDelay(func, 1, args);
});
/* harmony default export */ const lodash_es_defer = (defer);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_basePropertyOf.js
/**
* The base implementation of `_.propertyOf` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyOf(object) {
return function(key) {
return object == null ? undefined : object[key];
};
}
/* harmony default export */ const _basePropertyOf = (basePropertyOf);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_escapeHtmlChar.js
/** Used to map characters to HTML entities. */
var htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
/**
* Used by `_.escape` to convert characters to HTML entities.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
var escapeHtmlChar = _basePropertyOf(htmlEscapes);
/* harmony default export */ const _escapeHtmlChar = (escapeHtmlChar);
;// CONCATENATED MODULE: ./node_modules/lodash-es/escape.js
/** Used to match HTML entities and HTML characters. */
var reUnescapedHtml = /[&<>"']/g,
reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
/**
* Converts the characters "&", "<", ">", '"', and "'" in `string` to their
* corresponding HTML entities.
*
* **Note:** No other characters are escaped. To escape additional
* characters use a third-party library like [_he_](https://mths.be/he).
*
* Though the ">" character is escaped for symmetry, characters like
* ">" and "/" don't need escaping in HTML and have no special meaning
* unless they're part of a tag or unquoted attribute value. See
* [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
* (under "semi-related fun fact") for more details.
*
* When working with HTML you should always
* [quote attribute values](http://wonko.com/post/html-escaping) to reduce
* XSS vectors.
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escape('fred, barney, & pebbles');
* // => 'fred, barney, & pebbles'
*/
function escape_escape(string) {
string = lodash_es_toString(string);
return (string && reHasUnescapedHtml.test(string))
? string.replace(reUnescapedHtml, _escapeHtmlChar)
: string;
}
/* harmony default export */ const lodash_es_escape = (escape_escape);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_createBaseFor.js
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
/* harmony default export */ const _createBaseFor = (createBaseFor);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseFor.js
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = _createBaseFor();
/* harmony default export */ const _baseFor = (baseFor);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseForOwn.js
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && _baseFor(object, iteratee, lodash_es_keys);
}
/* harmony default export */ const _baseForOwn = (baseForOwn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseInverter.js
/**
* The base implementation of `_.invert` and `_.invertBy` which inverts
* `object` with values transformed by `iteratee` and set by `setter`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform values.
* @param {Object} accumulator The initial inverted object.
* @returns {Function} Returns `accumulator`.
*/
function baseInverter(object, setter, iteratee, accumulator) {
_baseForOwn(object, function(value, key, object) {
setter(accumulator, iteratee(value), key, object);
});
return accumulator;
}
/* harmony default export */ const _baseInverter = (baseInverter);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_createInverter.js
/**
* Creates a function like `_.invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} toIteratee The function to resolve iteratees.
* @returns {Function} Returns the new inverter function.
*/
function createInverter(setter, toIteratee) {
return function(object, iteratee) {
return _baseInverter(object, setter, toIteratee(iteratee), {});
};
}
/* harmony default export */ const _createInverter = (createInverter);
;// CONCATENATED MODULE: ./node_modules/lodash-es/invert.js
/** Used for built-in method references. */
var invert_objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var invert_nativeObjectToString = invert_objectProto.toString;
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*/
var invert = _createInverter(function(result, value, key) {
if (value != null &&
typeof value.toString != 'function') {
value = invert_nativeObjectToString.call(value);
}
result[value] = key;
}, lodash_es_constant(lodash_es_identity));
/* harmony default export */ const lodash_es_invert = (invert);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_setCacheAdd.js
/** Used to stand-in for `undefined` hash values. */
var _setCacheAdd_HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, _setCacheAdd_HASH_UNDEFINED);
return this;
}
/* harmony default export */ const _setCacheAdd = (setCacheAdd);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_setCacheHas.js
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
/* harmony default export */ const _setCacheHas = (setCacheHas);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_SetCache.js
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new _MapCache;
while (++index < length) {
this.add(values[index]);
}
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
SetCache.prototype.has = _setCacheHas;
/* harmony default export */ const _SetCache = (SetCache);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arraySome.js
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
/* harmony default export */ const _arraySome = (arraySome);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_cacheHas.js
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
/* harmony default export */ const _cacheHas = (cacheHas);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_equalArrays.js
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Check that cyclic values are equal.
var arrStacked = stack.get(array);
var othStacked = stack.get(other);
if (arrStacked && othStacked) {
return arrStacked == other && othStacked == array;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!_arraySome(other, function(othValue, othIndex) {
if (!_cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
/* harmony default export */ const _equalArrays = (equalArrays);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapToArray.js
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
/* harmony default export */ const _mapToArray = (mapToArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_setToArray.js
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
/* harmony default export */ const _setToArray = (setToArray);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_equalByTag.js
/** Used to compose bitmasks for value comparisons. */
var _equalByTag_COMPARE_PARTIAL_FLAG = 1,
_equalByTag_COMPARE_UNORDERED_FLAG = 2;
/** `Object#toString` result references. */
var _equalByTag_boolTag = '[object Boolean]',
_equalByTag_dateTag = '[object Date]',
_equalByTag_errorTag = '[object Error]',
_equalByTag_mapTag = '[object Map]',
_equalByTag_numberTag = '[object Number]',
_equalByTag_regexpTag = '[object RegExp]',
_equalByTag_setTag = '[object Set]',
_equalByTag_stringTag = '[object String]',
_equalByTag_symbolTag = '[object Symbol]';
var _equalByTag_arrayBufferTag = '[object ArrayBuffer]',
_equalByTag_dataViewTag = '[object DataView]';
/** Used to convert symbols to primitives and strings. */
var _equalByTag_symbolProto = _Symbol ? _Symbol.prototype : undefined,
_equalByTag_symbolValueOf = _equalByTag_symbolProto ? _equalByTag_symbolProto.valueOf : undefined;
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case _equalByTag_dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case _equalByTag_arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
return false;
}
return true;
case _equalByTag_boolTag:
case _equalByTag_dateTag:
case _equalByTag_numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return lodash_es_eq(+object, +other);
case _equalByTag_errorTag:
return object.name == other.name && object.message == other.message;
case _equalByTag_regexpTag:
case _equalByTag_stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case _equalByTag_mapTag:
var convert = _mapToArray;
case _equalByTag_setTag:
var isPartial = bitmask & _equalByTag_COMPARE_PARTIAL_FLAG;
convert || (convert = _setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= _equalByTag_COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case _equalByTag_symbolTag:
if (_equalByTag_symbolValueOf) {
return _equalByTag_symbolValueOf.call(object) == _equalByTag_symbolValueOf.call(other);
}
}
return false;
}
/* harmony default export */ const _equalByTag = (equalByTag);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_equalObjects.js
/** Used to compose bitmasks for value comparisons. */
var _equalObjects_COMPARE_PARTIAL_FLAG = 1;
/** Used for built-in method references. */
var _equalObjects_objectProto = Object.prototype;
/** Used to check objects for own properties. */
var _equalObjects_hasOwnProperty = _equalObjects_objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & _equalObjects_COMPARE_PARTIAL_FLAG,
objProps = _getAllKeys(object),
objLength = objProps.length,
othProps = _getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : _equalObjects_hasOwnProperty.call(other, key))) {
return false;
}
}
// Check that cyclic values are equal.
var objStacked = stack.get(object);
var othStacked = stack.get(other);
if (objStacked && othStacked) {
return objStacked == other && othStacked == object;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
/* harmony default export */ const _equalObjects = (equalObjects);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsEqualDeep.js
/** Used to compose bitmasks for value comparisons. */
var _baseIsEqualDeep_COMPARE_PARTIAL_FLAG = 1;
/** `Object#toString` result references. */
var _baseIsEqualDeep_argsTag = '[object Arguments]',
_baseIsEqualDeep_arrayTag = '[object Array]',
_baseIsEqualDeep_objectTag = '[object Object]';
/** Used for built-in method references. */
var _baseIsEqualDeep_objectProto = Object.prototype;
/** Used to check objects for own properties. */
var _baseIsEqualDeep_hasOwnProperty = _baseIsEqualDeep_objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = lodash_es_isArray(object),
othIsArr = lodash_es_isArray(other),
objTag = objIsArr ? _baseIsEqualDeep_arrayTag : _getTag(object),
othTag = othIsArr ? _baseIsEqualDeep_arrayTag : _getTag(other);
objTag = objTag == _baseIsEqualDeep_argsTag ? _baseIsEqualDeep_objectTag : objTag;
othTag = othTag == _baseIsEqualDeep_argsTag ? _baseIsEqualDeep_objectTag : othTag;
var objIsObj = objTag == _baseIsEqualDeep_objectTag,
othIsObj = othTag == _baseIsEqualDeep_objectTag,
isSameTag = objTag == othTag;
if (isSameTag && lodash_es_isBuffer(object)) {
if (!lodash_es_isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new _Stack);
return (objIsArr || lodash_es_isTypedArray(object))
? _equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & _baseIsEqualDeep_COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && _baseIsEqualDeep_hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && _baseIsEqualDeep_hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new _Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new _Stack);
return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
/* harmony default export */ const _baseIsEqualDeep = (baseIsEqualDeep);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsEqual.js
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!lodash_es_isObjectLike(value) && !lodash_es_isObjectLike(other))) {
return value !== value && other !== other;
}
return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
/* harmony default export */ const _baseIsEqual = (baseIsEqual);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isEqual.js
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return _baseIsEqual(value, other);
}
/* harmony default export */ const lodash_es_isEqual = (isEqual);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsMatch.js
/** Used to compose bitmasks for value comparisons. */
var _baseIsMatch_COMPARE_PARTIAL_FLAG = 1,
_baseIsMatch_COMPARE_UNORDERED_FLAG = 2;
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new _Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? _baseIsEqual(srcValue, objValue, _baseIsMatch_COMPARE_PARTIAL_FLAG | _baseIsMatch_COMPARE_UNORDERED_FLAG, customizer, stack)
: result
)) {
return false;
}
}
}
return true;
}
/* harmony default export */ const _baseIsMatch = (baseIsMatch);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isStrictComparable.js
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !lodash_es_isObject(value);
}
/* harmony default export */ const _isStrictComparable = (isStrictComparable);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_getMatchData.js
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = lodash_es_keys(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, _isStrictComparable(value)];
}
return result;
}
/* harmony default export */ const _getMatchData = (getMatchData);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_matchesStrictComparable.js
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
/* harmony default export */ const _matchesStrictComparable = (matchesStrictComparable);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseMatches.js
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatches(source) {
var matchData = _getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || _baseIsMatch(object, source, matchData);
};
}
/* harmony default export */ const _baseMatches = (baseMatches);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseGet.js
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = _castPath(path, object);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[_toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
/* harmony default export */ const _baseGet = (baseGet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/get.js
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : _baseGet(object, path);
return result === undefined ? defaultValue : result;
}
/* harmony default export */ const lodash_es_get = (get);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseHasIn.js
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
/* harmony default export */ const _baseHasIn = (baseHasIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/hasIn.js
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && _hasPath(object, path, _baseHasIn);
}
/* harmony default export */ const lodash_es_hasIn = (hasIn);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseMatchesProperty.js
/** Used to compose bitmasks for value comparisons. */
var _baseMatchesProperty_COMPARE_PARTIAL_FLAG = 1,
_baseMatchesProperty_COMPARE_UNORDERED_FLAG = 2;
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (_isKey(path) && _isStrictComparable(srcValue)) {
return _matchesStrictComparable(_toKey(path), srcValue);
}
return function(object) {
var objValue = lodash_es_get(object, path);
return (objValue === undefined && objValue === srcValue)
? lodash_es_hasIn(object, path)
: _baseIsEqual(srcValue, objValue, _baseMatchesProperty_COMPARE_PARTIAL_FLAG | _baseMatchesProperty_COMPARE_UNORDERED_FLAG);
};
}
/* harmony default export */ const _baseMatchesProperty = (baseMatchesProperty);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseProperty.js
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/* harmony default export */ const _baseProperty = (baseProperty);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_basePropertyDeep.js
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return _baseGet(object, path);
};
}
/* harmony default export */ const _basePropertyDeep = (basePropertyDeep);
;// CONCATENATED MODULE: ./node_modules/lodash-es/property.js
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
}
/* harmony default export */ const lodash_es_property = (property);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIteratee.js
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return lodash_es_identity;
}
if (typeof value == 'object') {
return lodash_es_isArray(value)
? _baseMatchesProperty(value[0], value[1])
: _baseMatches(value);
}
return lodash_es_property(value);
}
/* harmony default export */ const _baseIteratee = (baseIteratee);
;// CONCATENATED MODULE: ./node_modules/lodash-es/iteratee.js
/** Used to compose bitmasks for cloning. */
var iteratee_CLONE_DEEP_FLAG = 1;
/**
* Creates a function that invokes `func` with the arguments of the created
* function. If `func` is a property name, the created function returns the
* property value for a given element. If `func` is an array or object, the
* created function returns `true` for elements that contain the equivalent
* source properties, otherwise it returns `false`.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Util
* @param {*} [func=_.identity] The value to convert to a callback.
* @returns {Function} Returns the callback.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
* // => [{ 'user': 'barney', 'age': 36, 'active': true }]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, _.iteratee(['user', 'fred']));
* // => [{ 'user': 'fred', 'age': 40 }]
*
* // The `_.property` iteratee shorthand.
* _.map(users, _.iteratee('user'));
* // => ['barney', 'fred']
*
* // Create custom iteratee shorthands.
* _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
* return !_.isRegExp(func) ? iteratee(func) : function(string) {
* return func.test(string);
* };
* });
*
* _.filter(['abc', 'def'], /ef/);
* // => ['def']
*/
function iteratee(func) {
return _baseIteratee(typeof func == 'function' ? func : _baseClone(func, iteratee_CLONE_DEEP_FLAG));
}
/* harmony default export */ const lodash_es_iteratee = (iteratee);
;// CONCATENATED MODULE: ./node_modules/lodash-es/last.js
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
/* harmony default export */ const lodash_es_last = (last);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSlice.js
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
/* harmony default export */ const _baseSlice = (baseSlice);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_parent.js
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function _parent_parent(object, path) {
return path.length < 2 ? object : _baseGet(object, _baseSlice(path, 0, -1));
}
/* harmony default export */ const _parent = (_parent_parent);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseUnset.js
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = _castPath(path, object);
object = _parent(object, path);
return object == null || delete object[_toKey(lodash_es_last(path))];
}
/* harmony default export */ const _baseUnset = (baseUnset);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isPlainObject.js
/** `Object#toString` result references. */
var isPlainObject_objectTag = '[object Object]';
/** Used for built-in method references. */
var isPlainObject_funcProto = Function.prototype,
isPlainObject_objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var isPlainObject_funcToString = isPlainObject_funcProto.toString;
/** Used to check objects for own properties. */
var isPlainObject_hasOwnProperty = isPlainObject_objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = isPlainObject_funcToString.call(Object);
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!lodash_es_isObjectLike(value) || _baseGetTag(value) != isPlainObject_objectTag) {
return false;
}
var proto = _getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = isPlainObject_hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
isPlainObject_funcToString.call(Ctor) == objectCtorString;
}
/* harmony default export */ const lodash_es_isPlainObject = (isPlainObject);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_customOmitClone.js
/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/
function customOmitClone(value) {
return lodash_es_isPlainObject(value) ? undefined : value;
}
/* harmony default export */ const _customOmitClone = (customOmitClone);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_isFlattenable.js
/** Built-in value references. */
var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return lodash_es_isArray(value) || lodash_es_isArguments(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
/* harmony default export */ const _isFlattenable = (isFlattenable);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseFlatten.js
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = _isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
_arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
/* harmony default export */ const _baseFlatten = (baseFlatten);
;// CONCATENATED MODULE: ./node_modules/lodash-es/flatten.js
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array == null ? 0 : array.length;
return length ? _baseFlatten(array, 1) : [];
}
/* harmony default export */ const lodash_es_flatten = (flatten);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_flatRest.js
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest(func) {
return _setToString(_overRest(func, undefined, lodash_es_flatten), func + '');
}
/* harmony default export */ const _flatRest = (flatRest);
;// CONCATENATED MODULE: ./node_modules/lodash-es/omit.js
/** Used to compose bitmasks for cloning. */
var omit_CLONE_DEEP_FLAG = 1,
omit_CLONE_FLAT_FLAG = 2,
omit_CLONE_SYMBOLS_FLAG = 4;
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = _flatRest(function(object, paths) {
var result = {};
if (object == null) {
return result;
}
var isDeep = false;
paths = _arrayMap(paths, function(path) {
path = _castPath(path, object);
isDeep || (isDeep = path.length > 1);
return path;
});
_copyObject(object, _getAllKeysIn(object), result);
if (isDeep) {
result = _baseClone(result, omit_CLONE_DEEP_FLAG | omit_CLONE_FLAT_FLAG | omit_CLONE_SYMBOLS_FLAG, _customOmitClone);
}
var length = paths.length;
while (length--) {
_baseUnset(result, paths[length]);
}
return result;
});
/* harmony default export */ const lodash_es_omit = (omit);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSet.js
/**
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseSet(object, path, value, customizer) {
if (!lodash_es_isObject(object)) {
return object;
}
path = _castPath(path, object);
var index = -1,
length = path.length,
lastIndex = length - 1,
nested = object;
while (nested != null && ++index < length) {
var key = _toKey(path[index]),
newValue = value;
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return object;
}
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : undefined;
if (newValue === undefined) {
newValue = lodash_es_isObject(objValue)
? objValue
: (_isIndex(path[index + 1]) ? [] : {});
}
}
_assignValue(nested, key, newValue);
nested = nested[key];
}
return object;
}
/* harmony default export */ const _baseSet = (baseSet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_basePickBy.js
/**
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
*/
function basePickBy(object, paths, predicate) {
var index = -1,
length = paths.length,
result = {};
while (++index < length) {
var path = paths[index],
value = _baseGet(object, path);
if (predicate(value, path)) {
_baseSet(result, _castPath(path, object), value);
}
}
return result;
}
/* harmony default export */ const _basePickBy = (basePickBy);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_basePick.js
/**
* The base implementation of `_.pick` without support for individual
* property identifiers.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @returns {Object} Returns the new object.
*/
function basePick(object, paths) {
return _basePickBy(object, paths, function(value, path) {
return lodash_es_hasIn(object, path);
});
}
/* harmony default export */ const _basePick = (basePick);
;// CONCATENATED MODULE: ./node_modules/lodash-es/pick.js
/**
* Creates an object composed of the picked `object` properties.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pick(object, ['a', 'c']);
* // => { 'a': 1, 'c': 3 }
*/
var pick = _flatRest(function(object, paths) {
return object == null ? {} : _basePick(object, paths);
});
/* harmony default export */ const lodash_es_pick = (pick);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/model.js
// Backbone.js 1.4.0
// (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
// Backbone may be freely distributed under the MIT license.
// Model
// -----
// **Models** are the basic data object in the framework --
// frequently representing a row in a table in a database on your server.
// A discrete chunk of data and a bunch of useful, related methods for
// performing computations and transformations on that data.
// Create a new model with the specified attributes. A client id (`cid`)
// is automatically generated and assigned for you.
const Model = function (attributes, options) {
let attrs = attributes || {};
options || (options = {});
this.preinitialize.apply(this, arguments);
this.cid = lodash_es_uniqueId(this.cidPrefix);
this.attributes = {};
if (options.collection) this.collection = options.collection;
if (options.parse) attrs = this.parse(attrs, options) || {};
const default_attrs = lodash_es_result(this, 'defaults');
attrs = lodash_es_defaults(lodash_es_assignIn({}, default_attrs, attrs), default_attrs);
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
};
Model.extend = inherits;
// Attach all inheritable methods to the Model prototype.
Object.assign(Model.prototype, Events, {
// A hash of attributes whose current and previous value differ.
changed: null,
// The value returned during the last failed validation.
validationError: null,
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
// CouchDB users may want to set this to `"_id"`.
idAttribute: 'id',
// The prefix is used to create the client id which is used to identify models locally.
// You may want to override this if you're experiencing name clashes with model ids.
cidPrefix: 'c',
// preinitialize is an empty function by default. You can override it with a function
// or object. preinitialize will run before any instantiation logic is run in the Model.
preinitialize: function () {},
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function () {},
// Return a copy of the model's `attributes` object.
toJSON: function (options) {
return lodash_es_clone(this.attributes);
},
// Proxy `Backbone.sync` by default -- but override this if you need
// custom syncing semantics for *this* particular model.
sync: function (method, model, options) {
return getSyncMethod(this)(method, model, options);
},
// Get the value of an attribute.
get: function (attr) {
return this.attributes[attr];
},
keys: function () {
return Object.keys(this.attributes);
},
values: function () {
return Object.values(this.attributes);
},
pairs: function () {
return this.entries();
},
entries: function () {
return Object.entries(this.attributes);
},
invert: function () {
return lodash_es_invert(this.attributes);
},
pick: function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args.length === 1 && Array.isArray(args[0])) {
args = args[0];
}
return lodash_es_pick(this.attributes, args);
},
omit: function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
if (args.length === 1 && Array.isArray(args[0])) {
args = args[0];
}
return lodash_es_omit(this.attributes, args);
},
isEmpty: function () {
return lodash_es_isEmpty(this.attributes);
},
// Get the HTML-escaped value of an attribute.
escape: function (attr) {
return lodash_es_escape(this.get(attr));
},
// Returns `true` if the attribute contains a value that is not null
// or undefined.
has: function (attr) {
return this.get(attr) != null;
},
// Special-cased proxy to lodash's `matches` method.
matches: function (attrs) {
return !!lodash_es_iteratee(attrs, this)(this.attributes);
},
// Set a hash of model attributes on the object, firing `"change"`. This is
// the core primitive operation of a model, updating the data and notifying
// anyone who needs to know about the change in state. The heart of the beast.
set: function (key, val, options) {
if (key == null) return this;
// Handle both `"key", value` and `{key: value}` -style arguments.
let attrs;
if (typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options || (options = {});
// Run validation.
if (!this._validate(attrs, options)) return false;
// Extract attributes and options.
const unset = options.unset;
const silent = options.silent;
const changes = [];
const changing = this._changing;
this._changing = true;
if (!changing) {
this._previousAttributes = lodash_es_clone(this.attributes);
this.changed = {};
}
const current = this.attributes;
const changed = this.changed;
const prev = this._previousAttributes;
// For each `set` attribute, update or delete the current value.
for (const attr in attrs) {
val = attrs[attr];
if (!lodash_es_isEqual(current[attr], val)) changes.push(attr);
if (!lodash_es_isEqual(prev[attr], val)) {
changed[attr] = val;
} else {
delete changed[attr];
}
unset ? delete current[attr] : current[attr] = val;
}
// Update the `id`.
if (this.idAttribute in attrs) this.id = this.get(this.idAttribute);
// Trigger all relevant attribute changes.
if (!silent) {
if (changes.length) this._pending = options;
for (let i = 0; i < changes.length; i++) {
this.trigger('change:' + changes[i], this, current[changes[i]], options);
}
}
// You might be wondering why there's a `while` loop here. Changes can
// be recursively nested within `"change"` events.
if (changing) return this;
if (!silent) {
while (this._pending) {
options = this._pending;
this._pending = false;
this.trigger('change', this, options);
}
}
this._pending = false;
this._changing = false;
return this;
},
// Remove an attribute from the model, firing `"change"`. `unset` is a noop
// if the attribute doesn't exist.
unset: function (attr, options) {
return this.set(attr, undefined, lodash_es_assignIn({}, options, {
unset: true
}));
},
// Clear all attributes on the model, firing `"change"`.
clear: function (options) {
const attrs = {};
for (const key in this.attributes) attrs[key] = undefined;
return this.set(attrs, lodash_es_assignIn({}, options, {
unset: true
}));
},
// Determine if the model has changed since the last `"change"` event.
// If you specify an attribute name, determine if that attribute has changed.
hasChanged: function (attr) {
if (attr == null) return !lodash_es_isEmpty(this.changed);
return lodash_es_has(this.changed, attr);
},
// Return an object containing all the attributes that have changed, or
// false if there are no changed attributes. Useful for determining what
// parts of a view need to be updated and/or what attributes need to be
// persisted to the server. Unset attributes will be set to undefined.
// You can also pass an attributes object to diff against the model,
// determining if there *would be* a change.
changedAttributes: function (diff) {
if (!diff) return this.hasChanged() ? lodash_es_clone(this.changed) : false;
const old = this._changing ? this._previousAttributes : this.attributes;
const changed = {};
let hasChanged;
for (const attr in diff) {
const val = diff[attr];
if (lodash_es_isEqual(old[attr], val)) continue;
changed[attr] = val;
hasChanged = true;
}
return hasChanged ? changed : false;
},
// Get the previous value of an attribute, recorded at the time the last
// `"change"` event was fired.
previous: function (attr) {
if (attr == null || !this._previousAttributes) return null;
return this._previousAttributes[attr];
},
// Get all of the attributes of the model at the time of the previous
// `"change"` event.
previousAttributes: function () {
return lodash_es_clone(this._previousAttributes);
},
// Fetch the model from the server, merging the response with the model's
// local attributes. Any changed attributes will trigger a "change" event.
fetch: function (options) {
options = lodash_es_assignIn({
parse: true
}, options);
const model = this;
const success = options.success;
options.success = function (resp) {
const serverAttrs = options.parse ? model.parse(resp, options) : resp;
if (!model.set(serverAttrs, options)) return false;
if (success) success.call(options.context, model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
// Set a hash of model attributes, and sync the model to the server.
// If the server returns an attributes hash that differs, the model's
// state will be `set` again.
save: function (key, val, options) {
// Handle both `"key", value` and `{key: value}` -style arguments.
let attrs;
if (key == null || typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options = lodash_es_assignIn({
validate: true,
parse: true
}, options);
const wait = options.wait;
const return_promise = options.promise;
const promise = return_promise && getResolveablePromise();
// If we're not waiting and attributes exist, save acts as
// `set(attr).save(null, opts)` with validation. Otherwise, check if
// the model will be valid when the attributes, if any, are set.
if (attrs && !wait) {
if (!this.set(attrs, options)) return false;
} else if (!this._validate(attrs, options)) {
return false;
}
// After a successful server-side save, the client is (optionally)
// updated with the server-side state.
const model = this;
const success = options.success;
const error = options.error;
const attributes = this.attributes;
options.success = function (resp) {
// Ensure attributes are restored during synchronous saves.
model.attributes = attributes;
let serverAttrs = options.parse ? model.parse(resp, options) : resp;
if (wait) serverAttrs = lodash_es_assignIn({}, attrs, serverAttrs);
if (serverAttrs && !model.set(serverAttrs, options)) return false;
if (success) success.call(options.context, model, resp, options);
model.trigger('sync', model, resp, options);
return_promise && promise.resolve();
};
options.error = function (model, e, options) {
error && error.call(options.context, model, e, options);
return_promise && promise.reject(e);
};
wrapError(this, options);
// Set temporary attributes if `{wait: true}` to properly find new ids.
if (attrs && wait) this.attributes = lodash_es_assignIn({}, attributes, attrs);
const method = this.isNew() ? 'create' : options.patch ? 'patch' : 'update';
if (method === 'patch' && !options.attrs) options.attrs = attrs;
const xhr = this.sync(method, this, options);
// Restore attributes.
this.attributes = attributes;
if (return_promise) {
return promise;
} else {
return xhr;
}
},
// Destroy this model on the server if it was already persisted.
// Optimistically removes the model from its collection, if it has one.
// If `wait: true` is passed, waits for the server to respond before removal.
destroy: function (options) {
options = options ? lodash_es_clone(options) : {};
const model = this;
const success = options.success;
const wait = options.wait;
const destroy = function () {
model.stopListening();
model.trigger('destroy', model, model.collection, options);
};
options.success = function (resp) {
if (wait) destroy();
if (success) success.call(options.context, model, resp, options);
if (!model.isNew()) model.trigger('sync', model, resp, options);
};
let xhr = false;
if (this.isNew()) {
lodash_es_defer(options.success);
} else {
wrapError(this, options);
xhr = this.sync('delete', this, options);
}
if (!wait) destroy();
return xhr;
},
// Default URL for the model's representation on the server -- if you're
// using Backbone's restful methods, override this to change the endpoint
// that will be called.
url: function () {
const base = lodash_es_result(this, 'urlRoot') || lodash_es_result(this.collection, 'url') || urlError();
if (this.isNew()) return base;
const id = this.get(this.idAttribute);
return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
},
// **parse** converts a response into the hash of attributes to be `set` on
// the model. The default implementation is just to pass the response along.
parse: function (resp, options) {
return resp;
},
// Create a new model with identical attributes to this one.
clone: function () {
return new this.constructor(this.attributes);
},
// A model is new if it has never been saved to the server, and lacks an id.
isNew: function () {
return !this.has(this.idAttribute);
},
// Check if the model is currently in a valid state.
isValid: function (options) {
return this._validate({}, lodash_es_assignIn({}, options, {
validate: true
}));
},
// Run validation against the next complete set of model attributes,
// returning `true` if all is well. Otherwise, fire an `"invalid"` event.
_validate: function (attrs, options) {
if (!options.validate || !this.validate) return true;
attrs = lodash_es_assignIn({}, this.attributes, attrs);
const error = this.validationError = this.validate(attrs, options) || null;
if (!error) return true;
this.trigger('invalid', this, error, lodash_es_assignIn(options, {
validationError: error
}));
return false;
}
});
;// CONCATENATED MODULE: ./src/strophe-shims.js
const WebSocket = window.WebSocket;
const DOMParser = window.DOMParser;
function getDummyXMLDOMDocument() {
return document.implementation.createDocument('jabber:client', 'strophe', null);
}
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/constants.js
/**
* Common namespace constants from the XMPP RFCs and XEPs.
*
* @typedef { Object } NS
* @property {string} NS.HTTPBIND - HTTP BIND namespace from XEP 124.
* @property {string} NS.BOSH - BOSH namespace from XEP 206.
* @property {string} NS.CLIENT - Main XMPP client namespace.
* @property {string} NS.AUTH - Legacy authentication namespace.
* @property {string} NS.ROSTER - Roster operations namespace.
* @property {string} NS.PROFILE - Profile namespace.
* @property {string} NS.DISCO_INFO - Service discovery info namespace from XEP 30.
* @property {string} NS.DISCO_ITEMS - Service discovery items namespace from XEP 30.
* @property {string} NS.MUC - Multi-User Chat namespace from XEP 45.
* @property {string} NS.SASL - XMPP SASL namespace from RFC 3920.
* @property {string} NS.STREAM - XMPP Streams namespace from RFC 3920.
* @property {string} NS.BIND - XMPP Binding namespace from RFC 3920 and RFC 6120.
* @property {string} NS.SESSION - XMPP Session namespace from RFC 3920.
* @property {string} NS.XHTML_IM - XHTML-IM namespace from XEP 71.
* @property {string} NS.XHTML - XHTML body namespace from XEP 71.
* @property {string} NS.STANZAS
* @property {string} NS.FRAMING
*/
const NS = {
HTTPBIND: 'http://jabber.org/protocol/httpbind',
BOSH: 'urn:xmpp:xbosh',
CLIENT: 'jabber:client',
AUTH: 'jabber:iq:auth',
ROSTER: 'jabber:iq:roster',
PROFILE: 'jabber:iq:profile',
DISCO_INFO: 'http://jabber.org/protocol/disco#info',
DISCO_ITEMS: 'http://jabber.org/protocol/disco#items',
MUC: 'http://jabber.org/protocol/muc',
SASL: 'urn:ietf:params:xml:ns:xmpp-sasl',
STREAM: 'http://etherx.jabber.org/streams',
FRAMING: 'urn:ietf:params:xml:ns:xmpp-framing',
BIND: 'urn:ietf:params:xml:ns:xmpp-bind',
SESSION: 'urn:ietf:params:xml:ns:xmpp-session',
VERSION: 'jabber:iq:version',
STANZAS: 'urn:ietf:params:xml:ns:xmpp-stanzas',
XHTML_IM: 'http://jabber.org/protocol/xhtml-im',
XHTML: 'http://www.w3.org/1999/xhtml'
};
/**
* Contains allowed tags, tag attributes, and css properties.
* Used in the {@link Strophe.createHtml} function to filter incoming html into the allowed XHTML-IM subset.
* See [XEP-0071](http://xmpp.org/extensions/xep-0071.html#profile-summary) for the list of recommended
* allowed tags and their attributes.
*/
const XHTML = {
tags: ['a', 'blockquote', 'br', 'cite', 'em', 'img', 'li', 'ol', 'p', 'span', 'strong', 'ul', 'body'],
attributes: {
'a': ['href'],
'blockquote': ['style'],
/** @type {never[]} */
'br': [],
'cite': ['style'],
/** @type {never[]} */
'em': [],
'img': ['src', 'alt', 'style', 'height', 'width'],
'li': ['style'],
'ol': ['style'],
'p': ['style'],
'span': ['style'],
/** @type {never[]} */
'strong': [],
'ul': ['style'],
/** @type {never[]} */
'body': []
},
css: ['background-color', 'color', 'font-family', 'font-size', 'font-style', 'font-weight', 'margin-left', 'margin-right', 'text-align', 'text-decoration']
};
/** @typedef {number} connstatus */
/**
* Connection status constants for use by the connection handler
* callback.
*
* @typedef {Object} Status
* @property {connstatus} Status.ERROR - An error has occurred
* @property {connstatus} Status.CONNECTING - The connection is currently being made
* @property {connstatus} Status.CONNFAIL - The connection attempt failed
* @property {connstatus} Status.AUTHENTICATING - The connection is authenticating
* @property {connstatus} Status.AUTHFAIL - The authentication attempt failed
* @property {connstatus} Status.CONNECTED - The connection has succeeded
* @property {connstatus} Status.DISCONNECTED - The connection has been terminated
* @property {connstatus} Status.DISCONNECTING - The connection is currently being terminated
* @property {connstatus} Status.ATTACHED - The connection has been attached
* @property {connstatus} Status.REDIRECT - The connection has been redirected
* @property {connstatus} Status.CONNTIMEOUT - The connection has timed out
* @property {connstatus} Status.BINDREQUIRED - The JID resource needs to be bound for this session
* @property {connstatus} Status.ATTACHFAIL - Failed to attach to a pre-existing session
* @property {connstatus} Status.RECONNECTING - Not used by Strophe, but added for integrators
*/
const Status = {
ERROR: 0,
CONNECTING: 1,
CONNFAIL: 2,
AUTHENTICATING: 3,
AUTHFAIL: 4,
CONNECTED: 5,
DISCONNECTED: 6,
DISCONNECTING: 7,
ATTACHED: 8,
REDIRECT: 9,
CONNTIMEOUT: 10,
BINDREQUIRED: 11,
ATTACHFAIL: 12,
RECONNECTING: 13
};
const ErrorCondition = {
BAD_FORMAT: 'bad-format',
CONFLICT: 'conflict',
MISSING_JID_NODE: 'x-strophe-bad-non-anon-jid',
NO_AUTH_MECH: 'no-auth-mech',
UNKNOWN_REASON: 'unknown'
};
/**
* @typedef {Object} LogLevel
* @property {string} DEBUG
* @property {string} INFO
* @property {string} WARN
* @property {string} ERROR
* @property {string} FATAL
*/
/**
* Logging level indicators.
*
* - Strophe.LogLevel.DEBUG - Debug output
* - Strophe.LogLevel.INFO - Informational output
* - Strophe.LogLevel.WARN - Warnings
* - Strophe.LogLevel.ERROR - Errors
* - Strophe.LogLevel.FATAL - Fatal errors
*/
const LogLevel = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3,
FATAL: 4
};
/**
* DOM element types.
*
* - ElementType.NORMAL - Normal element.
* - ElementType.TEXT - Text data element.
* - ElementType.FRAGMENT - XHTML fragment element.
*/
const ElementType = {
NORMAL: 1,
TEXT: 3,
CDATA: 4,
FRAGMENT: 11
};
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/builder.js
/**
* Create a {@link Strophe.Builder}
* This is an alias for `new Strophe.Builder(name, attrs)`.
* @param {string} name - The root element name.
* @param {Object.<string,string|number>} [attrs] - The attributes for the root element in object notation.
* @return {Builder} A new Strophe.Builder object.
*/
function $build(name, attrs) {
return new Builder(name, attrs);
}
/**
* Create a {@link Strophe.Builder} with a `<message/>` element as the root.
* @param {Object.<string,string>} [attrs] - The <message/> element attributes in object notation.
* @return {Builder} A new Strophe.Builder object.
*/
function $msg(attrs) {
return new Builder('message', attrs);
}
/**
* Create a {@link Strophe.Builder} with an `<iq/>` element as the root.
* @param {Object.<string,string>} [attrs] - The <iq/> element attributes in object notation.
* @return {Builder} A new Strophe.Builder object.
*/
function $iq(attrs) {
return new Builder('iq', attrs);
}
/**
* Create a {@link Strophe.Builder} with a `<presence/>` element as the root.
* @param {Object.<string,string>} [attrs] - The <presence/> element attributes in object notation.
* @return {Builder} A new Strophe.Builder object.
*/
function $pres(attrs) {
return new Builder('presence', attrs);
}
/**
* This class provides an interface similar to JQuery but for building
* DOM elements easily and rapidly. All the functions except for `toString()`
* and tree() return the object, so calls can be chained.
*
* The corresponding DOM manipulations to get a similar fragment would be
* a lot more tedious and probably involve several helper variables.
*
* Since adding children makes new operations operate on the child, up()
* is provided to traverse up the tree. To add two children, do
* > builder.c('child1', ...).up().c('child2', ...)
*
* The next operation on the Builder will be relative to the second child.
*
* @example
* // Here's an example using the $iq() builder helper.
* $iq({to: 'you', from: 'me', type: 'get', id: '1'})
* .c('query', {xmlns: 'strophe:example'})
* .c('example')
* .toString()
*
* // The above generates this XML fragment
* // <iq to='you' from='me' type='get' id='1'>
* // <query xmlns='strophe:example'>
* // <example/>
* // </query>
* // </iq>
*/
class Builder {
/**
* @typedef {Object.<string, string|number>} StanzaAttrs
* @property {string} [StanzaAttrs.xmlns]
*/
/**
* The attributes should be passed in object notation.
* @param {string} name - The name of the root element.
* @param {StanzaAttrs} [attrs] - The attributes for the root element in object notation.
* @example const b = new Builder('message', {to: 'you', from: 'me'});
* @example const b = new Builder('messsage', {'xml:lang': 'en'});
*/
constructor(name, attrs) {
// Set correct namespace for jabber:client elements
if (name === 'presence' || name === 'message' || name === 'iq') {
if (attrs && !attrs.xmlns) {
attrs.xmlns = NS.CLIENT;
} else if (!attrs) {
attrs = {
xmlns: NS.CLIENT
};
}
}
// Holds the tree being built.
this.nodeTree = xmlElement(name, attrs);
// Points to the current operation node.
this.node = this.nodeTree;
}
/**
* Return the DOM tree.
*
* This function returns the current DOM tree as an element object. This
* is suitable for passing to functions like Strophe.Connection.send().
*
* @return {Element} The DOM tree as a element object.
*/
tree() {
return this.nodeTree;
}
/**
* Serialize the DOM tree to a String.
*
* This function returns a string serialization of the current DOM
* tree. It is often used internally to pass data to a
* Strophe.Request object.
*
* @return {string} The serialized DOM tree in a String.
*/
toString() {
return serialize(this.nodeTree);
}
/**
* Make the current parent element the new current element.
* This function is often used after c() to traverse back up the tree.
*
* @example
* // For example, to add two children to the same element
* builder.c('child1', {}).up().c('child2', {});
*
* @return {Builder} The Strophe.Builder object.
*/
up() {
this.node = this.node.parentElement;
return this;
}
/**
* Make the root element the new current element.
*
* When at a deeply nested element in the tree, this function can be used
* to jump back to the root of the tree, instead of having to repeatedly
* call up().
*
* @return {Builder} The Strophe.Builder object.
*/
root() {
this.node = this.nodeTree;
return this;
}
/**
* Add or modify attributes of the current element.
*
* The attributes should be passed in object notation.
* This function does not move the current element pointer.
* @param {Object.<string, string|number|null>} moreattrs - The attributes to add/modify in object notation.
* If an attribute is set to `null` or `undefined`, it will be removed.
* @return {Builder} The Strophe.Builder object.
*/
attrs(moreattrs) {
for (const k in moreattrs) {
if (Object.prototype.hasOwnProperty.call(moreattrs, k)) {
// eslint-disable-next-line no-eq-null
if (moreattrs[k] != null) {
this.node.setAttribute(k, moreattrs[k].toString());
} else {
this.node.removeAttribute(k);
}
}
}
return this;
}
/**
* Add a child to the current element and make it the new current
* element.
*
* This function moves the current element pointer to the child,
* unless text is provided. If you need to add another child, it
* is necessary to use up() to go back to the parent in the tree.
*
* @param {string} name - The name of the child.
* @param {Object.<string, string>|string} [attrs] - The attributes of the child in object notation.
* @param {string} [text] - The text to add to the child.
*
* @return {Builder} The Strophe.Builder object.
*/
c(name, attrs, text) {
const child = xmlElement(name, attrs, text);
this.node.appendChild(child);
if (typeof text !== 'string' && typeof text !== 'number') {
this.node = child;
}
return this;
}
/**
* Add a child to the current element and make it the new current
* element.
*
* This function is the same as c() except that instead of using a
* name and an attributes object to create the child it uses an
* existing DOM element object.
*
* @param {Element} elem - A DOM element.
* @return {Builder} The Strophe.Builder object.
*/
cnode(elem) {
let impNode;
const xmlGen = xmlGenerator();
try {
impNode = xmlGen.importNode !== undefined;
} catch (e) {
impNode = false;
}
const newElem = impNode ? xmlGen.importNode(elem, true) : copyElement(elem);
this.node.appendChild(newElem);
this.node = /** @type {Element} */newElem;
return this;
}
/**
* Add a child text element.
*
* This *does not* make the child the new current element since there
* are no children of text elements.
*
* @param {string} text - The text data to append to the current element.
* @return {Builder} The Strophe.Builder object.
*/
t(text) {
const child = xmlTextNode(text);
this.node.appendChild(child);
return this;
}
/**
* Replace current element contents with the HTML passed in.
*
* This *does not* make the child the new current element
*
* @param {string} html - The html to insert as contents of current element.
* @return {Builder} The Strophe.Builder object.
*/
h(html) {
const fragment = xmlGenerator().createElement('body');
// force the browser to try and fix any invalid HTML tags
fragment.innerHTML = html;
// copy cleaned html into an xml dom
const xhtml = createHtml(fragment);
while (xhtml.childNodes.length > 0) {
this.node.appendChild(xhtml.childNodes[0]);
}
return this;
}
}
/* harmony default export */ const builder = (Builder);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/utils.js
/* global btoa */
/**
* @param {string} str
* @return {string}
*/
function utf16to8(str) {
let out = '';
const len = str.length;
for (let i = 0; i < len; i++) {
const c = str.charCodeAt(i);
if (c >= 0x0000 && c <= 0x007f) {
out += str.charAt(i);
} else if (c > 0x07ff) {
out += String.fromCharCode(0xe0 | c >> 12 & 0x0f);
out += String.fromCharCode(0x80 | c >> 6 & 0x3f);
out += String.fromCharCode(0x80 | c >> 0 & 0x3f);
} else {
out += String.fromCharCode(0xc0 | c >> 6 & 0x1f);
out += String.fromCharCode(0x80 | c >> 0 & 0x3f);
}
}
return out;
}
/**
* @param {ArrayBufferLike} x
* @param {ArrayBufferLike} y
*/
function xorArrayBuffers(x, y) {
const xIntArray = new Uint8Array(x);
const yIntArray = new Uint8Array(y);
const zIntArray = new Uint8Array(x.byteLength);
for (let i = 0; i < x.byteLength; i++) {
zIntArray[i] = xIntArray[i] ^ yIntArray[i];
}
return zIntArray.buffer;
}
/**
* @param {ArrayBufferLike} buffer
* @return {string}
*/
function arrayBufToBase64(buffer) {
// This function is due to mobz (https://stackoverflow.com/users/1234628/mobz)
// and Emmanuel (https://stackoverflow.com/users/288564/emmanuel)
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
/**
* @param {string} str
* @return {ArrayBufferLike}
*/
function base64ToArrayBuf(str) {
return Uint8Array.from(atob(str), c => c.charCodeAt(0))?.buffer;
}
/**
* @param {string} str
* @return {ArrayBufferLike}
*/
function stringToArrayBuf(str) {
const bytes = new TextEncoder().encode(str);
return bytes.buffer;
}
/**
* @param {Cookies} cookies
*/
function addCookies(cookies) {
if (typeof document === 'undefined') {
core.log(core.LogLevel.ERROR, `addCookies: not adding any cookies, since there's no document object`);
}
/**
* @typedef {Object.<string, string>} Cookie
*
* A map of cookie names to string values or to maps of cookie values.
* @typedef {Cookie|Object.<string, Cookie>} Cookies
*
* For example:
* { "myCookie": "1234" }
*
* or:
* { "myCookie": {
* "value": "1234",
* "domain": ".example.org",
* "path": "/",
* "expires": expirationDate
* }
* }
*
* These values get passed to {@link Strophe.Connection} via options.cookies
*/
cookies = cookies || {};
for (const cookieName in cookies) {
if (Object.prototype.hasOwnProperty.call(cookies, cookieName)) {
let expires = '';
let domain = '';
let path = '';
const cookieObj = cookies[cookieName];
const isObj = typeof cookieObj === 'object';
const cookieValue = escape(unescape(isObj ? cookieObj.value : cookieObj));
if (isObj) {
expires = cookieObj.expires ? ';expires=' + cookieObj.expires : '';
domain = cookieObj.domain ? ';domain=' + cookieObj.domain : '';
path = cookieObj.path ? ';path=' + cookieObj.path : '';
}
document.cookie = cookieName + '=' + cookieValue + expires + domain + path;
}
}
}
/** @type {Document} */
let _xmlGenerator = null;
/**
* Get the DOM document to generate elements.
* @return {Document} - The currently used DOM document.
*/
function xmlGenerator() {
if (!_xmlGenerator) {
_xmlGenerator = getDummyXMLDOMDocument();
}
return _xmlGenerator;
}
/**
* Creates an XML DOM text node.
* Provides a cross implementation version of document.createTextNode.
* @param {string} text - The content of the text node.
* @return {Text} - A new XML DOM text node.
*/
function xmlTextNode(text) {
return xmlGenerator().createTextNode(text);
}
/**
* Creates an XML DOM node.
* @param {string} html - The content of the html node.
* @return {XMLDocument}
*/
function xmlHtmlNode(html) {
const parser = new DOMParser();
return parser.parseFromString(html, 'text/xml');
}
/**
* Create an XML DOM element.
*
* This function creates an XML DOM element correctly across all
* implementations. Note that these are not HTML DOM elements, which
* aren't appropriate for XMPP stanzas.
*
* @param {string} name - The name for the element.
* @param {Array<Array<string>>|Object.<string,string|number>|string|number} [attrs]
* An optional array or object containing
* key/value pairs to use as element attributes.
* The object should be in the format `{'key': 'value'}`.
* The array should have the format `[['key1', 'value1'], ['key2', 'value2']]`.
* @param {string|number} [text] - The text child data for the element.
*
* @return {Element} A new XML DOM element.
*/
function xmlElement(name, attrs, text) {
if (!name) return null;
const node = xmlGenerator().createElement(name);
if (text && (typeof text === 'string' || typeof text === 'number')) {
node.appendChild(xmlTextNode(text.toString()));
} else if (typeof attrs === 'string' || typeof attrs === 'number') {
node.appendChild(xmlTextNode( /** @type {number|string} */attrs.toString()));
return node;
} else if (!attrs) {
return node;
}
if (Array.isArray(attrs)) {
for (const attr of attrs) {
if (Array.isArray(attr)) {
// eslint-disable-next-line no-eq-null
if (attr[0] != null && attr[1] != null) {
node.setAttribute(attr[0], attr[1]);
}
}
}
} else if (typeof attrs === 'object') {
for (const k of Object.keys(attrs)) {
// eslint-disable-next-line no-eq-null
if (k && attrs[k] != null) {
node.setAttribute(k, attrs[k].toString());
}
}
}
return node;
}
/**
* Utility method to determine whether a tag is allowed
* in the XHTML_IM namespace.
*
* XHTML tag names are case sensitive and must be lower case.
* @method Strophe.XHTML.validTag
* @param {string} tag
*/
function validTag(tag) {
for (let i = 0; i < XHTML.tags.length; i++) {
if (tag === XHTML.tags[i]) {
return true;
}
}
return false;
}
/**
* @typedef {'a'|'blockquote'|'br'|'cite'|'em'|'img'|'li'|'ol'|'p'|'span'|'strong'|'ul'|'body'} XHTMLAttrs
*/
/**
* Utility method to determine whether an attribute is allowed
* as recommended per XEP-0071
*
* XHTML attribute names are case sensitive and must be lower case.
* @method Strophe.XHTML.validAttribute
* @param {string} tag
* @param {string} attribute
*/
function validAttribute(tag, attribute) {
const attrs = XHTML.attributes[/** @type {XHTMLAttrs} */tag];
if (attrs?.length > 0) {
for (let i = 0; i < attrs.length; i++) {
if (attribute === attrs[i]) {
return true;
}
}
}
return false;
}
/**
* @method Strophe.XHTML.validCSS
* @param {string} style
*/
function validCSS(style) {
for (let i = 0; i < XHTML.css.length; i++) {
if (style === XHTML.css[i]) {
return true;
}
}
return false;
}
/**
* Copy an HTML DOM Element into an XML DOM.
* This function copies a DOM element and all its descendants and returns
* the new copy.
* @method Strophe.createHtml
* @param {HTMLElement} elem - A DOM element.
* @return {Node} - A new, copied DOM element tree.
*/
function createFromHtmlElement(elem) {
let el;
const tag = elem.nodeName.toLowerCase(); // XHTML tags must be lower case.
if (validTag(tag)) {
try {
el = xmlElement(tag);
if (tag in XHTML.attributes) {
const attrs = XHTML.attributes[/** @type {XHTMLAttrs} */tag];
for (let i = 0; i < attrs.length; i++) {
const attribute = attrs[i];
let value = elem.getAttribute(attribute);
if (typeof value === 'undefined' || value === null || value === '') {
continue;
}
if (attribute === 'style' && typeof value === 'object') {
value = /** @type {Object.<'csstext',string>} */value.cssText ?? value; // we're dealing with IE, need to get CSS out
}
// filter out invalid css styles
if (attribute === 'style') {
const css = [];
const cssAttrs = value.split(';');
for (let j = 0; j < cssAttrs.length; j++) {
const attr = cssAttrs[j].split(':');
const cssName = attr[0].replace(/^\s*/, '').replace(/\s*$/, '').toLowerCase();
if (validCSS(cssName)) {
const cssValue = attr[1].replace(/^\s*/, '').replace(/\s*$/, '');
css.push(cssName + ': ' + cssValue);
}
}
if (css.length > 0) {
value = css.join('; ');
el.setAttribute(attribute, value);
}
} else {
el.setAttribute(attribute, value);
}
}
for (let i = 0; i < elem.childNodes.length; i++) {
el.appendChild(createHtml(elem.childNodes[i]));
}
}
} catch (e) {
// invalid elements
el = xmlTextNode('');
}
} else {
el = xmlGenerator().createDocumentFragment();
for (let i = 0; i < elem.childNodes.length; i++) {
el.appendChild(createHtml(elem.childNodes[i]));
}
}
return el;
}
/**
* Copy an HTML DOM Node into an XML DOM.
* This function copies a DOM element and all its descendants and returns
* the new copy.
* @method Strophe.createHtml
* @param {Node} node - A DOM element.
* @return {Node} - A new, copied DOM element tree.
*/
function createHtml(node) {
if (node.nodeType === ElementType.NORMAL) {
return createFromHtmlElement( /** @type {HTMLElement} */node);
} else if (node.nodeType === ElementType.FRAGMENT) {
const el = xmlGenerator().createDocumentFragment();
for (let i = 0; i < node.childNodes.length; i++) {
el.appendChild(createHtml(node.childNodes[i]));
}
return el;
} else if (node.nodeType === ElementType.TEXT) {
return xmlTextNode(node.nodeValue);
}
}
/**
* Copy an XML DOM element.
*
* This function copies a DOM element and all its descendants and returns
* the new copy.
* @method Strophe.copyElement
* @param {Node} node - A DOM element.
* @return {Element|Text} - A new, copied DOM element tree.
*/
function copyElement(node) {
let out;
if (node.nodeType === ElementType.NORMAL) {
const el = /** @type {Element} */node;
out = xmlElement(el.tagName);
for (let i = 0; i < el.attributes.length; i++) {
out.setAttribute(el.attributes[i].nodeName, el.attributes[i].value);
}
for (let i = 0; i < el.childNodes.length; i++) {
out.appendChild(copyElement(el.childNodes[i]));
}
} else if (node.nodeType === ElementType.TEXT) {
out = xmlGenerator().createTextNode(node.nodeValue);
}
return out;
}
/**
* Excapes invalid xml characters.
* @method Strophe.xmlescape
* @param {string} text - text to escape.
* @return {string} - Escaped text.
*/
function xmlescape(text) {
text = text.replace(/\&/g, '&');
text = text.replace(/</g, '<');
text = text.replace(/>/g, '>');
text = text.replace(/'/g, ''');
text = text.replace(/"/g, '"');
return text;
}
/**
* Unexcapes invalid xml characters.
* @method Strophe.xmlunescape
* @param {string} text - text to unescape.
* @return {string} - Unescaped text.
*/
function xmlunescape(text) {
text = text.replace(/\&/g, '&');
text = text.replace(/</g, '<');
text = text.replace(/>/g, '>');
text = text.replace(/'/g, "'");
text = text.replace(/"/g, '"');
return text;
}
/**
* Render a DOM element and all descendants to a String.
* @method Strophe.serialize
* @param {Element|Builder} elem - A DOM element.
* @return {string} - The serialized element tree as a String.
*/
function serialize(elem) {
if (!elem) return null;
const el = elem instanceof builder ? elem.tree() : elem;
const names = [...Array(el.attributes.length).keys()].map(i => el.attributes[i].nodeName);
names.sort();
let result = names.reduce((a, n) => `${a} ${n}="${xmlescape(el.attributes.getNamedItem(n).value)}"`, `<${el.nodeName}`);
if (el.childNodes.length > 0) {
result += '>';
for (let i = 0; i < el.childNodes.length; i++) {
const child = el.childNodes[i];
switch (child.nodeType) {
case ElementType.NORMAL:
// normal element, so recurse
result += serialize( /** @type {Element} */child);
break;
case ElementType.TEXT:
// text element to escape values
result += xmlescape(child.nodeValue);
break;
case ElementType.CDATA:
// cdata section so don't escape values
result += '<![CDATA[' + child.nodeValue + ']]>';
}
}
result += '</' + el.nodeName + '>';
} else {
result += '/>';
}
return result;
}
/**
* Map a function over some or all child elements of a given element.
*
* This is a small convenience function for mapping a function over
* some or all of the children of an element. If elemName is null, all
* children will be passed to the function, otherwise only children
* whose tag names match elemName will be passed.
*
* @method Strophe.forEachChild
* @param {Element} elem - The element to operate on.
* @param {string} elemName - The child element tag name filter.
* @param {Function} func - The function to apply to each child. This
* function should take a single argument, a DOM element.
*/
function forEachChild(elem, elemName, func) {
for (let i = 0; i < elem.childNodes.length; i++) {
const childNode = elem.childNodes[i];
if (childNode.nodeType === ElementType.NORMAL && (!elemName || this.isTagEqual(childNode, elemName))) {
func(childNode);
}
}
}
/**
* Compare an element's tag name with a string.
* This function is case sensitive.
* @method Strophe.isTagEqual
* @param {Element} el - A DOM element.
* @param {string} name - The element name.
* @return {boolean}
* true if the element's tag name matches _el_, and false
* otherwise.
*/
function isTagEqual(el, name) {
return el.tagName === name;
}
/**
* Get the concatenation of all text children of an element.
* @method Strophe.getText
* @param {Element} elem - A DOM element.
* @return {string} - A String with the concatenated text of all text element children.
*/
function getText(elem) {
if (!elem) {
return null;
}
let str = '';
if (!elem.childNodes?.length && elem.nodeType === ElementType.TEXT) {
str += elem.nodeValue;
}
for (let i = 0; i < elem.childNodes?.length ?? 0; i++) {
if (elem.childNodes[i].nodeType === ElementType.TEXT) {
str += elem.childNodes[i].nodeValue;
}
}
return xmlescape(str);
}
/**
* Escape the node part (also called local part) of a JID.
* @method Strophe.escapeNode
* @param {string} node - A node (or local part).
* @return {string} An escaped node (or local part).
*/
function escapeNode(node) {
if (typeof node !== 'string') {
return node;
}
return node.replace(/^\s+|\s+$/g, '').replace(/\\/g, '\\5c').replace(/ /g, '\\20').replace(/\"/g, '\\22').replace(/\&/g, '\\26').replace(/\'/g, '\\27').replace(/\//g, '\\2f').replace(/:/g, '\\3a').replace(/</g, '\\3c').replace(/>/g, '\\3e').replace(/@/g, '\\40');
}
/**
* Unescape a node part (also called local part) of a JID.
* @method Strophe.unescapeNode
* @param {string} node - A node (or local part).
* @return {string} An unescaped node (or local part).
*/
function unescapeNode(node) {
if (typeof node !== 'string') {
return node;
}
return node.replace(/\\20/g, ' ').replace(/\\22/g, '"').replace(/\\26/g, '&').replace(/\\27/g, "'").replace(/\\2f/g, '/').replace(/\\3a/g, ':').replace(/\\3c/g, '<').replace(/\\3e/g, '>').replace(/\\40/g, '@').replace(/\\5c/g, '\\');
}
/**
* Get the node portion of a JID String.
* @method Strophe.getNodeFromJid
* @param {string} jid - A JID.
* @return {string} - A String containing the node.
*/
function getNodeFromJid(jid) {
if (jid.indexOf('@') < 0) {
return null;
}
return jid.split('@')[0];
}
/**
* Get the domain portion of a JID String.
* @method Strophe.getDomainFromJid
* @param {string} jid - A JID.
* @return {string} - A String containing the domain.
*/
function getDomainFromJid(jid) {
const bare = getBareJidFromJid(jid);
if (bare.indexOf('@') < 0) {
return bare;
} else {
const parts = bare.split('@');
parts.splice(0, 1);
return parts.join('@');
}
}
/**
* Get the resource portion of a JID String.
* @method Strophe.getResourceFromJid
* @param {string} jid - A JID.
* @return {string} - A String containing the resource.
*/
function getResourceFromJid(jid) {
if (!jid) {
return null;
}
const s = jid.split('/');
if (s.length < 2) {
return null;
}
s.splice(0, 1);
return s.join('/');
}
/**
* Get the bare JID from a JID String.
* @method Strophe.getBareJidFromJid
* @param {string} jid - A JID.
* @return {string} - A String containing the bare JID.
*/
function getBareJidFromJid(jid) {
return jid ? jid.split('/')[0] : null;
}
const utils = {
utf16to8,
xorArrayBuffers,
arrayBufToBase64,
base64ToArrayBuf,
stringToArrayBuf,
addCookies
};
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/handler.js
/**
* _Private_ helper class for managing stanza handlers.
*
* A Strophe.Handler encapsulates a user provided callback function to be
* executed when matching stanzas are received by the connection.
* Handlers can be either one-off or persistant depending on their
* return value. Returning true will cause a Handler to remain active, and
* returning false will remove the Handler.
*
* Users will not use Strophe.Handler objects directly, but instead they
* will use {@link Strophe.Connection.addHandler} and
* {@link Strophe.Connection.deleteHandler}.
*/
class Handler {
/**
* @typedef {Object} HandlerOptions
* @property {boolean} [HandlerOptions.matchBareFromJid]
* @property {boolean} [HandlerOptions.ignoreNamespaceFragment]
*/
/**
* Create and initialize a new Strophe.Handler.
*
* @param {Function} handler - A function to be executed when the handler is run.
* @param {string} ns - The namespace to match.
* @param {string} name - The element name to match.
* @param {string|string[]} type - The stanza type (or types if an array) to match.
* @param {string} [id] - The element id attribute to match.
* @param {string} [from] - The element from attribute to match.
* @param {HandlerOptions} [options] - Handler options
*/
constructor(handler, ns, name, type, id, from, options) {
this.handler = handler;
this.ns = ns;
this.name = name;
this.type = type;
this.id = id;
this.options = options || {
'matchBareFromJid': false,
'ignoreNamespaceFragment': false
};
if (this.options.matchBareFromJid) {
this.from = from ? getBareJidFromJid(from) : null;
} else {
this.from = from;
}
// whether the handler is a user handler or a system handler
this.user = true;
}
/**
* Returns the XML namespace attribute on an element.
* If `ignoreNamespaceFragment` was passed in for this handler, then the
* URL fragment will be stripped.
* @param {Element} elem - The XML element with the namespace.
* @return {string} - The namespace, with optionally the fragment stripped.
*/
getNamespace(elem) {
let elNamespace = elem.getAttribute('xmlns');
if (elNamespace && this.options.ignoreNamespaceFragment) {
elNamespace = elNamespace.split('#')[0];
}
return elNamespace;
}
/**
* Tests if a stanza matches the namespace set for this Strophe.Handler.
* @param {Element} elem - The XML element to test.
* @return {boolean} - true if the stanza matches and false otherwise.
*/
namespaceMatch(elem) {
let nsMatch = false;
if (!this.ns) {
return true;
} else {
forEachChild(elem, null, /** @param {Element} elem */
elem => {
if (this.getNamespace(elem) === this.ns) {
nsMatch = true;
}
});
return nsMatch || this.getNamespace(elem) === this.ns;
}
}
/**
* Tests if a stanza matches the Strophe.Handler.
* @param {Element} elem - The XML element to test.
* @return {boolean} - true if the stanza matches and false otherwise.
*/
isMatch(elem) {
let from = elem.getAttribute('from');
if (this.options.matchBareFromJid) {
from = getBareJidFromJid(from);
}
const elem_type = elem.getAttribute('type');
if (this.namespaceMatch(elem) && (!this.name || core.isTagEqual(elem, this.name)) && (!this.type || (Array.isArray(this.type) ? this.type.indexOf(elem_type) !== -1 : elem_type === this.type)) && (!this.id || elem.getAttribute('id') === this.id) && (!this.from || from === this.from)) {
return true;
}
return false;
}
/**
* Run the callback on a matching stanza.
* @param {Element} elem - The DOM element that triggered the Strophe.Handler.
* @return {boolean} - A boolean indicating if the handler should remain active.
*/
run(elem) {
let result = null;
try {
result = this.handler(elem);
} catch (e) {
core._handleError(e);
throw e;
}
return result;
}
/**
* Get a String representation of the Strophe.Handler object.
* @return {string}
*/
toString() {
return '{Handler: ' + this.handler + '(' + this.name + ',' + this.id + ',' + this.ns + ')}';
}
}
/* harmony default export */ const src_handler = (Handler);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/timed-handler.js
/**
* _Private_ helper class for managing timed handlers.
*
* A Strophe.TimedHandler encapsulates a user provided callback that
* should be called after a certain period of time or at regular
* intervals. The return value of the callback determines whether the
* Strophe.TimedHandler will continue to fire.
*
* Users will not use Strophe.TimedHandler objects directly, but instead
* they will use {@link Strophe.Connection#addTimedHandler|addTimedHandler()} and
* {@link Strophe.Connection#deleteTimedHandler|deleteTimedHandler()}.
*
* @memberof Strophe
*/
class TimedHandler {
/**
* Create and initialize a new Strophe.TimedHandler object.
* @param {number} period - The number of milliseconds to wait before the
* handler is called.
* @param {Function} handler - The callback to run when the handler fires. This
* function should take no arguments.
*/
constructor(period, handler) {
this.period = period;
this.handler = handler;
this.lastCalled = new Date().getTime();
this.user = true;
}
/**
* Run the callback for the Strophe.TimedHandler.
*
* @return {boolean} Returns the result of running the handler,
* which is `true` if the Strophe.TimedHandler should be called again,
* and `false` otherwise.
*/
run() {
this.lastCalled = new Date().getTime();
return this.handler();
}
/**
* Reset the last called time for the Strophe.TimedHandler.
*/
reset() {
this.lastCalled = new Date().getTime();
}
/**
* Get a string representation of the Strophe.TimedHandler object.
* @return {string}
*/
toString() {
return '{TimedHandler: ' + this.handler + '(' + this.period + ')}';
}
}
/* harmony default export */ const timed_handler = (TimedHandler);
// EXTERNAL MODULE: ./node_modules/abab/index.js
var abab = __webpack_require__(494);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/errors.js
class SessionError extends Error {
/**
* @param {string} message
*/
constructor(message) {
super(message);
this.name = 'StropheSessionError';
}
}
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/connection.js
/**
* @typedef {import("./sasl.js").default} SASLMechanism
* @typedef {import("./request.js").default} Request
*/
/**
* **XMPP Connection manager**
*
* This class is the main part of Strophe. It manages a BOSH or websocket
* connection to an XMPP server and dispatches events to the user callbacks
* as data arrives.
*
* It supports various authentication mechanisms (e.g. SASL PLAIN, SASL SCRAM),
* and more can be added via
* {@link Strophe.Connection#registerSASLMechanisms|registerSASLMechanisms()}.
*
* After creating a Strophe.Connection object, the user will typically
* call {@link Strophe.Connection#connect|connect()} with a user supplied callback
* to handle connection level events like authentication failure,
* disconnection, or connection complete.
*
* The user will also have several event handlers defined by using
* {@link Strophe.Connection#addHandler|addHandler()} and
* {@link Strophe.Connection#addTimedHandler|addTimedHandler()}.
* These will allow the user code to respond to interesting stanzas or do
* something periodically with the connection. These handlers will be active
* once authentication is finished.
*
* To send data to the connection, use {@link Strophe.Connection#send|send()}.
*
* @memberof Strophe
*/
class Connection {
/**
* @typedef {Object.<string, string>} Cookie
* @typedef {Cookie|Object.<string, Cookie>} Cookies
*/
/**
* @typedef {Object} ConnectionOptions
* @property {Cookies} [cookies]
* Allows you to pass in cookies that will be included in HTTP requests.
* Relevant to both the BOSH and Websocket transports.
*
* The passed in value must be a map of cookie names and string values.
*
* > { "myCookie": {
* > "value": "1234",
* > "domain": ".example.org",
* > "path": "/",
* > "expires": expirationDate
* > }
* > }
*
* Note that cookies can't be set in this way for domains other than the one
* that's hosting Strophe (i.e. cross-domain).
* Those cookies need to be set under those domains, for example they can be
* set server-side by making a XHR call to that domain to ask it to set any
* necessary cookies.
* @property {SASLMechanism[]} [mechanisms]
* Allows you to specify the SASL authentication mechanisms that this
* instance of Strophe.Connection (and therefore your XMPP client) will support.
*
* The value must be an array of objects with {@link Strophe.SASLMechanism}
* prototypes.
*
* If nothing is specified, then the following mechanisms (and their
* priorities) are registered:
*
* Mechanism Priority
* ------------------------
* SCRAM-SHA-512 72
* SCRAM-SHA-384 71
* SCRAM-SHA-256 70
* SCRAM-SHA-1 60
* PLAIN 50
* OAUTHBEARER 40
* X-OAUTH2 30
* ANONYMOUS 20
* EXTERNAL 10
*
* @property {boolean} [explicitResourceBinding]
* If `explicitResourceBinding` is set to `true`, then the XMPP client
* needs to explicitly call {@link Strophe.Connection.bind} once the XMPP
* server has advertised the `urn:ietf:propertys:xml:ns:xmpp-bind` feature.
*
* Making this step explicit allows client authors to first finish other
* stream related tasks, such as setting up an XEP-0198 Stream Management
* session, before binding the JID resource for this session.
*
* @property {'ws'|'wss'} [protocol]
* _Note: This option is only relevant to Websocket connections, and not BOSH_
*
* If you want to connect to the current host with a WebSocket connection you
* can tell Strophe to use WebSockets through the "protocol" option.
* Valid values are `ws` for WebSocket and `wss` for Secure WebSocket.
* So to connect to "wss://CURRENT_HOSTNAME/xmpp-websocket" you would call
*
* const conn = new Strophe.Connection(
* "/xmpp-websocket/",
* {protocol: "wss"}
* );
*
* Note that relative URLs _NOT_ starting with a "/" will also include the path
* of the current site.
*
* Also because downgrading security is not permitted by browsers, when using
* relative URLs both BOSH and WebSocket connections will use their secure
* variants if the current connection to the site is also secure (https).
*
* @property {string} [worker]
* _Note: This option is only relevant to Websocket connections, and not BOSH_
*
* Set this option to URL from where the shared worker script should be loaded.
*
* To run the websocket connection inside a shared worker.
* This allows you to share a single websocket-based connection between
* multiple Strophe.Connection instances, for example one per browser tab.
*
* The script to use is the one in `src/shared-connection-worker.js`.
*
* @property {boolean} [sync]
* Used to control whether BOSH HTTP requests will be made synchronously or not.
* The default behaviour is asynchronous. If you want to make requests
* synchronous, make "sync" evaluate to true.
*
* > const conn = new Strophe.Connection("/http-bind/", {sync: true});
*
* You can also toggle this on an already established connection.
*
* > conn.options.sync = true;
*
* @property {string[]} [customHeaders]
* Used to provide custom HTTP headers to be included in the BOSH HTTP requests.
*
* @property {boolean} [keepalive]
* Used to instruct Strophe to maintain the current BOSH session across
* interruptions such as webpage reloads.
*
* It will do this by caching the sessions tokens in sessionStorage, and when
* "restore" is called it will check whether there are cached tokens with
* which it can resume an existing session.
*
* @property {boolean} [withCredentials]
* Used to indicate wether cookies should be included in HTTP requests (by default
* they're not).
* Set this value to `true` if you are connecting to a BOSH service
* and for some reason need to send cookies to it.
* In order for this to work cross-domain, the server must also enable
* credentials by setting the `Access-Control-Allow-Credentials` response header
* to "true". For most usecases however this setting should be false (which
* is the default).
* Additionally, when using `Access-Control-Allow-Credentials`, the
* `Access-Control-Allow-Origin` header can't be set to the wildcard "*", but
* instead must be restricted to actual domains.
*
* @property {string} [contentType]
* Used to change the default Content-Type, which is "text/xml; charset=utf-8".
* Can be useful to reduce the amount of CORS preflight requests that are sent
* to the server.
*/
/**
* Create and initialize a {@link Strophe.Connection} object.
*
* The transport-protocol for this connection will be chosen automatically
* based on the given service parameter. URLs starting with "ws://" or
* "wss://" will use WebSockets, URLs starting with "http://", "https://"
* or without a protocol will use [BOSH](https://xmpp.org/extensions/xep-0124.html).
*
* To make Strophe connect to the current host you can leave out the protocol
* and host part and just pass the path:
*
* const conn = new Strophe.Connection("/http-bind/");
*
* @param {string} service - The BOSH or WebSocket service URL.
* @param {ConnectionOptions} options - A object containing configuration options
*/
constructor(service) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// The service URL
this.service = service;
// Configuration options
this.options = options;
this.setProtocol();
/* The connected JID. */
this.jid = '';
/* the JIDs domain */
this.domain = null;
/* stream:features */
this.features = null;
// SASL
/**
* @typedef {Object.<string, any>} SASLData
* @property {Object} [SASLData.keys]
*/
/** @type {SASLData} */
this._sasl_data = {};
this.do_bind = false;
this.do_session = false;
/** @type {Object.<string, SASLMechanism>} */
this.mechanisms = {};
/** @type {TimedHandler[]} */
this.timedHandlers = [];
/** @type {Handler[]} */
this.handlers = [];
/** @type {TimedHandler[]} */
this.removeTimeds = [];
/** @type {Handler[]} */
this.removeHandlers = [];
/** @type {TimedHandler[]} */
this.addTimeds = [];
/** @type {Handler[]} */
this.addHandlers = [];
this.protocolErrorHandlers = {
/** @type {Object.<number, Function>} */
'HTTP': {},
/** @type {Object.<number, Function>} */
'websocket': {}
};
this._idleTimeout = null;
this._disconnectTimeout = null;
this.authenticated = false;
this.connected = false;
this.disconnecting = false;
this.do_authentication = true;
this.paused = false;
this.restored = false;
/** @type {(Element|'restart')[]} */
this._data = [];
this._uniqueId = 0;
this._sasl_success_handler = null;
this._sasl_failure_handler = null;
this._sasl_challenge_handler = null;
// Max retries before disconnecting
this.maxRetries = 5;
// Call onIdle callback every 1/10th of a second
this._idleTimeout = setTimeout(() => this._onIdle(), 100);
addCookies(this.options.cookies);
this.registerSASLMechanisms(this.options.mechanisms);
// A client must always respond to incoming IQ "set" and "get" stanzas.
// See https://datatracker.ietf.org/doc/html/rfc6120#section-8.2.3
//
// This is a fallback handler which gets called when no other handler
// was called for a received IQ "set" or "get".
this.iqFallbackHandler = new src_handler(
/**
* @param {Element} iq
*/
iq => this.send($iq({
type: 'error',
id: iq.getAttribute('id')
}).c('error', {
'type': 'cancel'
}).c('service-unavailable', {
'xmlns': core.NS.STANZAS
})), null, 'iq', ['get', 'set']);
// initialize plugins
for (const k in core._connectionPlugins) {
if (Object.prototype.hasOwnProperty.call(core._connectionPlugins, k)) {
const F = function () {};
F.prototype = core._connectionPlugins[k];
// @ts-ignore
this[k] = new F();
// @ts-ignore
this[k].init(this);
}
}
}
/**
* Select protocal based on this.options or this.service
*/
setProtocol() {
const proto = this.options.protocol || '';
if (this.options.worker) {
this._proto = new core.WorkerWebsocket(this);
} else if (this.service.indexOf('ws:') === 0 || this.service.indexOf('wss:') === 0 || proto.indexOf('ws') === 0) {
this._proto = new core.Websocket(this);
} else {
this._proto = new core.Bosh(this);
}
}
/**
* Reset the connection.
*
* This function should be called after a connection is disconnected
* before that connection is reused.
*/
reset() {
this._proto._reset();
// SASL
this.do_session = false;
this.do_bind = false;
// handler lists
this.timedHandlers = [];
this.handlers = [];
this.removeTimeds = [];
this.removeHandlers = [];
this.addTimeds = [];
this.addHandlers = [];
this.authenticated = false;
this.connected = false;
this.disconnecting = false;
this.restored = false;
this._data = [];
/** @type {Request[]} */
this._requests = [];
this._uniqueId = 0;
}
/**
* Pause the request manager.
*
* This will prevent Strophe from sending any more requests to the
* server. This is very useful for temporarily pausing
* BOSH-Connections while a lot of send() calls are happening quickly.
* This causes Strophe to send the data in a single request, saving
* many request trips.
*/
pause() {
this.paused = true;
}
/**
* Resume the request manager.
*
* This resumes after pause() has been called.
*/
resume() {
this.paused = false;
}
/**
* Generate a unique ID for use in <iq/> elements.
*
* All <iq/> stanzas are required to have unique id attributes. This
* function makes creating these easy. Each connection instance has
* a counter which starts from zero, and the value of this counter
* plus a colon followed by the suffix becomes the unique id. If no
* suffix is supplied, the counter is used as the unique id.
*
* Suffixes are used to make debugging easier when reading the stream
* data, and their use is recommended. The counter resets to 0 for
* every new connection for the same reason. For connections to the
* same server that authenticate the same way, all the ids should be
* the same, which makes it easy to see changes. This is useful for
* automated testing as well.
*
* @param {string} suffix - A optional suffix to append to the id.
* @returns {string} A unique string to be used for the id attribute.
*/
// eslint-disable-next-line class-methods-use-this
getUniqueId(suffix) {
const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = Math.random() * 16 | 0,
v = c === 'x' ? r : r & 0x3 | 0x8;
return v.toString(16);
});
if (typeof suffix === 'string' || typeof suffix === 'number') {
return uuid + ':' + suffix;
} else {
return uuid + '';
}
}
/**
* Register a handler function for when a protocol (websocker or HTTP)
* error occurs.
*
* NOTE: Currently only HTTP errors for BOSH requests are handled.
* Patches that handle websocket errors would be very welcome.
*
* @example
* function onError(err_code){
* //do stuff
* }
*
* const conn = Strophe.connect('http://example.com/http-bind');
* conn.addProtocolErrorHandler('HTTP', 500, onError);
* // Triggers HTTP 500 error and onError handler will be called
* conn.connect('user_jid@incorrect_jabber_host', 'secret', onConnect);
*
* @param {'HTTP'|'websocket'} protocol - 'HTTP' or 'websocket'
* @param {number} status_code - Error status code (e.g 500, 400 or 404)
* @param {Function} callback - Function that will fire on Http error
*/
addProtocolErrorHandler(protocol, status_code, callback) {
this.protocolErrorHandlers[protocol][status_code] = callback;
}
/**
* @typedef {Object} Password
* @property {string} Password.name
* @property {string} Password.ck
* @property {string} Password.sk
* @property {number} Password.iter
* @property {string} Password.salt
*/
/**
* Starts the connection process.
*
* As the connection process proceeds, the user supplied callback will
* be triggered multiple times with status updates. The callback
* should take two arguments - the status code and the error condition.
*
* The status code will be one of the values in the Strophe.Status
* constants. The error condition will be one of the conditions
* defined in RFC 3920 or the condition 'strophe-parsererror'.
*
* The Parameters _wait_, _hold_ and _route_ are optional and only relevant
* for BOSH connections. Please see XEP 124 for a more detailed explanation
* of the optional parameters.
*
* @param {string} jid - The user's JID. This may be a bare JID,
* or a full JID. If a node is not supplied, SASL OAUTHBEARER or
* SASL ANONYMOUS authentication will be attempted (OAUTHBEARER will
* process the provided password value as an access token).
* (String or Object) pass - The user's password, or an object containing
* the users SCRAM client and server keys, in a fashion described as follows:
*
* { name: String, representing the hash used (eg. SHA-1),
* salt: String, base64 encoded salt used to derive the client key,
* iter: Int, the iteration count used to derive the client key,
* ck: String, the base64 encoding of the SCRAM client key
* sk: String, the base64 encoding of the SCRAM server key
* }
* @param {string|Password} pass - The user password
* @param {Function} callback - The connect callback function.
* @param {number} [wait] - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* @param {number} [hold] - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* @param {string} [route] - The optional route value.
* @param {string} [authcid] - The optional alternative authentication identity
* (username) if intending to impersonate another user.
* When using the SASL-EXTERNAL authentication mechanism, for example
* with client certificates, then the authcid value is used to
* determine whether an authorization JID (authzid) should be sent to
* the server. The authzid should NOT be sent to the server if the
* authzid and authcid are the same. So to prevent it from being sent
* (for example when the JID is already contained in the client
* certificate), set authcid to that same JID. See XEP-178 for more
* details.
* @param {number} [disconnection_timeout=3000] - The optional disconnection timeout
* in milliseconds before _doDisconnect will be called.
*/
connect(jid, pass, callback, wait, hold, route, authcid) {
let disconnection_timeout = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 3000;
this.jid = jid;
/** Authorization identity */
this.authzid = core.getBareJidFromJid(this.jid);
/** Authentication identity (User name) */
this.authcid = authcid || core.getNodeFromJid(this.jid);
/** Authentication identity (User password) */
this.pass = pass;
/**
* The SASL SCRAM client and server keys. This variable will be populated with a non-null
* object of the above described form after a successful SCRAM connection
*/
this.scram_keys = null;
this.connect_callback = callback;
this.disconnecting = false;
this.connected = false;
this.authenticated = false;
this.restored = false;
this.disconnection_timeout = disconnection_timeout;
// parse jid for domain
this.domain = core.getDomainFromJid(this.jid);
this._changeConnectStatus(Status.CONNECTING, null);
this._proto._connect(wait, hold, route);
}
/**
* Attach to an already created and authenticated BOSH session.
*
* This function is provided to allow Strophe to attach to BOSH
* sessions which have been created externally, perhaps by a Web
* application. This is often used to support auto-login type features
* without putting user credentials into the page.
*
* @param {string|Function} jid - The full JID that is bound by the session.
* @param {string} [sid] - The SID of the BOSH session.
* @param {number} [rid] - The current RID of the BOSH session. This RID
* will be used by the next request.
* @param {Function} [callback] - The connect callback function.
* @param {number} [wait] - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* Other settings will require tweaks to the Strophe.TIMEOUT value.
* @param {number} [hold] - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* @param {number} [wind] - The optional HTTBIND window value. This is the
* allowed range of request ids that are valid. The default is 5.
*/
attach(jid, sid, rid, callback, wait, hold, wind) {
if (this._proto instanceof core.Bosh && typeof jid === 'string') {
return this._proto._attach(jid, sid, rid, callback, wait, hold, wind);
} else if (this._proto instanceof core.WorkerWebsocket && typeof jid === 'function') {
const callback = jid;
return this._proto._attach(callback);
} else {
throw new SessionError('The "attach" method is not available for your connection protocol');
}
}
/**
* Attempt to restore a cached BOSH session.
*
* This function is only useful in conjunction with providing the
* "keepalive":true option when instantiating a new {@link Strophe.Connection}.
*
* When "keepalive" is set to true, Strophe will cache the BOSH tokens
* RID (Request ID) and SID (Session ID) and then when this function is
* called, it will attempt to restore the session from those cached
* tokens.
*
* This function must therefore be called instead of connect or attach.
*
* For an example on how to use it, please see examples/restore.js
*
* @param {string} jid - The user's JID. This may be a bare JID or a full JID.
* @param {Function} callback - The connect callback function.
* @param {number} [wait] - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* @param {number} [hold] - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* @param {number} [wind] - The optional HTTBIND window value. This is the
* allowed range of request ids that are valid. The default is 5.
*/
restore(jid, callback, wait, hold, wind) {
if (!(this._proto instanceof core.Bosh) || !this._sessionCachingSupported()) {
throw new SessionError('The "restore" method can only be used with a BOSH connection.');
}
if (this._sessionCachingSupported()) {
this._proto._restore(jid, callback, wait, hold, wind);
}
}
/**
* Checks whether sessionStorage and JSON are supported and whether we're
* using BOSH.
*/
_sessionCachingSupported() {
if (this._proto instanceof core.Bosh) {
if (!JSON) {
return false;
}
try {
sessionStorage.setItem('_strophe_', '_strophe_');
sessionStorage.removeItem('_strophe_');
} catch (e) {
return false;
}
return true;
}
return false;
}
/**
* User overrideable function that receives XML data coming into the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.xmlInput = function (elem) {
* > (user code)
* > };
*
* Due to limitations of current Browsers' XML-Parsers the opening and closing
* <stream> tag for WebSocket-Connoctions will be passed as selfclosing here.
*
* BOSH-Connections will have all stanzas wrapped in a <body> tag. See
* <Strophe.Bosh.strip> if you want to strip this tag.
*
* @param {Node|MessageEvent} elem - The XML data received by the connection.
*/
// eslint-disable-next-line no-unused-vars, class-methods-use-this
xmlInput(elem) {
return;
}
/**
* User overrideable function that receives XML data sent to the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.xmlOutput = function (elem) {
* > (user code)
* > };
*
* Due to limitations of current Browsers' XML-Parsers the opening and closing
* <stream> tag for WebSocket-Connoctions will be passed as selfclosing here.
*
* BOSH-Connections will have all stanzas wrapped in a <body> tag. See
* <Strophe.Bosh.strip> if you want to strip this tag.
*
* @param {Element} elem - The XMLdata sent by the connection.
*/
// eslint-disable-next-line no-unused-vars, class-methods-use-this
xmlOutput(elem) {
return;
}
/**
* User overrideable function that receives raw data coming into the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.rawInput = function (data) {
* > (user code)
* > };
*
* @param {string} data - The data received by the connection.
*/
// eslint-disable-next-line no-unused-vars, class-methods-use-this
rawInput(data) {
return;
}
/**
* User overrideable function that receives raw data sent to the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.rawOutput = function (data) {
* > (user code)
* > };
*
* @param {string} data - The data sent by the connection.
*/
// eslint-disable-next-line no-unused-vars, class-methods-use-this
rawOutput(data) {
return;
}
/**
* User overrideable function that receives the new valid rid.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.nextValidRid = function (rid) {
* > (user code)
* > };
*
* @param {number} rid - The next valid rid
*/
// eslint-disable-next-line no-unused-vars, class-methods-use-this
nextValidRid(rid) {
return;
}
/**
* Send a stanza.
*
* This function is called to push data onto the send queue to
* go out over the wire. Whenever a request is sent to the BOSH
* server, all pending data is sent and the queue is flushed.
*
* @param {Element|Builder|Element[]|Builder[]} stanza - The stanza to send
*/
send(stanza) {
if (stanza === null) return;
if (Array.isArray(stanza)) {
stanza.forEach(s => this._queueData(s instanceof builder ? s.tree() : s));
} else {
const el = stanza instanceof builder ? stanza.tree() : stanza;
this._queueData(el);
}
this._proto._send();
}
/**
* Immediately send any pending outgoing data.
*
* Normally send() queues outgoing data until the next idle period
* (100ms), which optimizes network use in the common cases when
* several send()s are called in succession. flush() can be used to
* immediately send all pending data.
*/
flush() {
// cancel the pending idle period and run the idle function
// immediately
clearTimeout(this._idleTimeout);
this._onIdle();
}
/**
* Helper function to send presence stanzas. The main benefit is for
* sending presence stanzas for which you expect a responding presence
* stanza with the same id (for example when leaving a chat room).
*
* @param {Element} stanza - The stanza to send.
* @param {Function} [callback] - The callback function for a successful request.
* @param {Function} [errback] - The callback function for a failed or timed
* out request. On timeout, the stanza will be null.
* @param {number} [timeout] - The time specified in milliseconds for a
* timeout to occur.
* @return {string} The id used to send the presence.
*/
sendPresence(stanza, callback, errback, timeout) {
/** @type {TimedHandler} */
let timeoutHandler = null;
const el = stanza instanceof builder ? stanza.tree() : stanza;
let id = el.getAttribute('id');
if (!id) {
// inject id if not found
id = this.getUniqueId('sendPresence');
el.setAttribute('id', id);
}
if (typeof callback === 'function' || typeof errback === 'function') {
const handler = this.addHandler( /** @param {Element} stanza */
stanza => {
// remove timeout handler if there is one
if (timeoutHandler) this.deleteTimedHandler(timeoutHandler);
if (stanza.getAttribute('type') === 'error') {
errback?.(stanza);
} else if (callback) {
callback(stanza);
}
}, null, 'presence', null, id);
// if timeout specified, set up a timeout handler.
if (timeout) {
timeoutHandler = this.addTimedHandler(timeout, () => {
// get rid of normal handler
this.deleteHandler(handler);
// call errback on timeout with null stanza
errback?.(null);
return false;
});
}
}
this.send(el);
return id;
}
/**
* Helper function to send IQ stanzas.
*
* @param {Element|Builder} stanza - The stanza to send.
* @param {Function} [callback] - The callback function for a successful request.
* @param {Function} [errback] - The callback function for a failed or timed
* out request. On timeout, the stanza will be null.
* @param {number} [timeout] - The time specified in milliseconds for a
* timeout to occur.
* @return {string} The id used to send the IQ.
*/
sendIQ(stanza, callback, errback, timeout) {
/** @type {TimedHandler} */
let timeoutHandler = null;
const el = stanza instanceof builder ? stanza.tree() : stanza;
let id = el.getAttribute('id');
if (!id) {
// inject id if not found
id = this.getUniqueId('sendIQ');
el.setAttribute('id', id);
}
if (typeof callback === 'function' || typeof errback === 'function') {
const handler = this.addHandler( /** @param {Element} stanza */
stanza => {
// remove timeout handler if there is one
if (timeoutHandler) this.deleteTimedHandler(timeoutHandler);
const iqtype = stanza.getAttribute('type');
if (iqtype === 'result') {
callback?.(stanza);
} else if (iqtype === 'error') {
errback?.(stanza);
} else {
const error = new Error(`Got bad IQ type of ${iqtype}`);
error.name = 'StropheError';
throw error;
}
}, null, 'iq', ['error', 'result'], id);
// if timeout specified, set up a timeout handler.
if (timeout) {
timeoutHandler = this.addTimedHandler(timeout, () => {
// get rid of normal handler
this.deleteHandler(handler);
// call errback on timeout with null stanza
errback?.(null);
return false;
});
}
}
this.send(el);
return id;
}
/**
* Queue outgoing data for later sending. Also ensures that the data
* is a DOMElement.
* @private
* @param {Element} element
*/
_queueData(element) {
if (element === null || !element.tagName || !element.childNodes) {
const error = new Error('Cannot queue non-DOMElement.');
error.name = 'StropheError';
throw error;
}
this._data.push(element);
}
/**
* Send an xmpp:restart stanza.
* @private
*/
_sendRestart() {
this._data.push('restart');
this._proto._sendRestart();
this._idleTimeout = setTimeout(() => this._onIdle(), 100);
}
/**
* Add a timed handler to the connection.
*
* This function adds a timed handler. The provided handler will
* be called every period milliseconds until it returns false,
* the connection is terminated, or the handler is removed. Handlers
* that wish to continue being invoked should return true.
*
* Because of method binding it is necessary to save the result of
* this function if you wish to remove a handler with
* deleteTimedHandler().
*
* Note that user handlers are not active until authentication is
* successful.
*
* @param {number} period - The period of the handler.
* @param {Function} handler - The callback function.
* @return {TimedHandler} A reference to the handler that can be used to remove it.
*/
addTimedHandler(period, handler) {
const thand = new core.TimedHandler(period, handler);
this.addTimeds.push(thand);
return thand;
}
/**
* Delete a timed handler for a connection.
*
* This function removes a timed handler from the connection. The
* handRef parameter is *not* the function passed to addTimedHandler(),
* but is the reference returned from addTimedHandler().
* @param {TimedHandler} handRef - The handler reference.
*/
deleteTimedHandler(handRef) {
// this must be done in the Idle loop so that we don't change
// the handlers during iteration
this.removeTimeds.push(handRef);
}
/**
* @typedef {Object} HandlerOptions
* @property {boolean} [HandlerOptions.matchBareFromJid]
* @property {boolean} [HandlerOptions.ignoreNamespaceFragment]
*/
/**
* Add a stanza handler for the connection.
*
* This function adds a stanza handler to the connection. The
* handler callback will be called for any stanza that matches
* the parameters. Note that if multiple parameters are supplied,
* they must all match for the handler to be invoked.
*
* The handler will receive the stanza that triggered it as its argument.
* *The handler should return true if it is to be invoked again;
* returning false will remove the handler after it returns.*
*
* As a convenience, the ns parameters applies to the top level element
* and also any of its immediate children. This is primarily to make
* matching /iq/query elements easy.
*
* ### Options
*
* With the options argument, you can specify boolean flags that affect how
* matches are being done.
*
* Currently two flags exist:
*
* * *matchBareFromJid*:
* When set to true, the from parameter and the
* from attribute on the stanza will be matched as bare JIDs instead
* of full JIDs. To use this, pass {matchBareFromJid: true} as the
* value of options. The default value for matchBareFromJid is false.
*
* * *ignoreNamespaceFragment*:
* When set to true, a fragment specified on the stanza's namespace
* URL will be ignored when it's matched with the one configured for
* the handler.
*
* This means that if you register like this:
*
* > connection.addHandler(
* > handler,
* > 'http://jabber.org/protocol/muc',
* > null, null, null, null,
* > {'ignoreNamespaceFragment': true}
* > );
*
* Then a stanza with XML namespace of
* 'http://jabber.org/protocol/muc#user' will also be matched. If
* 'ignoreNamespaceFragment' is false, then only stanzas with
* 'http://jabber.org/protocol/muc' will be matched.
*
* ### Deleting the handler
*
* The return value should be saved if you wish to remove the handler
* with `deleteHandler()`.
*
* @param {Function} handler - The user callback.
* @param {string} ns - The namespace to match.
* @param {string} name - The stanza name to match.
* @param {string|string[]} type - The stanza type (or types if an array) to match.
* @param {string} id - The stanza id attribute to match.
* @param {string} [from] - The stanza from attribute to match.
* @param {HandlerOptions} [options] - The handler options
* @return {Handler} A reference to the handler that can be used to remove it.
*/
addHandler(handler, ns, name, type, id, from, options) {
const hand = new src_handler(handler, ns, name, type, id, from, options);
this.addHandlers.push(hand);
return hand;
}
/**
* Delete a stanza handler for a connection.
*
* This function removes a stanza handler from the connection. The
* handRef parameter is *not* the function passed to addHandler(),
* but is the reference returned from addHandler().
*
* @param {Handler} handRef - The handler reference.
*/
deleteHandler(handRef) {
// this must be done in the Idle loop so that we don't change
// the handlers during iteration
this.removeHandlers.push(handRef);
// If a handler is being deleted while it is being added,
// prevent it from getting added
const i = this.addHandlers.indexOf(handRef);
if (i >= 0) {
this.addHandlers.splice(i, 1);
}
}
/**
* Register the SASL mechanisms which will be supported by this instance of
* Strophe.Connection (i.e. which this XMPP client will support).
* @param {SASLMechanism[]} mechanisms - Array of objects with Strophe.SASLMechanism prototypes
*/
registerSASLMechanisms(mechanisms) {
this.mechanisms = {};
(mechanisms || [core.SASLAnonymous, core.SASLExternal, core.SASLOAuthBearer, core.SASLXOAuth2, core.SASLPlain, core.SASLSHA1, core.SASLSHA256, core.SASLSHA384, core.SASLSHA512]).forEach(m => this.registerSASLMechanism(m));
}
/**
* Register a single SASL mechanism, to be supported by this client.
* @param {any} Mechanism - Object with a Strophe.SASLMechanism prototype
*/
registerSASLMechanism(Mechanism) {
const mechanism = new Mechanism();
this.mechanisms[mechanism.mechname] = mechanism;
}
/**
* Start the graceful disconnection process.
*
* This function starts the disconnection process. This process starts
* by sending unavailable presence and sending BOSH body of type
* terminate. A timeout handler makes sure that disconnection happens
* even if the BOSH server does not respond.
* If the Connection object isn't connected, at least tries to abort all pending requests
* so the connection object won't generate successful requests (which were already opened).
*
* The user supplied connection callback will be notified of the
* progress as this process happens.
*
* @param {string} [reason] - The reason the disconnect is occuring.
*/
disconnect(reason) {
this._changeConnectStatus(Status.DISCONNECTING, reason);
if (reason) {
core.warn('Disconnect was called because: ' + reason);
} else {
core.info('Disconnect was called');
}
if (this.connected) {
let pres = null;
this.disconnecting = true;
if (this.authenticated) {
pres = $pres({
'xmlns': core.NS.CLIENT,
'type': 'unavailable'
});
}
// setup timeout handler
this._disconnectTimeout = this._addSysTimedHandler(this.disconnection_timeout, this._onDisconnectTimeout.bind(this));
this._proto._disconnect(pres);
} else {
core.warn('Disconnect was called before Strophe connected to the server');
this._proto._abortAllRequests();
this._doDisconnect();
}
}
/**
* _Private_ helper function that makes sure plugins and the user's
* callback are notified of connection status changes.
* @param {number} status - the new connection status, one of the values
* in Strophe.Status
* @param {string|null} [condition] - the error condition
* @param {Element} [elem] - The triggering stanza.
*/
_changeConnectStatus(status, condition, elem) {
// notify all plugins listening for status changes
for (const k in core._connectionPlugins) {
if (Object.prototype.hasOwnProperty.call(core._connectionPlugins, k)) {
// @ts-ignore
const plugin = this[k];
if (plugin.statusChanged) {
try {
plugin.statusChanged(status, condition);
} catch (err) {
core.error(`${k} plugin caused an exception changing status: ${err}`);
}
}
}
}
// notify the user's callback
if (this.connect_callback) {
try {
this.connect_callback(status, condition, elem);
} catch (e) {
core._handleError(e);
core.error(`User connection callback caused an exception: ${e}`);
}
}
}
/**
* _Private_ function to disconnect.
*
* This is the last piece of the disconnection logic. This resets the
* connection and alerts the user's connection callback.
* @param {string|null} [condition] - the error condition
*/
_doDisconnect(condition) {
if (typeof this._idleTimeout === 'number') {
clearTimeout(this._idleTimeout);
}
// Cancel Disconnect Timeout
if (this._disconnectTimeout !== null) {
this.deleteTimedHandler(this._disconnectTimeout);
this._disconnectTimeout = null;
}
core.debug('_doDisconnect was called');
this._proto._doDisconnect();
this.authenticated = false;
this.disconnecting = false;
this.restored = false;
// delete handlers
this.handlers = [];
this.timedHandlers = [];
this.removeTimeds = [];
this.removeHandlers = [];
this.addTimeds = [];
this.addHandlers = [];
// tell the parent we disconnected
this._changeConnectStatus(Status.DISCONNECTED, condition);
this.connected = false;
}
/**
* _Private_ handler to processes incoming data from the the connection.
*
* Except for _connect_cb handling the initial connection request,
* this function handles the incoming data for all requests. This
* function also fires stanza handlers that match each incoming
* stanza.
* @param {Element | Request} req - The request that has data ready.
* @param {string} [raw] - The stanza as raw string.
*/
_dataRecv(req, raw) {
const elem = /** @type {Element} */
'_reqToData' in this._proto ? this._proto._reqToData( /** @type {Request} */req) : req;
if (elem === null) {
return;
}
if (this.xmlInput !== core.Connection.prototype.xmlInput) {
if (elem.nodeName === this._proto.strip && elem.childNodes.length) {
this.xmlInput(elem.childNodes[0]);
} else {
this.xmlInput(elem);
}
}
if (this.rawInput !== core.Connection.prototype.rawInput) {
if (raw) {
this.rawInput(raw);
} else {
this.rawInput(core.serialize(elem));
}
}
// remove handlers scheduled for deletion
while (this.removeHandlers.length > 0) {
const hand = this.removeHandlers.pop();
const i = this.handlers.indexOf(hand);
if (i >= 0) {
this.handlers.splice(i, 1);
}
}
// add handlers scheduled for addition
while (this.addHandlers.length > 0) {
this.handlers.push(this.addHandlers.pop());
}
// handle graceful disconnect
if (this.disconnecting && this._proto._emptyQueue()) {
this._doDisconnect();
return;
}
const type = elem.getAttribute('type');
if (type !== null && type === 'terminate') {
// Don't process stanzas that come in after disconnect
if (this.disconnecting) {
return;
}
// an error occurred
let cond = elem.getAttribute('condition');
const conflict = elem.getElementsByTagName('conflict');
if (cond !== null) {
if (cond === 'remote-stream-error' && conflict.length > 0) {
cond = 'conflict';
}
this._changeConnectStatus(Status.CONNFAIL, cond);
} else {
this._changeConnectStatus(Status.CONNFAIL, core.ErrorCondition.UNKNOWN_REASON);
}
this._doDisconnect(cond);
return;
}
// send each incoming stanza through the handler chain
core.forEachChild(elem, null, /** @param {Element} child */
child => {
const matches = [];
this.handlers = this.handlers.reduce((handlers, handler) => {
try {
if (handler.isMatch(child) && (this.authenticated || !handler.user)) {
if (handler.run(child)) {
handlers.push(handler);
}
matches.push(handler);
} else {
handlers.push(handler);
}
} catch (e) {
// if the handler throws an exception, we consider it as false
core.warn('Removing Strophe handlers due to uncaught exception: ' + e.message);
}
return handlers;
}, []);
// If no handler was fired for an incoming IQ with type="set",
// then we return an IQ error stanza with service-unavailable.
if (!matches.length && this.iqFallbackHandler.isMatch(child)) {
this.iqFallbackHandler.run(child);
}
});
}
/**
* @callback connectionCallback
* @param {Connection} connection
*/
/**
* _Private_ handler for initial connection request.
*
* This handler is used to process the initial connection request
* response from the BOSH server. It is used to set up authentication
* handlers and start the authentication process.
*
* SASL authentication will be attempted if available, otherwise
* the code will fall back to legacy authentication.
*
* @param {Element | Request} req - The current request.
* @param {connectionCallback} _callback - low level (xmpp) connect callback function.
* Useful for plugins with their own xmpp connect callback (when they
* want to do something special).
* @param {string} [raw] - The stanza as raw string.
*/
_connect_cb(req, _callback, raw) {
core.debug('_connect_cb was called');
this.connected = true;
let bodyWrap;
try {
bodyWrap = /** @type {Element} */
'_reqToData' in this._proto ? this._proto._reqToData( /** @type {Request} */req) : req;
} catch (e) {
if (e.name !== core.ErrorCondition.BAD_FORMAT) {
throw e;
}
this._changeConnectStatus(Status.CONNFAIL, core.ErrorCondition.BAD_FORMAT);
this._doDisconnect(core.ErrorCondition.BAD_FORMAT);
}
if (!bodyWrap) {
return;
}
if (this.xmlInput !== core.Connection.prototype.xmlInput) {
if (bodyWrap.nodeName === this._proto.strip && bodyWrap.childNodes.length) {
this.xmlInput(bodyWrap.childNodes[0]);
} else {
this.xmlInput(bodyWrap);
}
}
if (this.rawInput !== core.Connection.prototype.rawInput) {
if (raw) {
this.rawInput(raw);
} else {
this.rawInput(core.serialize(bodyWrap));
}
}
const conncheck = this._proto._connect_cb(bodyWrap);
if (conncheck === Status.CONNFAIL) {
return;
}
// Check for the stream:features tag
let hasFeatures;
if (bodyWrap.getElementsByTagNameNS) {
hasFeatures = bodyWrap.getElementsByTagNameNS(core.NS.STREAM, 'features').length > 0;
} else {
hasFeatures = bodyWrap.getElementsByTagName('stream:features').length > 0 || bodyWrap.getElementsByTagName('features').length > 0;
}
if (!hasFeatures) {
this._proto._no_auth_received(_callback);
return;
}
const matched = Array.from(bodyWrap.getElementsByTagName('mechanism')).map(m => this.mechanisms[m.textContent]).filter(m => m);
if (matched.length === 0) {
if (bodyWrap.getElementsByTagName('auth').length === 0) {
// There are no matching SASL mechanisms and also no legacy
// auth available.
this._proto._no_auth_received(_callback);
return;
}
}
if (this.do_authentication !== false) {
this.authenticate(matched);
}
}
/**
* Sorts an array of objects with prototype SASLMechanism according to
* their priorities.
* @param {SASLMechanism[]} mechanisms - Array of SASL mechanisms.
*/
// eslint-disable-next-line class-methods-use-this
sortMechanismsByPriority(mechanisms) {
// Sorting mechanisms according to priority.
for (let i = 0; i < mechanisms.length - 1; ++i) {
let higher = i;
for (let j = i + 1; j < mechanisms.length; ++j) {
if (mechanisms[j].priority > mechanisms[higher].priority) {
higher = j;
}
}
if (higher !== i) {
const swap = mechanisms[i];
mechanisms[i] = mechanisms[higher];
mechanisms[higher] = swap;
}
}
return mechanisms;
}
/**
* Set up authentication
*
* Continues the initial connection request by setting up authentication
* handlers and starting the authentication process.
*
* SASL authentication will be attempted if available, otherwise
* the code will fall back to legacy authentication.
*
* @param {SASLMechanism[]} matched - Array of SASL mechanisms supported.
*/
authenticate(matched) {
if (!this._attemptSASLAuth(matched)) {
this._attemptLegacyAuth();
}
}
/**
* Iterate through an array of SASL mechanisms and attempt authentication
* with the highest priority (enabled) mechanism.
*
* @private
* @param {SASLMechanism[]} mechanisms - Array of SASL mechanisms.
* @return {Boolean} mechanism_found - true or false, depending on whether a
* valid SASL mechanism was found with which authentication could be started.
*/
_attemptSASLAuth(mechanisms) {
mechanisms = this.sortMechanismsByPriority(mechanisms || []);
let mechanism_found = false;
for (let i = 0; i < mechanisms.length; ++i) {
if (!mechanisms[i].test(this)) {
continue;
}
this._sasl_success_handler = this._addSysHandler(this._sasl_success_cb.bind(this), null, 'success', null, null);
this._sasl_failure_handler = this._addSysHandler(this._sasl_failure_cb.bind(this), null, 'failure', null, null);
this._sasl_challenge_handler = this._addSysHandler(this._sasl_challenge_cb.bind(this), null, 'challenge', null, null);
this._sasl_mechanism = mechanisms[i];
this._sasl_mechanism.onStart(this);
const request_auth_exchange = $build('auth', {
'xmlns': core.NS.SASL,
'mechanism': this._sasl_mechanism.mechname
});
if (this._sasl_mechanism.isClientFirst) {
const response = this._sasl_mechanism.clientChallenge(this);
request_auth_exchange.t((0,abab.btoa)( /** @type {string} */response));
}
this.send(request_auth_exchange.tree());
mechanism_found = true;
break;
}
return mechanism_found;
}
/**
* _Private_ handler for the SASL challenge
* @private
* @param {Element} elem
*/
async _sasl_challenge_cb(elem) {
const challenge = (0,abab.atob)(getText(elem));
const response = await this._sasl_mechanism.onChallenge(this, challenge);
const stanza = $build('response', {
'xmlns': core.NS.SASL
});
if (response) stanza.t((0,abab.btoa)(response));
this.send(stanza.tree());
return true;
}
/**
* Attempt legacy (i.e. non-SASL) authentication.
* @private
*/
_attemptLegacyAuth() {
if (core.getNodeFromJid(this.jid) === null) {
// we don't have a node, which is required for non-anonymous
// client connections
this._changeConnectStatus(Status.CONNFAIL, core.ErrorCondition.MISSING_JID_NODE);
this.disconnect(core.ErrorCondition.MISSING_JID_NODE);
} else {
// Fall back to legacy authentication
this._changeConnectStatus(Status.AUTHENTICATING, null);
this._addSysHandler(this._onLegacyAuthIQResult.bind(this), null, null, null, '_auth_1');
this.send($iq({
'type': 'get',
'to': this.domain,
'id': '_auth_1'
}).c('query', {
xmlns: core.NS.AUTH
}).c('username', {}).t(core.getNodeFromJid(this.jid)).tree());
}
}
/**
* _Private_ handler for legacy authentication.
*
* This handler is called in response to the initial <iq type='get'/>
* for legacy authentication. It builds an authentication <iq/> and
* sends it, creating a handler (calling back to _auth2_cb()) to
* handle the result
* @private
* @return {false} `false` to remove the handler.
*/
// eslint-disable-next-line no-unused-vars
//
_onLegacyAuthIQResult() {
const pass = typeof this.pass === 'string' ? this.pass : '';
// build plaintext auth iq
const iq = $iq({
type: 'set',
id: '_auth_2'
}).c('query', {
xmlns: core.NS.AUTH
}).c('username', {}).t(core.getNodeFromJid(this.jid)).up().c('password').t(pass);
if (!core.getResourceFromJid(this.jid)) {
// since the user has not supplied a resource, we pick
// a default one here. unlike other auth methods, the server
// cannot do this for us.
this.jid = core.getBareJidFromJid(this.jid) + '/strophe';
}
iq.up().c('resource', {}).t(core.getResourceFromJid(this.jid));
this._addSysHandler(this._auth2_cb.bind(this), null, null, null, '_auth_2');
this.send(iq.tree());
return false;
}
/**
* _Private_ handler for succesful SASL authentication.
* @private
* @param {Element} elem - The matching stanza.
* @return {false} `false` to remove the handler.
*/
_sasl_success_cb(elem) {
if (this._sasl_data['server-signature']) {
let serverSignature;
const success = (0,abab.atob)(getText(elem));
const attribMatch = /([a-z]+)=([^,]+)(,|$)/;
const matches = success.match(attribMatch);
if (matches[1] === 'v') {
serverSignature = matches[2];
}
if (serverSignature !== this._sasl_data['server-signature']) {
// remove old handlers
this.deleteHandler(this._sasl_failure_handler);
this._sasl_failure_handler = null;
if (this._sasl_challenge_handler) {
this.deleteHandler(this._sasl_challenge_handler);
this._sasl_challenge_handler = null;
}
this._sasl_data = {};
return this._sasl_failure_cb(null);
}
}
core.info('SASL authentication succeeded.');
if (this._sasl_data.keys) {
this.scram_keys = this._sasl_data.keys;
}
if (this._sasl_mechanism) {
this._sasl_mechanism.onSuccess();
}
// remove old handlers
this.deleteHandler(this._sasl_failure_handler);
this._sasl_failure_handler = null;
if (this._sasl_challenge_handler) {
this.deleteHandler(this._sasl_challenge_handler);
this._sasl_challenge_handler = null;
}
/** @type {Handler[]} */
const streamfeature_handlers = [];
/**
* @param {Handler[]} handlers
* @param {Element} elem
*/
const wrapper = (handlers, elem) => {
while (handlers.length) {
this.deleteHandler(handlers.pop());
}
this._onStreamFeaturesAfterSASL(elem);
return false;
};
streamfeature_handlers.push(this._addSysHandler( /** @param {Element} elem */
elem => wrapper(streamfeature_handlers, elem), null, 'stream:features', null, null));
streamfeature_handlers.push(this._addSysHandler( /** @param {Element} elem */
elem => wrapper(streamfeature_handlers, elem), core.NS.STREAM, 'features', null, null));
// we must send an xmpp:restart now
this._sendRestart();
return false;
}
/**
* @private
* @param {Element} elem - The matching stanza.
* @return {false} `false` to remove the handler.
*/
_onStreamFeaturesAfterSASL(elem) {
// save stream:features for future usage
this.features = elem;
for (let i = 0; i < elem.childNodes.length; i++) {
const child = elem.childNodes[i];
if (child.nodeName === 'bind') {
this.do_bind = true;
}
if (child.nodeName === 'session') {
this.do_session = true;
}
}
if (!this.do_bind) {
this._changeConnectStatus(Status.AUTHFAIL, null);
return false;
} else if (!this.options.explicitResourceBinding) {
this.bind();
} else {
this._changeConnectStatus(Status.BINDREQUIRED, null);
}
return false;
}
/**
* Sends an IQ to the XMPP server to bind a JID resource for this session.
*
* https://tools.ietf.org/html/rfc6120#section-7.5
*
* If `explicitResourceBinding` was set to a truthy value in the options
* passed to the Strophe.Connection constructor, then this function needs
* to be called explicitly by the client author.
*
* Otherwise it'll be called automatically as soon as the XMPP server
* advertises the "urn:ietf:params:xml:ns:xmpp-bind" stream feature.
*/
bind() {
if (!this.do_bind) {
core.log(core.LogLevel.INFO, `Strophe.Connection.prototype.bind called but "do_bind" is false`);
return;
}
this._addSysHandler(this._onResourceBindResultIQ.bind(this), null, null, null, '_bind_auth_2');
const resource = core.getResourceFromJid(this.jid);
if (resource) {
this.send($iq({
type: 'set',
id: '_bind_auth_2'
}).c('bind', {
xmlns: core.NS.BIND
}).c('resource', {}).t(resource).tree());
} else {
this.send($iq({
type: 'set',
id: '_bind_auth_2'
}).c('bind', {
xmlns: core.NS.BIND
}).tree());
}
}
/**
* _Private_ handler for binding result and session start.
* @private
* @param {Element} elem - The matching stanza.
* @return {false} `false` to remove the handler.
*/
_onResourceBindResultIQ(elem) {
if (elem.getAttribute('type') === 'error') {
core.warn('Resource binding failed.');
const conflict = elem.getElementsByTagName('conflict');
let condition;
if (conflict.length > 0) {
condition = core.ErrorCondition.CONFLICT;
}
this._changeConnectStatus(Status.AUTHFAIL, condition, elem);
return false;
}
// TODO - need to grab errors
const bind = elem.getElementsByTagName('bind');
if (bind.length > 0) {
const jidNode = bind[0].getElementsByTagName('jid');
if (jidNode.length > 0) {
this.authenticated = true;
this.jid = getText(jidNode[0]);
if (this.do_session) {
this._establishSession();
} else {
this._changeConnectStatus(Status.CONNECTED, null);
}
}
} else {
core.warn('Resource binding failed.');
this._changeConnectStatus(Status.AUTHFAIL, null, elem);
return false;
}
}
/**
* Send IQ request to establish a session with the XMPP server.
*
* See https://xmpp.org/rfcs/rfc3921.html#session
*
* Note: The protocol for session establishment has been determined as
* unnecessary and removed in RFC-6121.
* @private
*/
_establishSession() {
if (!this.do_session) {
throw new Error(`Strophe.Connection.prototype._establishSession ` + `called but apparently ${core.NS.SESSION} wasn't advertised by the server`);
}
this._addSysHandler(this._onSessionResultIQ.bind(this), null, null, null, '_session_auth_2');
this.send($iq({
type: 'set',
id: '_session_auth_2'
}).c('session', {
xmlns: core.NS.SESSION
}).tree());
}
/**
* _Private_ handler for the server's IQ response to a client's session
* request.
*
* This sets Connection.authenticated to true on success, which
* starts the processing of user handlers.
*
* See https://xmpp.org/rfcs/rfc3921.html#session
*
* Note: The protocol for session establishment has been determined as
* unnecessary and removed in RFC-6121.
* @private
* @param {Element} elem - The matching stanza.
* @return {false} `false` to remove the handler.
*/
_onSessionResultIQ(elem) {
if (elem.getAttribute('type') === 'result') {
this.authenticated = true;
this._changeConnectStatus(Status.CONNECTED, null);
} else if (elem.getAttribute('type') === 'error') {
this.authenticated = false;
core.warn('Session creation failed.');
this._changeConnectStatus(Status.AUTHFAIL, null, elem);
return false;
}
return false;
}
/**
* _Private_ handler for SASL authentication failure.
* @param {Element} [elem] - The matching stanza.
* @return {false} `false` to remove the handler.
*/
_sasl_failure_cb(elem) {
// delete unneeded handlers
if (this._sasl_success_handler) {
this.deleteHandler(this._sasl_success_handler);
this._sasl_success_handler = null;
}
if (this._sasl_challenge_handler) {
this.deleteHandler(this._sasl_challenge_handler);
this._sasl_challenge_handler = null;
}
if (this._sasl_mechanism) this._sasl_mechanism.onFailure();
this._changeConnectStatus(Status.AUTHFAIL, null, elem);
return false;
}
/**
* _Private_ handler to finish legacy authentication.
*
* This handler is called when the result from the jabber:iq:auth
* <iq/> stanza is returned.
* @private
* @param {Element} elem - The stanza that triggered the callback.
* @return {false} `false` to remove the handler.
*/
_auth2_cb(elem) {
if (elem.getAttribute('type') === 'result') {
this.authenticated = true;
this._changeConnectStatus(Status.CONNECTED, null);
} else if (elem.getAttribute('type') === 'error') {
this._changeConnectStatus(Status.AUTHFAIL, null, elem);
this.disconnect('authentication failed');
}
return false;
}
/**
* _Private_ function to add a system level timed handler.
*
* This function is used to add a Strophe.TimedHandler for the
* library code. System timed handlers are allowed to run before
* authentication is complete.
* @param {number} period - The period of the handler.
* @param {Function} handler - The callback function.
*/
_addSysTimedHandler(period, handler) {
const thand = new timed_handler(period, handler);
thand.user = false;
this.addTimeds.push(thand);
return thand;
}
/**
* _Private_ function to add a system level stanza handler.
*
* This function is used to add a Handler for the
* library code. System stanza handlers are allowed to run before
* authentication is complete.
* @param {Function} handler - The callback function.
* @param {string} ns - The namespace to match.
* @param {string} name - The stanza name to match.
* @param {string} type - The stanza type attribute to match.
* @param {string} id - The stanza id attribute to match.
*/
_addSysHandler(handler, ns, name, type, id) {
const hand = new src_handler(handler, ns, name, type, id);
hand.user = false;
this.addHandlers.push(hand);
return hand;
}
/**
* _Private_ timeout handler for handling non-graceful disconnection.
*
* If the graceful disconnect process does not complete within the
* time allotted, this handler finishes the disconnect anyway.
* @return {false} `false` to remove the handler.
*/
_onDisconnectTimeout() {
core.debug('_onDisconnectTimeout was called');
this._changeConnectStatus(Status.CONNTIMEOUT, null);
this._proto._onDisconnectTimeout();
// actually disconnect
this._doDisconnect();
return false;
}
/**
* _Private_ handler to process events during idle cycle.
*
* This handler is called every 100ms to fire timed handlers that
* are ready and keep poll requests going.
*/
_onIdle() {
// add timed handlers scheduled for addition
// NOTE: we add before remove in the case a timed handler is
// added and then deleted before the next _onIdle() call.
while (this.addTimeds.length > 0) {
this.timedHandlers.push(this.addTimeds.pop());
}
// remove timed handlers that have been scheduled for deletion
while (this.removeTimeds.length > 0) {
const thand = this.removeTimeds.pop();
const i = this.timedHandlers.indexOf(thand);
if (i >= 0) {
this.timedHandlers.splice(i, 1);
}
}
// call ready timed handlers
const now = new Date().getTime();
const newList = [];
for (let i = 0; i < this.timedHandlers.length; i++) {
const thand = this.timedHandlers[i];
if (this.authenticated || !thand.user) {
const since = thand.lastCalled + thand.period;
if (since - now <= 0) {
if (thand.run()) {
newList.push(thand);
}
} else {
newList.push(thand);
}
}
}
this.timedHandlers = newList;
clearTimeout(this._idleTimeout);
this._proto._onIdle();
// reactivate the timer only if connected
if (this.connected) {
this._idleTimeout = setTimeout(() => this._onIdle(), 100);
}
}
}
/* harmony default export */ const connection = (Connection);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl.js
/**
* @typedef {import("./connection.js").default} Connection
*/
/**
* Encapsulates an SASL authentication mechanism.
*
* User code may override the priority for each mechanism or disable it completely.
* See <priority> for information about changing priority and <test> for informatian on
* how to disable a mechanism.
*
* By default, all mechanisms are enabled and t_he priorities are
*
* SCRAM-SHA-512 - 72
* SCRAM-SHA-384 - 71
* SCRAM-SHA-256 - 70
* SCRAM-SHA-1 - 60
* PLAIN - 50
* OAUTHBEARER - 40
* X-OAUTH2 - 30
* ANONYMOUS - 20
* EXTERNAL - 10
*
* See: {@link Strophe.Connection#registerSASLMechanisms}
*/
class SASLMechanism {
/**
* PrivateConstructor: Strophe.SASLMechanism
* SASL auth mechanism abstraction.
* @param {String} [name] - SASL Mechanism name.
* @param {Boolean} [isClientFirst] - If client should send response first without challenge.
* @param {Number} [priority] - Priority.
*/
constructor(name, isClientFirst, priority) {
/** Mechanism name. */
this.mechname = name;
/**
* If client sends response without initial server challenge.
*/
this.isClientFirst = isClientFirst;
/**
* Determines which {@link SASLMechanism} is chosen for authentication (Higher is better).
* Users may override this to prioritize mechanisms differently.
*
* Example: (This will cause Strophe to choose the mechanism that the server sent first)
*
* > Strophe.SASLPlain.priority = Strophe.SASLSHA1.priority;
*
* See <SASL mechanisms> for a list of available mechanisms.
*/
this.priority = priority;
}
/**
* Checks if mechanism able to run.
* To disable a mechanism, make this return false;
*
* To disable plain authentication run
* > Strophe.SASLPlain.test = function() {
* > return false;
* > }
*
* See <SASL mechanisms> for a list of available mechanisms.
* @param {Connection} connection - Target Connection.
* @return {boolean} If mechanism was able to run.
*/
// eslint-disable-next-line class-methods-use-this, no-unused-vars
test(connection) {
return true;
}
/**
* Called before starting mechanism on some connection.
* @param {Connection} connection - Target Connection.
*/
onStart(connection) {
this._connection = connection;
}
/**
* Called by protocol implementation on incoming challenge.
*
* By deafult, if the client is expected to send data first (isClientFirst === true),
* this method is called with `challenge` as null on the first call,
* unless `clientChallenge` is overridden in the relevant subclass.
* @param {Connection} connection - Target Connection.
* @param {string} [challenge] - current challenge to handle.
* @return {string|Promise<string|false>} Mechanism response.
*/
// eslint-disable-next-line no-unused-vars, class-methods-use-this
onChallenge(connection, challenge) {
throw new Error('You should implement challenge handling!');
}
/**
* Called by the protocol implementation if the client is expected to send
* data first in the authentication exchange (i.e. isClientFirst === true).
* @param {Connection} connection - Target Connection.
* @return {string|Promise<string|false>} Mechanism response.
*/
clientChallenge(connection) {
if (!this.isClientFirst) {
throw new Error('clientChallenge should not be called if isClientFirst is false!');
}
return this.onChallenge(connection);
}
/**
* Protocol informs mechanism implementation about SASL failure.
*/
onFailure() {
this._connection = null;
}
/**
* Protocol informs mechanism implementation about SASL success.
*/
onSuccess() {
this._connection = null;
}
}
/* harmony default export */ const sasl = (SASLMechanism);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-anon.js
/**
* @typedef {import("./connection.js").default} Connection
*/
class SASLAnonymous extends sasl {
/**
* SASL ANONYMOUS authentication.
*/
constructor() {
let mechname = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'ANONYMOUS';
let isClientFirst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
let priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 20;
super(mechname, isClientFirst, priority);
}
/**
* @param {Connection} connection
*/
// eslint-disable-next-line class-methods-use-this
test(connection) {
return connection.authcid === null;
}
}
/* harmony default export */ const sasl_anon = (SASLAnonymous);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-external.js
/**
* @typedef {import("./connection.js").default} Connection
*/
class SASLExternal extends sasl {
/**
* SASL EXTERNAL authentication.
*
* The EXTERNAL mechanism allows a client to request the server to use
* credentials established by means external to the mechanism to
* authenticate the client. The external means may be, for instance,
* TLS services.
*/
constructor() {
let mechname = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'EXTERNAL';
let isClientFirst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
let priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10;
super(mechname, isClientFirst, priority);
}
/**
* @param {Connection} connection
*/
// eslint-disable-next-line class-methods-use-this
onChallenge(connection) {
/* According to XEP-178, an authzid SHOULD NOT be presented when the
* authcid contained or implied in the client certificate is the JID (i.e.
* authzid) with which the user wants to log in as.
*
* To NOT send the authzid, the user should therefore set the authcid equal
* to the JID when instantiating a new Strophe.Connection object.
*/
return connection.authcid === connection.authzid ? '' : connection.authzid;
}
}
/* harmony default export */ const sasl_external = (SASLExternal);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-oauthbearer.js
/**
* @typedef {import("./connection.js").default} Connection
*/
class SASLOAuthBearer extends sasl {
/**
* SASL OAuth Bearer authentication.
*/
constructor() {
let mechname = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'OAUTHBEARER';
let isClientFirst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
let priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 40;
super(mechname, isClientFirst, priority);
}
/**
* @param {Connection} connection
*/
// eslint-disable-next-line class-methods-use-this
test(connection) {
return connection.pass !== null;
}
/**
* @param {Connection} connection
*/
// eslint-disable-next-line class-methods-use-this
onChallenge(connection) {
let auth_str = 'n,';
if (connection.authcid !== null) {
auth_str = auth_str + 'a=' + connection.authzid;
}
auth_str = auth_str + ',';
auth_str = auth_str + '\u0001';
auth_str = auth_str + 'auth=Bearer ';
auth_str = auth_str + connection.pass;
auth_str = auth_str + '\u0001';
auth_str = auth_str + '\u0001';
return utils.utf16to8(auth_str);
}
}
/* harmony default export */ const sasl_oauthbearer = (SASLOAuthBearer);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-plain.js
/**
* @typedef {import("./connection.js").default} Connection
*/
class SASLPlain extends sasl {
/**
* SASL PLAIN authentication.
*/
constructor() {
let mechname = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'PLAIN';
let isClientFirst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
let priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 50;
super(mechname, isClientFirst, priority);
}
/**
* @param {Connection} connection
*/
// eslint-disable-next-line class-methods-use-this
test(connection) {
return connection.authcid !== null;
}
/**
* @param {Connection} connection
*/
// eslint-disable-next-line class-methods-use-this
onChallenge(connection) {
const {
authcid,
authzid,
domain,
pass
} = connection;
if (!domain) {
throw new Error('SASLPlain onChallenge: domain is not defined!');
}
// Only include authzid if it differs from authcid.
// See: https://tools.ietf.org/html/rfc6120#section-6.3.8
let auth_str = authzid !== `${authcid}@${domain}` ? authzid : '';
auth_str = auth_str + '\u0000';
auth_str = auth_str + authcid;
auth_str = auth_str + '\u0000';
auth_str = auth_str + pass;
return utils.utf16to8(auth_str);
}
}
/* harmony default export */ const sasl_plain = (SASLPlain);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/scram.js
/**
* @typedef {import("./connection.js").default} Connection
*/
/**
* @param {string} authMessage
* @param {ArrayBufferLike} clientKey
* @param {string} hashName
*/
async function scramClientProof(authMessage, clientKey, hashName) {
const storedKey = await crypto.subtle.importKey('raw', await crypto.subtle.digest(hashName, clientKey), {
'name': 'HMAC',
'hash': hashName
}, false, ['sign']);
const clientSignature = await crypto.subtle.sign('HMAC', storedKey, utils.stringToArrayBuf(authMessage));
return utils.xorArrayBuffers(clientKey, clientSignature);
}
/**
* This function parses the information in a SASL SCRAM challenge response,
* into an object of the form
* { nonce: String,
* salt: ArrayBuffer,
* iter: Int
* }
* Returns undefined on failure.
* @param {string} challenge
*/
function scramParseChallenge(challenge) {
let nonce, salt, iter;
const attribMatch = /([a-z]+)=([^,]+)(,|$)/;
while (challenge.match(attribMatch)) {
const matches = challenge.match(attribMatch);
challenge = challenge.replace(matches[0], '');
switch (matches[1]) {
case 'r':
nonce = matches[2];
break;
case 's':
salt = utils.base64ToArrayBuf(matches[2]);
break;
case 'i':
iter = parseInt(matches[2], 10);
break;
case 'm':
// Mandatory but unknown extension, per RFC 5802 we should abort
return undefined;
default:
// Non-mandatory extension, per RFC 5802 we should ignore it
break;
}
}
// Consider iteration counts less than 4096 insecure, as reccommended by
// RFC 5802
if (isNaN(iter) || iter < 4096) {
core.warn('Failing SCRAM authentication because server supplied iteration count < 4096.');
return undefined;
}
if (!salt) {
core.warn('Failing SCRAM authentication because server supplied incorrect salt.');
return undefined;
}
return {
'nonce': nonce,
'salt': salt,
'iter': iter
};
}
/**
* Derive the client and server keys given a string password,
* a hash name, and a bit length.
* Returns an object of the following form:
* { ck: ArrayBuffer, the client key
* sk: ArrayBuffer, the server key
* }
* @param {string} password
* @param {BufferSource} salt
* @param {number} iter
* @param {string} hashName
* @param {number} hashBits
*/
async function scramDeriveKeys(password, salt, iter, hashName, hashBits) {
const saltedPasswordBits = await crypto.subtle.deriveBits({
'name': 'PBKDF2',
'salt': salt,
'iterations': iter,
'hash': {
'name': hashName
}
}, await crypto.subtle.importKey('raw', utils.stringToArrayBuf(password), 'PBKDF2', false, ['deriveBits']), hashBits);
const saltedPassword = await crypto.subtle.importKey('raw', saltedPasswordBits, {
'name': 'HMAC',
'hash': hashName
}, false, ['sign']);
return {
'ck': await crypto.subtle.sign('HMAC', saltedPassword, utils.stringToArrayBuf('Client Key')),
'sk': await crypto.subtle.sign('HMAC', saltedPassword, utils.stringToArrayBuf('Server Key'))
};
}
/**
* @param {string} authMessage
* @param {BufferSource} sk
* @param {string} hashName
*/
async function scramServerSign(authMessage, sk, hashName) {
const serverKey = await crypto.subtle.importKey('raw', sk, {
'name': 'HMAC',
'hash': hashName
}, false, ['sign']);
return crypto.subtle.sign('HMAC', serverKey, utils.stringToArrayBuf(authMessage));
}
/**
* Generate an ASCII nonce (not containing the ',' character)
* @return {string}
*/
function generate_cnonce() {
// generate 16 random bytes of nonce, base64 encoded
const bytes = new Uint8Array(16);
return utils.arrayBufToBase64(crypto.getRandomValues(bytes).buffer);
}
/**
* @typedef {Object} Password
* @property {string} Password.name
* @property {string} Password.ck
* @property {string} Password.sk
* @property {number} Password.iter
* @property {string} salt
*/
const scram = {
/**
* On success, sets
* connection_sasl_data["server-signature"]
* and
* connection._sasl_data.keys
*
* The server signature should be verified after this function completes..
*
* On failure, returns connection._sasl_failure_cb();
* @param {Connection} connection
* @param {string} challenge
* @param {string} hashName
* @param {number} hashBits
*/
async scramResponse(connection, challenge, hashName, hashBits) {
const cnonce = connection._sasl_data.cnonce;
const challengeData = scramParseChallenge(challenge);
// The RFC requires that we verify the (server) nonce has the client
// nonce as an initial substring.
if (!challengeData && challengeData?.nonce.slice(0, cnonce.length) !== cnonce) {
core.warn('Failing SCRAM authentication because server supplied incorrect nonce.');
connection._sasl_data = {};
return connection._sasl_failure_cb();
}
let clientKey, serverKey;
const {
pass
} = connection;
if (typeof connection.pass === 'string' || connection.pass instanceof String) {
const keys = await scramDeriveKeys( /** @type {string} */pass, challengeData.salt, challengeData.iter, hashName, hashBits);
clientKey = keys.ck;
serverKey = keys.sk;
} else if (
// Either restore the client key and server key passed in, or derive new ones
/** @type {Password} */
pass?.name === hashName && /** @type {Password} */pass?.salt === utils.arrayBufToBase64(challengeData.salt) && /** @type {Password} */pass?.iter === challengeData.iter) {
const {
ck,
sk
} = /** @type {Password} */pass;
clientKey = utils.base64ToArrayBuf(ck);
serverKey = utils.base64ToArrayBuf(sk);
} else {
return connection._sasl_failure_cb();
}
const clientFirstMessageBare = connection._sasl_data['client-first-message-bare'];
const serverFirstMessage = challenge;
const clientFinalMessageBare = `c=biws,r=${challengeData.nonce}`;
const authMessage = `${clientFirstMessageBare},${serverFirstMessage},${clientFinalMessageBare}`;
const clientProof = await scramClientProof(authMessage, clientKey, hashName);
const serverSignature = await scramServerSign(authMessage, serverKey, hashName);
connection._sasl_data['server-signature'] = utils.arrayBufToBase64(serverSignature);
connection._sasl_data.keys = {
'name': hashName,
'iter': challengeData.iter,
'salt': utils.arrayBufToBase64(challengeData.salt),
'ck': utils.arrayBufToBase64(clientKey),
'sk': utils.arrayBufToBase64(serverKey)
};
return `${clientFinalMessageBare},p=${utils.arrayBufToBase64(clientProof)}`;
},
/**
* Returns a string containing the client first message
* @param {Connection} connection
* @param {string} test_cnonce
*/
clientChallenge(connection, test_cnonce) {
const cnonce = test_cnonce || generate_cnonce();
const client_first_message_bare = `n=${connection.authcid},r=${cnonce}`;
connection._sasl_data.cnonce = cnonce;
connection._sasl_data['client-first-message-bare'] = client_first_message_bare;
return `n,,${client_first_message_bare}`;
}
};
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-sha1.js
/**
* @typedef {import("./connection.js").default} Connection
*/
class SASLSHA1 extends sasl {
/**
* SASL SCRAM SHA 1 authentication.
*/
constructor() {
let mechname = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'SCRAM-SHA-1';
let isClientFirst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
let priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 60;
super(mechname, isClientFirst, priority);
}
/**
* @param {Connection} connection
*/
// eslint-disable-next-line class-methods-use-this
test(connection) {
return connection.authcid !== null;
}
/**
* @param {Connection} connection
* @param {string} [challenge]
* @return {Promise<string|false>} Mechanism response.
*/
// eslint-disable-next-line class-methods-use-this
async onChallenge(connection, challenge) {
return await scram.scramResponse(connection, challenge, 'SHA-1', 160);
}
/**
* @param {Connection} connection
* @param {string} [test_cnonce]
*/
// eslint-disable-next-line class-methods-use-this
clientChallenge(connection, test_cnonce) {
return scram.clientChallenge(connection, test_cnonce);
}
}
/* harmony default export */ const sasl_sha1 = (SASLSHA1);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-sha256.js
/**
* @typedef {import("./connection.js").default} Connection
*/
class SASLSHA256 extends sasl {
/**
* SASL SCRAM SHA 256 authentication.
*/
constructor() {
let mechname = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'SCRAM-SHA-256';
let isClientFirst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
let priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 70;
super(mechname, isClientFirst, priority);
}
/**
* @param {Connection} connection
*/
// eslint-disable-next-line class-methods-use-this
test(connection) {
return connection.authcid !== null;
}
/**
* @param {Connection} connection
* @param {string} [challenge]
*/
// eslint-disable-next-line class-methods-use-this
async onChallenge(connection, challenge) {
return await scram.scramResponse(connection, challenge, 'SHA-256', 256);
}
/**
* @param {Connection} connection
* @param {string} [test_cnonce]
*/
// eslint-disable-next-line class-methods-use-this
clientChallenge(connection, test_cnonce) {
return scram.clientChallenge(connection, test_cnonce);
}
}
/* harmony default export */ const sasl_sha256 = (SASLSHA256);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-sha384.js
/**
* @typedef {import("./connection.js").default} Connection
*/
class SASLSHA384 extends sasl {
/**
* SASL SCRAM SHA 384 authentication.
*/
constructor() {
let mechname = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'SCRAM-SHA-384';
let isClientFirst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
let priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 71;
super(mechname, isClientFirst, priority);
}
/**
* @param {Connection} connection
*/
// eslint-disable-next-line class-methods-use-this
test(connection) {
return connection.authcid !== null;
}
/**
* @param {Connection} connection
* @param {string} [challenge]
*/
// eslint-disable-next-line class-methods-use-this
async onChallenge(connection, challenge) {
return await scram.scramResponse(connection, challenge, 'SHA-384', 384);
}
/**
* @param {Connection} connection
* @param {string} [test_cnonce]
*/
// eslint-disable-next-line class-methods-use-this
clientChallenge(connection, test_cnonce) {
return scram.clientChallenge(connection, test_cnonce);
}
}
/* harmony default export */ const sasl_sha384 = (SASLSHA384);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-sha512.js
/**
* @typedef {import("./connection.js").default} Connection
*/
class SASLSHA512 extends sasl {
/**
* SASL SCRAM SHA 512 authentication.
*/
constructor() {
let mechname = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'SCRAM-SHA-512';
let isClientFirst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
let priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 72;
super(mechname, isClientFirst, priority);
}
/**
* @param {Connection} connection
*/
// eslint-disable-next-line class-methods-use-this
test(connection) {
return connection.authcid !== null;
}
/**
* @param {Connection} connection
* @param {string} [challenge]
*/
// eslint-disable-next-line class-methods-use-this
async onChallenge(connection, challenge) {
return await scram.scramResponse(connection, challenge, 'SHA-512', 512);
}
/**
* @param {Connection} connection
* @param {string} [test_cnonce]
*/
// eslint-disable-next-line class-methods-use-this
clientChallenge(connection, test_cnonce) {
return scram.clientChallenge(connection, test_cnonce);
}
}
/* harmony default export */ const sasl_sha512 = (SASLSHA512);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/sasl-xoauth2.js
/**
* @typedef {import("./connection.js").default} Connection
*/
class SASLXOAuth2 extends sasl {
/**
* SASL X-OAuth2 authentication.
*/
constructor() {
let mechname = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'X-OAUTH2';
let isClientFirst = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
let priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 30;
super(mechname, isClientFirst, priority);
}
/**
* @param {Connection} connection
*/
// eslint-disable-next-line class-methods-use-this
test(connection) {
return connection.pass !== null;
}
/**
* @param {Connection} connection
*/
// eslint-disable-next-line class-methods-use-this
onChallenge(connection) {
let auth_str = '\u0000';
if (connection.authcid !== null) {
auth_str = auth_str + connection.authzid;
}
auth_str = auth_str + '\u0000';
auth_str = auth_str + connection.pass;
return utils.utf16to8(auth_str);
}
}
/* harmony default export */ const sasl_xoauth2 = (SASLXOAuth2);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/request.js
/**
* Helper class that provides a cross implementation abstraction
* for a BOSH related XMLHttpRequest.
*
* The Strophe.Request class is used internally to encapsulate BOSH request
* information. It is not meant to be used from user's code.
*
* @property {number} id
* @property {number} sends
* @property {XMLHttpRequest} xhr
*/
class Request {
/**
* Create and initialize a new Strophe.Request object.
*
* @param {Element} elem - The XML data to be sent in the request.
* @param {Function} func - The function that will be called when the
* XMLHttpRequest readyState changes.
* @param {number} rid - The BOSH rid attribute associated with this request.
* @param {number} [sends=0] - The number of times this same request has been sent.
*/
constructor(elem, func, rid) {
let sends = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
this.id = ++core._requestId;
this.xmlData = elem;
this.data = core.serialize(elem);
// save original function in case we need to make a new request
// from this one.
this.origFunc = func;
this.func = func;
this.rid = rid;
this.date = NaN;
this.sends = sends;
this.abort = false;
this.dead = null;
this.age = () => this.date ? (new Date().valueOf() - this.date.valueOf()) / 1000 : 0;
this.timeDead = () => this.dead ? (new Date().valueOf() - this.dead.valueOf()) / 1000 : 0;
this.xhr = this._newXHR();
}
/**
* Get a response from the underlying XMLHttpRequest.
* This function attempts to get a response from the request and checks
* for errors.
* @throws "parsererror" - A parser error occured.
* @throws "bad-format" - The entity has sent XML that cannot be processed.
* @return {Element} - The DOM element tree of the response.
*/
getResponse() {
let node = this.xhr.responseXML?.documentElement;
if (node) {
if (node.tagName === 'parsererror') {
core.error('invalid response received');
core.error('responseText: ' + this.xhr.responseText);
core.error('responseXML: ' + core.serialize(node));
throw new Error('parsererror');
}
} else if (this.xhr.responseText) {
// In Node (with xhr2) or React Native, we may get responseText but no responseXML.
// We can try to parse it manually.
core.debug('Got responseText but no responseXML; attempting to parse it with DOMParser...');
node = new DOMParser().parseFromString(this.xhr.responseText, 'application/xml').documentElement;
const parserError = node?.querySelector('parsererror');
if (!node || parserError) {
if (parserError) {
core.error('invalid response received: ' + parserError.textContent);
core.error('responseText: ' + this.xhr.responseText);
}
const error = new Error();
error.name = core.ErrorCondition.BAD_FORMAT;
throw error;
}
}
return node;
}
/**
* _Private_ helper function to create XMLHttpRequests.
* This function creates XMLHttpRequests across all implementations.
* @private
* @return {XMLHttpRequest}
*/
_newXHR() {
const xhr = new XMLHttpRequest();
if (xhr.overrideMimeType) {
xhr.overrideMimeType('text/xml; charset=utf-8');
}
// use Function.bind() to prepend ourselves as an argument
xhr.onreadystatechange = this.func.bind(null, this);
return xhr;
}
}
/* harmony default export */ const request = (Request);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/bosh.js
/**
* A JavaScript library to enable BOSH in Strophejs.
*
* this library uses Bidirectional-streams Over Synchronous HTTP (BOSH)
* to emulate a persistent, stateful, two-way connection to an XMPP server.
* More information on BOSH can be found in XEP 124.
*/
/**
* @typedef {import("./connection.js").default} Connection
* @typedef {import("./request.js").default} Request
*/
/**
* _Private_ helper class that handles BOSH Connections
* The Strophe.Bosh class is used internally by Strophe.Connection
* to encapsulate BOSH sessions. It is not meant to be used from user's code.
*/
class Bosh {
/**
* @param {Connection} connection - The Strophe.Connection that will use BOSH.
*/
constructor(connection) {
this._conn = connection;
/* request id for body tags */
this.rid = Math.floor(Math.random() * 4294967295);
/* The current session ID. */
this.sid = null;
// default BOSH values
this.hold = 1;
this.wait = 60;
this.window = 5;
this.errors = 0;
this.inactivity = null;
/**
* BOSH-Connections will have all stanzas wrapped in a <body> tag when
* passed to {@link Strophe.Connection#xmlInput|xmlInput()} or {@link Strophe.Connection#xmlOutput|xmlOutput()}.
* To strip this tag, User code can set {@link Strophe.Bosh#strip|strip} to `true`:
*
* > // You can set `strip` on the prototype
* > Strophe.Bosh.prototype.strip = true;
*
* > // Or you can set it on the Bosh instance (which is `._proto` on the connection instance.
* > const conn = new Strophe.Connection();
* > conn._proto.strip = true;
*
* This will enable stripping of the body tag in both
* {@link Strophe.Connection#xmlInput|xmlInput} and {@link Strophe.Connection#xmlOutput|xmlOutput}.
*
* @property {boolean} [strip=false]
*/
this.strip = Bosh.prototype.strip ?? false;
this.lastResponseHeaders = null;
/** @type {Request[]} */
this._requests = [];
}
/**
* _Private_ helper function to generate the <body/> wrapper for BOSH.
* @private
* @return {Builder} - A Strophe.Builder with a <body/> element.
*/
_buildBody() {
const bodyWrap = $build('body', {
'rid': this.rid++,
'xmlns': core.NS.HTTPBIND
});
if (this.sid !== null) {
bodyWrap.attrs({
'sid': this.sid
});
}
if (this._conn.options.keepalive && this._conn._sessionCachingSupported()) {
this._cacheSession();
}
return bodyWrap;
}
/**
* Reset the connection.
* This function is called by the reset function of the Strophe Connection
*/
_reset() {
this.rid = Math.floor(Math.random() * 4294967295);
this.sid = null;
this.errors = 0;
if (this._conn._sessionCachingSupported()) {
sessionStorage.removeItem('strophe-bosh-session');
}
this._conn.nextValidRid(this.rid);
}
/**
* _Private_ function that initializes the BOSH connection.
* Creates and sends the Request that initializes the BOSH connection.
* @param {number} wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* Other settings will require tweaks to the Strophe.TIMEOUT value.
* @param {number} hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* @param {string} route
*/
_connect(wait, hold, route) {
this.wait = wait || this.wait;
this.hold = hold || this.hold;
this.errors = 0;
const body = this._buildBody().attrs({
'to': this._conn.domain,
'xml:lang': 'en',
'wait': this.wait,
'hold': this.hold,
'content': 'text/xml; charset=utf-8',
'ver': '1.6',
'xmpp:version': '1.0',
'xmlns:xmpp': core.NS.BOSH
});
if (route) {
body.attrs({
route
});
}
const _connect_cb = this._conn._connect_cb;
this._requests.push(new core.Request(body.tree(), this._onRequestStateChange.bind(this, _connect_cb.bind(this._conn)), Number(body.tree().getAttribute('rid'))));
this._throttledRequestHandler();
}
/**
* Attach to an already created and authenticated BOSH session.
*
* This function is provided to allow Strophe to attach to BOSH
* sessions which have been created externally, perhaps by a Web
* application. This is often used to support auto-login type features
* without putting user credentials into the page.
*
* @param {string} jid - The full JID that is bound by the session.
* @param {string} sid - The SID of the BOSH session.
* @param {number} rid - The current RID of the BOSH session. This RID
* will be used by the next request.
* @param {Function} callback The connect callback function.
* @param {number} wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* Other settings will require tweaks to the Strophe.TIMEOUT value.
* @param {number} hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* @param {number} wind - The optional HTTBIND window value. This is the
* allowed range of request ids that are valid. The default is 5.
*/
_attach(jid, sid, rid, callback, wait, hold, wind) {
this._conn.jid = jid;
this.sid = sid;
this.rid = rid;
this._conn.connect_callback = callback;
this._conn.domain = core.getDomainFromJid(this._conn.jid);
this._conn.authenticated = true;
this._conn.connected = true;
this.wait = wait || this.wait;
this.hold = hold || this.hold;
this.window = wind || this.window;
this._conn._changeConnectStatus(core.Status.ATTACHED, null);
}
/**
* Attempt to restore a cached BOSH session
*
* @param {string} jid - The full JID that is bound by the session.
* This parameter is optional but recommended, specifically in cases
* where prebinded BOSH sessions are used where it's important to know
* that the right session is being restored.
* @param {Function} callback The connect callback function.
* @param {number} wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* Other settings will require tweaks to the Strophe.TIMEOUT value.
* @param {number} hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* @param {number} wind - The optional HTTBIND window value. This is the
* allowed range of request ids that are valid. The default is 5.
*/
_restore(jid, callback, wait, hold, wind) {
const session = JSON.parse(sessionStorage.getItem('strophe-bosh-session'));
if (typeof session !== 'undefined' && session !== null && session.rid && session.sid && session.jid && (typeof jid === 'undefined' || jid === null || core.getBareJidFromJid(session.jid) === core.getBareJidFromJid(jid) ||
// If authcid is null, then it's an anonymous login, so
// we compare only the domains:
core.getNodeFromJid(jid) === null && core.getDomainFromJid(session.jid) === jid)) {
this._conn.restored = true;
this._attach(session.jid, session.sid, session.rid, callback, wait, hold, wind);
} else {
const error = new Error('_restore: no restoreable session.');
error.name = 'StropheSessionError';
throw error;
}
}
/**
* _Private_ handler for the beforeunload event.
* This handler is used to process the Bosh-part of the initial request.
* @private
*/
_cacheSession() {
if (this._conn.authenticated) {
if (this._conn.jid && this.rid && this.sid) {
sessionStorage.setItem('strophe-bosh-session', JSON.stringify({
'jid': this._conn.jid,
'rid': this.rid,
'sid': this.sid
}));
}
} else {
sessionStorage.removeItem('strophe-bosh-session');
}
}
/**
* _Private_ handler for initial connection request.
* This handler is used to process the Bosh-part of the initial request.
* @param {Element} bodyWrap - The received stanza.
*/
_connect_cb(bodyWrap) {
const typ = bodyWrap.getAttribute('type');
if (typ !== null && typ === 'terminate') {
// an error occurred
let cond = bodyWrap.getAttribute('condition');
core.error('BOSH-Connection failed: ' + cond);
const conflict = bodyWrap.getElementsByTagName('conflict');
if (cond !== null) {
if (cond === 'remote-stream-error' && conflict.length > 0) {
cond = 'conflict';
}
this._conn._changeConnectStatus(core.Status.CONNFAIL, cond);
} else {
this._conn._changeConnectStatus(core.Status.CONNFAIL, 'unknown');
}
this._conn._doDisconnect(cond);
return core.Status.CONNFAIL;
}
// check to make sure we don't overwrite these if _connect_cb is
// called multiple times in the case of missing stream:features
if (!this.sid) {
this.sid = bodyWrap.getAttribute('sid');
}
const wind = bodyWrap.getAttribute('requests');
if (wind) {
this.window = parseInt(wind, 10);
}
const hold = bodyWrap.getAttribute('hold');
if (hold) {
this.hold = parseInt(hold, 10);
}
const wait = bodyWrap.getAttribute('wait');
if (wait) {
this.wait = parseInt(wait, 10);
}
const inactivity = bodyWrap.getAttribute('inactivity');
if (inactivity) {
this.inactivity = parseInt(inactivity, 10);
}
}
/**
* _Private_ part of Connection.disconnect for Bosh
* @param {Element|Builder} pres - This stanza will be sent before disconnecting.
*/
_disconnect(pres) {
this._sendTerminate(pres);
}
/**
* _Private_ function to disconnect.
* Resets the SID and RID.
*/
_doDisconnect() {
this.sid = null;
this.rid = Math.floor(Math.random() * 4294967295);
if (this._conn._sessionCachingSupported()) {
sessionStorage.removeItem('strophe-bosh-session');
}
this._conn.nextValidRid(this.rid);
}
/**
* _Private_ function to check if the Request queue is empty.
* @return {boolean} - True, if there are no Requests queued, False otherwise.
*/
_emptyQueue() {
return this._requests.length === 0;
}
/**
* _Private_ function to call error handlers registered for HTTP errors.
* @private
* @param {Request} req - The request that is changing readyState.
*/
_callProtocolErrorHandlers(req) {
const reqStatus = Bosh._getRequestStatus(req);
const err_callback = this._conn.protocolErrorHandlers.HTTP[reqStatus];
if (err_callback) {
err_callback.call(this, reqStatus);
}
}
/**
* _Private_ function to handle the error count.
*
* Requests are resent automatically until their error count reaches
* 5. Each time an error is encountered, this function is called to
* increment the count and disconnect if the count is too high.
* @private
* @param {number} reqStatus - The request status.
*/
_hitError(reqStatus) {
this.errors++;
core.warn('request errored, status: ' + reqStatus + ', number of errors: ' + this.errors);
if (this.errors > 4) {
this._conn._onDisconnectTimeout();
}
}
/**
* @callback connectionCallback
* @param {Connection} connection
*/
/**
* Called on stream start/restart when no stream:features
* has been received and sends a blank poll request.
* @param {connectionCallback} callback
*/
_no_auth_received(callback) {
core.warn('Server did not yet offer a supported authentication ' + 'mechanism. Sending a blank poll request.');
if (callback) {
callback = callback.bind(this._conn);
} else {
callback = this._conn._connect_cb.bind(this._conn);
}
const body = this._buildBody();
this._requests.push(new core.Request(body.tree(), this._onRequestStateChange.bind(this, callback), Number(body.tree().getAttribute('rid'))));
this._throttledRequestHandler();
}
/**
* _Private_ timeout handler for handling non-graceful disconnection.
* Cancels all remaining Requests and clears the queue.
*/
_onDisconnectTimeout() {
this._abortAllRequests();
}
/**
* _Private_ helper function that makes sure all pending requests are aborted.
*/
_abortAllRequests() {
while (this._requests.length > 0) {
const req = this._requests.pop();
req.abort = true;
req.xhr.abort();
req.xhr.onreadystatechange = function () {};
}
}
/**
* _Private_ handler called by {@link Strophe.Connection#_onIdle|Strophe.Connection._onIdle()}.
* Sends all queued Requests or polls with empty Request if there are none.
*/
_onIdle() {
const data = this._conn._data;
// if no requests are in progress, poll
if (this._conn.authenticated && this._requests.length === 0 && data.length === 0 && !this._conn.disconnecting) {
core.debug('no requests during idle cycle, sending blank request');
data.push(null);
}
if (this._conn.paused) {
return;
}
if (this._requests.length < 2 && data.length > 0) {
const body = this._buildBody();
for (let i = 0; i < data.length; i++) {
if (data[i] !== null) {
if (data[i] === 'restart') {
body.attrs({
'to': this._conn.domain,
'xml:lang': 'en',
'xmpp:restart': 'true',
'xmlns:xmpp': core.NS.BOSH
});
} else {
body.cnode( /** @type {Element} */data[i]).up();
}
}
}
delete this._conn._data;
this._conn._data = [];
this._requests.push(new core.Request(body.tree(), this._onRequestStateChange.bind(this, this._conn._dataRecv.bind(this._conn)), Number(body.tree().getAttribute('rid'))));
this._throttledRequestHandler();
}
if (this._requests.length > 0) {
const time_elapsed = this._requests[0].age();
if (this._requests[0].dead !== null) {
if (this._requests[0].timeDead() > Math.floor(core.SECONDARY_TIMEOUT * this.wait)) {
this._throttledRequestHandler();
}
}
if (time_elapsed > Math.floor(core.TIMEOUT * this.wait)) {
core.warn('Request ' + this._requests[0].id + ' timed out, over ' + Math.floor(core.TIMEOUT * this.wait) + ' seconds since last activity');
this._throttledRequestHandler();
}
}
}
/**
* Returns the HTTP status code from a {@link Strophe.Request}
* @private
* @param {Request} req - The {@link Strophe.Request} instance.
* @param {number} [def] - The default value that should be returned if no status value was found.
*/
static _getRequestStatus(req, def) {
let reqStatus;
if (req.xhr.readyState === 4) {
try {
reqStatus = req.xhr.status;
} catch (e) {
// ignore errors from undefined status attribute. Works
// around a browser bug
core.error("Caught an error while retrieving a request's status, " + 'reqStatus: ' + reqStatus);
}
}
if (typeof reqStatus === 'undefined') {
reqStatus = typeof def === 'number' ? def : 0;
}
return reqStatus;
}
/**
* _Private_ handler for {@link Strophe.Request} state changes.
*
* This function is called when the XMLHttpRequest readyState changes.
* It contains a lot of error handling logic for the many ways that
* requests can fail, and calls the request callback when requests
* succeed.
* @private
*
* @param {Function} func - The handler for the request.
* @param {Request} req - The request that is changing readyState.
*/
_onRequestStateChange(func, req) {
core.debug('request id ' + req.id + '.' + req.sends + ' state changed to ' + req.xhr.readyState);
if (req.abort) {
req.abort = false;
return;
}
if (req.xhr.readyState !== 4) {
// The request is not yet complete
return;
}
const reqStatus = Bosh._getRequestStatus(req);
this.lastResponseHeaders = req.xhr.getAllResponseHeaders();
if (this._conn.disconnecting && reqStatus >= 400) {
this._hitError(reqStatus);
this._callProtocolErrorHandlers(req);
return;
}
const reqIs0 = this._requests[0] === req;
const reqIs1 = this._requests[1] === req;
const valid_request = reqStatus > 0 && reqStatus < 500;
const too_many_retries = req.sends > this._conn.maxRetries;
if (valid_request || too_many_retries) {
// remove from internal queue
this._removeRequest(req);
core.debug('request id ' + req.id + ' should now be removed');
}
if (reqStatus === 200) {
// request succeeded
// if request 1 finished, or request 0 finished and request
// 1 is over Strophe.SECONDARY_TIMEOUT seconds old, we need to
// restart the other - both will be in the first spot, as the
// completed request has been removed from the queue already
if (reqIs1 || reqIs0 && this._requests.length > 0 && this._requests[0].age() > Math.floor(core.SECONDARY_TIMEOUT * this.wait)) {
this._restartRequest(0);
}
this._conn.nextValidRid(req.rid + 1);
core.debug('request id ' + req.id + '.' + req.sends + ' got 200');
func(req); // call handler
this.errors = 0;
} else if (reqStatus === 0 || reqStatus >= 400 && reqStatus < 600 || reqStatus >= 12000) {
// request failed
core.error('request id ' + req.id + '.' + req.sends + ' error ' + reqStatus + ' happened');
this._hitError(reqStatus);
this._callProtocolErrorHandlers(req);
if (reqStatus >= 400 && reqStatus < 500) {
this._conn._changeConnectStatus(core.Status.DISCONNECTING, null);
this._conn._doDisconnect();
}
} else {
core.error('request id ' + req.id + '.' + req.sends + ' error ' + reqStatus + ' happened');
}
if (!valid_request && !too_many_retries) {
this._throttledRequestHandler();
} else if (too_many_retries && !this._conn.connected) {
this._conn._changeConnectStatus(core.Status.CONNFAIL, 'giving-up');
}
}
/**
* _Private_ function to process a request in the queue.
*
* This function takes requests off the queue and sends them and
* restarts dead requests.
* @private
*
* @param {number} i - The index of the request in the queue.
*/
_processRequest(i) {
let req = this._requests[i];
const reqStatus = Bosh._getRequestStatus(req, -1);
// make sure we limit the number of retries
if (req.sends > this._conn.maxRetries) {
this._conn._onDisconnectTimeout();
return;
}
const time_elapsed = req.age();
const primary_timeout = !isNaN(time_elapsed) && time_elapsed > Math.floor(core.TIMEOUT * this.wait);
const secondary_timeout = req.dead !== null && req.timeDead() > Math.floor(core.SECONDARY_TIMEOUT * this.wait);
const server_error = req.xhr.readyState === 4 && (reqStatus < 1 || reqStatus >= 500);
if (primary_timeout || secondary_timeout || server_error) {
if (secondary_timeout) {
core.error(`Request ${this._requests[i].id} timed out (secondary), restarting`);
}
req.abort = true;
req.xhr.abort();
// setting to null fails on IE6, so set to empty function
req.xhr.onreadystatechange = function () {};
this._requests[i] = new core.Request(req.xmlData, req.origFunc, req.rid, req.sends);
req = this._requests[i];
}
if (req.xhr.readyState === 0) {
core.debug('request id ' + req.id + '.' + req.sends + ' posting');
try {
const content_type = this._conn.options.contentType || 'text/xml; charset=utf-8';
req.xhr.open('POST', this._conn.service, this._conn.options.sync ? false : true);
if (typeof req.xhr.setRequestHeader !== 'undefined') {
// IE9 doesn't have setRequestHeader
req.xhr.setRequestHeader('Content-Type', content_type);
}
if (this._conn.options.withCredentials) {
req.xhr.withCredentials = true;
}
} catch (e2) {
core.error('XHR open failed: ' + e2.toString());
if (!this._conn.connected) {
this._conn._changeConnectStatus(core.Status.CONNFAIL, 'bad-service');
}
this._conn.disconnect();
return;
}
// Fires the XHR request -- may be invoked immediately
// or on a gradually expanding retry window for reconnects
const sendFunc = () => {
req.date = new Date().valueOf();
if (this._conn.options.customHeaders) {
const headers = this._conn.options.customHeaders;
for (const header in headers) {
if (Object.prototype.hasOwnProperty.call(headers, header)) {
req.xhr.setRequestHeader(header, headers[header]);
}
}
}
req.xhr.send(req.data);
};
// Implement progressive backoff for reconnects --
// First retry (send === 1) should also be instantaneous
if (req.sends > 1) {
// Using a cube of the retry number creates a nicely
// expanding retry window
const backoff = Math.min(Math.floor(core.TIMEOUT * this.wait), Math.pow(req.sends, 3)) * 1000;
setTimeout(function () {
// XXX: setTimeout should be called only with function expressions (23974bc1)
sendFunc();
}, backoff);
} else {
sendFunc();
}
req.sends++;
if (this.strip && req.xmlData.nodeName === 'body' && req.xmlData.childNodes.length) {
this._conn.xmlOutput?.(req.xmlData.children[0]);
} else {
this._conn.xmlOutput?.(req.xmlData);
}
this._conn.rawOutput?.(req.data);
} else {
core.debug('_processRequest: ' + (i === 0 ? 'first' : 'second') + ' request has readyState of ' + req.xhr.readyState);
}
}
/**
* _Private_ function to remove a request from the queue.
* @private
* @param {Request} req - The request to remove.
*/
_removeRequest(req) {
core.debug('removing request');
for (let i = this._requests.length - 1; i >= 0; i--) {
if (req === this._requests[i]) {
this._requests.splice(i, 1);
}
}
// IE6 fails on setting to null, so set to empty function
req.xhr.onreadystatechange = function () {};
this._throttledRequestHandler();
}
/**
* _Private_ function to restart a request that is presumed dead.
* @private
*
* @param {number} i - The index of the request in the queue.
*/
_restartRequest(i) {
const req = this._requests[i];
if (req.dead === null) {
req.dead = new Date();
}
this._processRequest(i);
}
/**
* _Private_ function to get a stanza out of a request.
* Tries to extract a stanza out of a Request Object.
* When this fails the current connection will be disconnected.
*
* @param {Request} req - The Request.
* @return {Element} - The stanza that was passed.
*/
_reqToData(req) {
try {
return req.getResponse();
} catch (e) {
if (e.message !== 'parsererror') {
throw e;
}
this._conn.disconnect('strophe-parsererror');
}
}
/**
* _Private_ function to send initial disconnect sequence.
*
* This is the first step in a graceful disconnect. It sends
* the BOSH server a terminate body and includes an unavailable
* presence if authentication has completed.
* @private
* @param {Element|Builder} [pres]
*/
_sendTerminate(pres) {
core.debug('_sendTerminate was called');
const body = this._buildBody().attrs({
type: 'terminate'
});
const el = pres instanceof builder ? pres.tree() : pres;
if (pres) {
body.cnode(el);
}
const req = new core.Request(body.tree(), this._onRequestStateChange.bind(this, this._conn._dataRecv.bind(this._conn)), Number(body.tree().getAttribute('rid')));
this._requests.push(req);
this._throttledRequestHandler();
}
/**
* _Private_ part of the Connection.send function for BOSH
* Just triggers the RequestHandler to send the messages that are in the queue
*/
_send() {
clearTimeout(this._conn._idleTimeout);
this._throttledRequestHandler();
this._conn._idleTimeout = setTimeout(() => this._conn._onIdle(), 100);
}
/**
* Send an xmpp:restart stanza.
*/
_sendRestart() {
this._throttledRequestHandler();
clearTimeout(this._conn._idleTimeout);
}
/**
* _Private_ function to throttle requests to the connection window.
*
* This function makes sure we don't send requests so fast that the
* request ids overflow the connection window in the case that one
* request died.
* @private
*/
_throttledRequestHandler() {
if (!this._requests) {
core.debug('_throttledRequestHandler called with ' + 'undefined requests');
} else {
core.debug('_throttledRequestHandler called with ' + this._requests.length + ' requests');
}
if (!this._requests || this._requests.length === 0) {
return;
}
if (this._requests.length > 0) {
this._processRequest(0);
}
if (this._requests.length > 1 && Math.abs(this._requests[0].rid - this._requests[1].rid) < this.window) {
this._processRequest(1);
}
}
}
/* harmony default export */ const bosh = (Bosh);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/websocket.js
/**
* A JavaScript library to enable XMPP over Websocket in Strophejs.
*
* This file implements XMPP over WebSockets for Strophejs.
* If a Connection is established with a Websocket url (ws://...)
* Strophe will use WebSockets.
* For more information on XMPP-over-WebSocket see RFC 7395:
* http://tools.ietf.org/html/rfc7395
*
* WebSocket support implemented by Andreas Guth (andreas.guth@rwth-aachen.de)
*/
/* global clearTimeout, location */
/**
* @typedef {import("./builder.js").default} Builder
* @typedef {import("./connection.js").default} Connection
*/
/**
* Helper class that handles WebSocket Connections
*
* The Strophe.WebSocket class is used internally by Strophe.Connection
* to encapsulate WebSocket sessions. It is not meant to be used from user's code.
*/
class Websocket {
/**
* Create and initialize a Strophe.WebSocket object.
* Currently only sets the connection Object.
* @param {Connection} connection - The Strophe.Connection that will use WebSockets.
*/
constructor(connection) {
this._conn = connection;
this.strip = 'wrapper';
const service = connection.service;
if (service.indexOf('ws:') !== 0 && service.indexOf('wss:') !== 0) {
// If the service is not an absolute URL, assume it is a path and put the absolute
// URL together from options, current URL and the path.
let new_service = '';
if (connection.options.protocol === 'ws' && location.protocol !== 'https:') {
new_service += 'ws';
} else {
new_service += 'wss';
}
new_service += '://' + location.host;
if (service.indexOf('/') !== 0) {
new_service += location.pathname + service;
} else {
new_service += service;
}
connection.service = new_service;
}
}
/**
* _Private_ helper function to generate the <stream> start tag for WebSockets
* @private
* @return {Builder} - A Strophe.Builder with a <stream> element.
*/
_buildStream() {
return $build('open', {
'xmlns': core.NS.FRAMING,
'to': this._conn.domain,
'version': '1.0'
});
}
/**
* _Private_ checks a message for stream:error
* @private
* @param {Element} bodyWrap - The received stanza.
* @param {number} connectstatus - The ConnectStatus that will be set on error.
* @return {boolean} - true if there was a streamerror, false otherwise.
*/
_checkStreamError(bodyWrap, connectstatus) {
let errors;
if (bodyWrap.getElementsByTagNameNS) {
errors = bodyWrap.getElementsByTagNameNS(core.NS.STREAM, 'error');
} else {
errors = bodyWrap.getElementsByTagName('stream:error');
}
if (errors.length === 0) {
return false;
}
const error = errors[0];
let condition = '';
let text = '';
const ns = 'urn:ietf:params:xml:ns:xmpp-streams';
for (let i = 0; i < error.childNodes.length; i++) {
const e = error.children[i];
if (e.getAttribute('xmlns') !== ns) {
break;
}
if (e.nodeName === 'text') {
text = e.textContent;
} else {
condition = e.nodeName;
}
}
let errorString = 'WebSocket stream error: ';
if (condition) {
errorString += condition;
} else {
errorString += 'unknown';
}
if (text) {
errorString += ' - ' + text;
}
core.error(errorString);
// close the connection on stream_error
this._conn._changeConnectStatus(connectstatus, condition);
this._conn._doDisconnect();
return true;
}
/**
* Reset the connection.
*
* This function is called by the reset function of the Strophe Connection.
* Is not needed by WebSockets.
*/
// eslint-disable-next-line class-methods-use-this
_reset() {
return;
}
/**
* _Private_ function called by Strophe.Connection.connect
*
* Creates a WebSocket for a connection and assigns Callbacks to it.
* Does nothing if there already is a WebSocket.
*/
_connect() {
// Ensure that there is no open WebSocket from a previous Connection.
this._closeSocket();
/**
* @typedef {Object} WebsocketLike
* @property {(str: string) => void} WebsocketLike.send
* @property {function(): void} WebsocketLike.close
* @property {function(): void} WebsocketLike.onopen
* @property {(e: ErrorEvent) => void} WebsocketLike.onerror
* @property {(e: CloseEvent) => void} WebsocketLike.onclose
* @property {(message: MessageEvent) => void} WebsocketLike.onmessage
* @property {string} WebsocketLike.readyState
*/
/** @type {import('ws')|WebSocket|WebsocketLike} */
this.socket = new WebSocket(this._conn.service, 'xmpp');
this.socket.onopen = () => this._onOpen();
/** @param {ErrorEvent} e */
this.socket.onerror = e => this._onError(e);
/** @param {CloseEvent} e */
this.socket.onclose = e => this._onClose(e);
/**
* Gets replaced with this._onMessage once _onInitialMessage is called
* @param {MessageEvent} message
*/
this.socket.onmessage = message => this._onInitialMessage(message);
}
/**
* _Private_ function called by Strophe.Connection._connect_cb
* checks for stream:error
* @param {Element} bodyWrap - The received stanza.
*/
_connect_cb(bodyWrap) {
const error = this._checkStreamError(bodyWrap, core.Status.CONNFAIL);
if (error) {
return core.Status.CONNFAIL;
}
}
/**
* _Private_ function that checks the opening <open /> tag for errors.
*
* Disconnects if there is an error and returns false, true otherwise.
* @private
* @param {Element} message - Stanza containing the <open /> tag.
*/
_handleStreamStart(message) {
let error = null;
// Check for errors in the <open /> tag
const ns = message.getAttribute('xmlns');
if (typeof ns !== 'string') {
error = 'Missing xmlns in <open />';
} else if (ns !== core.NS.FRAMING) {
error = 'Wrong xmlns in <open />: ' + ns;
}
const ver = message.getAttribute('version');
if (typeof ver !== 'string') {
error = 'Missing version in <open />';
} else if (ver !== '1.0') {
error = 'Wrong version in <open />: ' + ver;
}
if (error) {
this._conn._changeConnectStatus(core.Status.CONNFAIL, error);
this._conn._doDisconnect();
return false;
}
return true;
}
/**
* _Private_ function that handles the first connection messages.
*
* On receiving an opening stream tag this callback replaces itself with the real
* message handler. On receiving a stream error the connection is terminated.
* @param {MessageEvent} message
*/
_onInitialMessage(message) {
if (message.data.indexOf('<open ') === 0 || message.data.indexOf('<?xml') === 0) {
// Strip the XML Declaration, if there is one
const data = message.data.replace(/^(<\?.*?\?>\s*)*/, '');
if (data === '') return;
const streamStart = new DOMParser().parseFromString(data, 'text/xml').documentElement;
this._conn.xmlInput(streamStart);
this._conn.rawInput(message.data);
//_handleStreamSteart will check for XML errors and disconnect on error
if (this._handleStreamStart(streamStart)) {
//_connect_cb will check for stream:error and disconnect on error
this._connect_cb(streamStart);
}
} else if (message.data.indexOf('<close ') === 0) {
// <close xmlns="urn:ietf:params:xml:ns:xmpp-framing />
// Parse the raw string to an XML element
const parsedMessage = new DOMParser().parseFromString(message.data, 'text/xml').documentElement;
// Report this input to the raw and xml handlers
this._conn.xmlInput(parsedMessage);
this._conn.rawInput(message.data);
const see_uri = parsedMessage.getAttribute('see-other-uri');
if (see_uri) {
const service = this._conn.service;
// Valid scenarios: WSS->WSS, WS->ANY
const isSecureRedirect = service.indexOf('wss:') >= 0 && see_uri.indexOf('wss:') >= 0 || service.indexOf('ws:') >= 0;
if (isSecureRedirect) {
this._conn._changeConnectStatus(core.Status.REDIRECT, 'Received see-other-uri, resetting connection');
this._conn.reset();
this._conn.service = see_uri;
this._connect();
}
} else {
this._conn._changeConnectStatus(core.Status.CONNFAIL, 'Received closing stream');
this._conn._doDisconnect();
}
} else {
this._replaceMessageHandler();
const string = this._streamWrap(message.data);
const elem = new DOMParser().parseFromString(string, 'text/xml').documentElement;
this._conn._connect_cb(elem, null, message.data);
}
}
/**
* Called by _onInitialMessage in order to replace itself with the general message handler.
* This method is overridden by Strophe.WorkerWebsocket, which manages a
* websocket connection via a service worker and doesn't have direct access
* to the socket.
*/
_replaceMessageHandler() {
/** @param {MessageEvent} m */
this.socket.onmessage = m => this._onMessage(m);
}
/**
* _Private_ function called by Strophe.Connection.disconnect
* Disconnects and sends a last stanza if one is given
* @param {Element|Builder} [pres] - This stanza will be sent before disconnecting.
*/
_disconnect(pres) {
if (this.socket && this.socket.readyState !== WebSocket.CLOSED) {
if (pres) {
this._conn.send(pres);
}
const close = $build('close', {
'xmlns': core.NS.FRAMING
});
this._conn.xmlOutput(close.tree());
const closeString = core.serialize(close);
this._conn.rawOutput(closeString);
try {
this.socket.send(closeString);
} catch (e) {
core.warn("Couldn't send <close /> tag.");
}
}
setTimeout(() => this._conn._doDisconnect(), 0);
}
/**
* _Private_ function to disconnect.
* Just closes the Socket for WebSockets
*/
_doDisconnect() {
core.debug('WebSockets _doDisconnect was called');
this._closeSocket();
}
/**
* PrivateFunction _streamWrap
* _Private_ helper function to wrap a stanza in a <stream> tag.
* This is used so Strophe can process stanzas from WebSockets like BOSH
* @param {string} stanza
*/
// eslint-disable-next-line class-methods-use-this
_streamWrap(stanza) {
return '<wrapper>' + stanza + '</wrapper>';
}
/**
* _Private_ function to close the WebSocket.
*
* Closes the socket if it is still open and deletes it
*/
_closeSocket() {
if (this.socket) {
try {
this.socket.onclose = null;
this.socket.onerror = null;
this.socket.onmessage = null;
this.socket.close();
} catch (e) {
core.debug(e.message);
}
}
this.socket = null;
}
/**
* _Private_ function to check if the message queue is empty.
* @return {true} - True, because WebSocket messages are send immediately after queueing.
*/
// eslint-disable-next-line class-methods-use-this
_emptyQueue() {
return true;
}
/**
* _Private_ function to handle websockets closing.
* @param {CloseEvent} [e]
*/
_onClose(e) {
if (this._conn.connected && !this._conn.disconnecting) {
core.error('Websocket closed unexpectedly');
this._conn._doDisconnect();
} else if (e && e.code === 1006 && !this._conn.connected && this.socket) {
// in case the onError callback was not called (Safari 10 does not
// call onerror when the initial connection fails) we need to
// dispatch a CONNFAIL status update to be consistent with the
// behavior on other browsers.
core.error('Websocket closed unexcectedly');
this._conn._changeConnectStatus(core.Status.CONNFAIL, 'The WebSocket connection could not be established or was disconnected.');
this._conn._doDisconnect();
} else {
core.debug('Websocket closed');
}
}
/**
* @callback connectionCallback
* @param {Connection} connection
*/
/**
* Called on stream start/restart when no stream:features
* has been received.
* @param {connectionCallback} callback
*/
_no_auth_received(callback) {
core.error('Server did not offer a supported authentication mechanism');
this._conn._changeConnectStatus(core.Status.CONNFAIL, core.ErrorCondition.NO_AUTH_MECH);
callback?.call(this._conn);
this._conn._doDisconnect();
}
/**
* _Private_ timeout handler for handling non-graceful disconnection.
*
* This does nothing for WebSockets
*/
_onDisconnectTimeout() {} // eslint-disable-line class-methods-use-this
/**
* _Private_ helper function that makes sure all pending requests are aborted.
*/
_abortAllRequests() {} // eslint-disable-line class-methods-use-this
/**
* _Private_ function to handle websockets errors.
* @param {Object} error - The websocket error.
*/
_onError(error) {
core.error('Websocket error ' + JSON.stringify(error));
this._conn._changeConnectStatus(core.Status.CONNFAIL, 'The WebSocket connection could not be established or was disconnected.');
this._disconnect();
}
/**
* _Private_ function called by Strophe.Connection._onIdle
* sends all queued stanzas
*/
_onIdle() {
const data = this._conn._data;
if (data.length > 0 && !this._conn.paused) {
for (let i = 0; i < data.length; i++) {
if (data[i] !== null) {
const stanza = data[i] === 'restart' ? this._buildStream().tree() : data[i];
if (stanza === 'restart') throw new Error('Wrong type for stanza'); // Shut up tsc
const rawStanza = core.serialize(stanza);
this._conn.xmlOutput(stanza);
this._conn.rawOutput(rawStanza);
this.socket.send(rawStanza);
}
}
this._conn._data = [];
}
}
/**
* _Private_ function to handle websockets messages.
*
* This function parses each of the messages as if they are full documents.
* [TODO : We may actually want to use a SAX Push parser].
*
* Since all XMPP traffic starts with
* <stream:stream version='1.0'
* xml:lang='en'
* xmlns='jabber:client'
* xmlns:stream='http://etherx.jabber.org/streams'
* id='3697395463'
* from='SERVER'>
*
* The first stanza will always fail to be parsed.
*
* Additionally, the seconds stanza will always be <stream:features> with
* the stream NS defined in the previous stanza, so we need to 'force'
* the inclusion of the NS in this stanza.
*
* @param {MessageEvent} message - The websocket message event
*/
_onMessage(message) {
let elem;
// check for closing stream
const close = '<close xmlns="urn:ietf:params:xml:ns:xmpp-framing" />';
if (message.data === close) {
this._conn.rawInput(close);
this._conn.xmlInput(message);
if (!this._conn.disconnecting) {
this._conn._doDisconnect();
}
return;
} else if (message.data.search('<open ') === 0) {
// This handles stream restarts
elem = new DOMParser().parseFromString(message.data, 'text/xml').documentElement;
if (!this._handleStreamStart(elem)) {
return;
}
} else {
const data = this._streamWrap(message.data);
elem = new DOMParser().parseFromString(data, 'text/xml').documentElement;
}
if (this._checkStreamError(elem, core.Status.ERROR)) {
return;
}
//handle unavailable presence stanza before disconnecting
if (this._conn.disconnecting && elem.firstElementChild.nodeName === 'presence' && elem.firstElementChild.getAttribute('type') === 'unavailable') {
this._conn.xmlInput(elem);
this._conn.rawInput(core.serialize(elem));
// if we are already disconnecting we will ignore the unavailable stanza and
// wait for the </stream:stream> tag before we close the connection
return;
}
this._conn._dataRecv(elem, message.data);
}
/**
* _Private_ function to handle websockets connection setup.
* The opening stream tag is sent here.
* @private
*/
_onOpen() {
core.debug('Websocket open');
const start = this._buildStream();
this._conn.xmlOutput(start.tree());
const startString = core.serialize(start);
this._conn.rawOutput(startString);
this.socket.send(startString);
}
/**
* _Private_ part of the Connection.send function for WebSocket
* Just flushes the messages that are in the queue
*/
_send() {
this._conn.flush();
}
/**
* Send an xmpp:restart stanza.
*/
_sendRestart() {
clearTimeout(this._conn._idleTimeout);
this._conn._onIdle.bind(this._conn)();
}
}
/* harmony default export */ const websocket = (Websocket);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/worker-websocket.js
/**
* @license MIT
* @copyright JC Brand
*
* @typedef {import("./connection.js").default} Connection
* @typedef {import("./builder.js").default} Builder
*/
/**
* Helper class that handles a websocket connection inside a shared worker.
*/
class WorkerWebsocket extends websocket {
/**
* Create and initialize a Strophe.WorkerWebsocket object.
* @param {Connection} connection - The Strophe.Connection
*/
constructor(connection) {
super(connection);
this._conn = connection;
this.worker = new SharedWorker(this._conn.options.worker, 'Strophe XMPP Connection');
this.worker.onerror = e => {
console?.error(e);
core.log(core.LogLevel.ERROR, `Shared Worker Error: ${e}`);
};
}
/**
* @private
*/
_setSocket() {
this.socket = {
/** @param {string} str */
send: str => this.worker.port.postMessage(['send', str]),
close: () => this.worker.port.postMessage(['_closeSocket']),
onopen: () => {},
/** @param {ErrorEvent} e */
onerror: e => this._onError(e),
/** @param {CloseEvent} e */
onclose: e => this._onClose(e),
onmessage: () => {},
readyState: null
};
}
_connect() {
this._setSocket();
/** @param {MessageEvent} m */
this._messageHandler = m => this._onInitialMessage(m);
this.worker.port.start();
this.worker.port.onmessage = ev => this._onWorkerMessage(ev);
this.worker.port.postMessage(['_connect', this._conn.service, this._conn.jid]);
}
/**
* @param {Function} callback
*/
_attach(callback) {
this._setSocket();
/** @param {MessageEvent} m */
this._messageHandler = m => this._onMessage(m);
this._conn.connect_callback = callback;
this.worker.port.start();
this.worker.port.onmessage = ev => this._onWorkerMessage(ev);
this.worker.port.postMessage(['_attach', this._conn.service]);
}
/**
* @param {number} status
* @param {string} jid
*/
_attachCallback(status, jid) {
if (status === core.Status.ATTACHED) {
this._conn.jid = jid;
this._conn.authenticated = true;
this._conn.connected = true;
this._conn.restored = true;
this._conn._changeConnectStatus(core.Status.ATTACHED);
} else if (status === core.Status.ATTACHFAIL) {
this._conn.authenticated = false;
this._conn.connected = false;
this._conn.restored = false;
this._conn._changeConnectStatus(core.Status.ATTACHFAIL);
}
}
/**
* @param {Element|Builder} pres - This stanza will be sent before disconnecting.
*/
_disconnect(pres) {
pres && this._conn.send(pres);
const close = $build('close', {
'xmlns': core.NS.FRAMING
});
this._conn.xmlOutput(close.tree());
const closeString = core.serialize(close);
this._conn.rawOutput(closeString);
this.worker.port.postMessage(['send', closeString]);
this._conn._doDisconnect();
}
_closeSocket() {
this.socket.close();
}
/**
* Called by _onInitialMessage in order to replace itself with the general message handler.
* This method is overridden by WorkerWebsocket, which manages a
* websocket connection via a service worker and doesn't have direct access
* to the socket.
*/
_replaceMessageHandler() {
/** @param {MessageEvent} m */
this._messageHandler = m => this._onMessage(m);
}
/**
* function that handles messages received from the service worker
* @private
* @param {MessageEvent} ev
*/
_onWorkerMessage(ev) {
/** @type {Object.<string, number>} */
const lmap = {};
lmap['debug'] = core.LogLevel.DEBUG;
lmap['info'] = core.LogLevel.INFO;
lmap['warn'] = core.LogLevel.WARN;
lmap['error'] = core.LogLevel.ERROR;
lmap['fatal'] = core.LogLevel.FATAL;
const {
data
} = ev;
const method_name = data[0];
if (method_name === '_onMessage') {
this._messageHandler(data[1]);
} else if (method_name in this) {
try {
this[/** @type {'_attachCallback'|'_onOpen'|'_onClose'|'_onError'} */
method_name].apply(this, ev.data.slice(1));
} catch (e) {
core.log(core.LogLevel.ERROR, e);
}
} else if (method_name === 'log') {
const level = data[1];
const msg = data[2];
core.log(lmap[level], msg);
} else {
core.log(core.LogLevel.ERROR, `Found unhandled service worker message: ${data}`);
}
}
}
/* harmony default export */ const worker_websocket = (WorkerWebsocket);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/core.js
/**
* A container for all Strophe library functions.
*
* This object is a container for all the objects and constants
* used in the library. It is not meant to be instantiated, but to
* provide a namespace for library objects, constants, and functions.
*
* @namespace Strophe
* @property {Handler} Handler
* @property {Builder} Builder
* @property {Request} Request Represents HTTP Requests made for a BOSH connection
* @property {Bosh} Bosh Support for XMPP-over-HTTP via XEP-0124 (BOSH)
* @property {Websocket} Websocket Support for XMPP over websocket
* @property {WorkerWebsocket} WorkerWebsocket Support for XMPP over websocket in a shared worker
* @property {number} TIMEOUT=1.1 Timeout multiplier. A waiting BOSH HTTP request
* will be considered failed after Math.floor(TIMEOUT * wait) seconds have elapsed.
* This defaults to 1.1, and with default wait, 66 seconds.
* @property {number} SECONDARY_TIMEOUT=0.1 Secondary timeout multiplier.
* In cases where Strophe can detect early failure, it will consider the request
* failed if it doesn't return after `Math.floor(SECONDARY_TIMEOUT * wait)`
* seconds have elapsed. This defaults to 0.1, and with default wait, 6 seconds.
* @property {SASLAnonymous} SASLAnonymous SASL ANONYMOUS authentication.
* @property {SASLPlain} SASLPlain SASL PLAIN authentication
* @property {SASLSHA1} SASLSHA1 SASL SCRAM-SHA-1 authentication
* @property {SASLSHA256} SASLSHA256 SASL SCRAM-SHA-256 authentication
* @property {SASLSHA384} SASLSHA384 SASL SCRAM-SHA-384 authentication
* @property {SASLSHA512} SASLSHA512 SASL SCRAM-SHA-512 authentication
* @property {SASLOAuthBearer} SASLOAuthBearer SASL OAuth Bearer authentication
* @property {SASLExternal} SASLExternal SASL EXTERNAL authentication
* @property {SASLXOAuth2} SASLXOAuth2 SASL X-OAuth2 authentication
* @property {Status} Status
* @property {Object.<string, string>} NS
* @property {XHTML} XHTML
*/
const core_Strophe = {
/** @constant: VERSION */
VERSION: '1.6.1',
TIMEOUT: 1.1,
SECONDARY_TIMEOUT: 0.1,
shims: strophe_shims_namespaceObject,
Request: request,
// Transports
Bosh: bosh,
Websocket: websocket,
WorkerWebsocket: worker_websocket,
// Available authentication mechanisms
SASLAnonymous: sasl_anon,
SASLPlain: sasl_plain,
SASLSHA1: sasl_sha1,
SASLSHA256: sasl_sha256,
SASLSHA384: sasl_sha384,
SASLSHA512: sasl_sha512,
SASLOAuthBearer: sasl_oauthbearer,
SASLExternal: sasl_external,
SASLXOAuth2: sasl_xoauth2,
Builder: builder,
Connection: connection,
ElementType: ElementType,
ErrorCondition: ErrorCondition,
Handler: src_handler,
LogLevel: LogLevel,
/** @type {Object.<string, string>} */
NS: NS,
SASLMechanism: sasl,
/** @type {Status} */
Status: Status,
TimedHandler: timed_handler,
...utils_namespaceObject,
XHTML: {
...XHTML,
validTag: validTag,
validCSS: validCSS,
validAttribute: validAttribute
},
/**
* This function is used to extend the current namespaces in
* Strophe.NS. It takes a key and a value with the key being the
* name of the new namespace, with its actual value.
* @example: Strophe.addNamespace('PUBSUB', "http://jabber.org/protocol/pubsub");
*
* @param {string} name - The name under which the namespace will be
* referenced under Strophe.NS
* @param {string} value - The actual namespace.
*/
addNamespace(name, value) {
core_Strophe.NS[name] = value;
},
/**
* _Private_ function that properly logs an error to the console
* @private
* @param {Error} e
*/
_handleError(e) {
if (typeof e.stack !== 'undefined') {
core_Strophe.fatal(e.stack);
}
core_Strophe.fatal('error: ' + e.message);
},
/**
* User overrideable logging function.
*
* This function is called whenever the Strophe library calls any
* of the logging functions. The default implementation of this
* function logs only fatal errors. If client code wishes to handle the logging
* messages, it should override this with
* > Strophe.log = function (level, msg) {
* > (user code here)
* > };
*
* Please note that data sent and received over the wire is logged
* via {@link Strophe.Connection#rawInput|Strophe.Connection.rawInput()}
* and {@link Strophe.Connection#rawOutput|Strophe.Connection.rawOutput()}.
*
* The different levels and their meanings are
*
* DEBUG - Messages useful for debugging purposes.
* INFO - Informational messages. This is mostly information like
* 'disconnect was called' or 'SASL auth succeeded'.
* WARN - Warnings about potential problems. This is mostly used
* to report transient connection errors like request timeouts.
* ERROR - Some error occurred.
* FATAL - A non-recoverable fatal error occurred.
*
* @param {number} level - The log level of the log message.
* This will be one of the values in Strophe.LogLevel.
* @param {string} msg - The log message.
*/
log(level, msg) {
if (level === this.LogLevel.FATAL) {
console?.error(msg);
}
},
/**
* Log a message at the Strophe.LogLevel.DEBUG level.
* @param {string} msg - The log message.
*/
debug(msg) {
this.log(this.LogLevel.DEBUG, msg);
},
/**
* Log a message at the Strophe.LogLevel.INFO level.
* @param {string} msg - The log message.
*/
info(msg) {
this.log(this.LogLevel.INFO, msg);
},
/**
* Log a message at the Strophe.LogLevel.WARN level.
* @param {string} msg - The log message.
*/
warn(msg) {
this.log(this.LogLevel.WARN, msg);
},
/**
* Log a message at the Strophe.LogLevel.ERROR level.
* @param {string} msg - The log message.
*/
error(msg) {
this.log(this.LogLevel.ERROR, msg);
},
/**
* Log a message at the Strophe.LogLevel.FATAL level.
* @param {string} msg - The log message.
*/
fatal(msg) {
this.log(this.LogLevel.FATAL, msg);
},
/**
* _Private_ variable that keeps track of the request ids for connections.
* @private
*/
_requestId: 0,
/**
* _Private_ variable Used to store plugin names that need
* initialization on Strophe.Connection construction.
* @private
* @type {Object.<string, Object>}
*/
_connectionPlugins: {},
/**
* Extends the Strophe.Connection object with the given plugin.
* @param {string} name - The name of the extension.
* @param {Object} ptype - The plugin's prototype.
*/
addConnectionPlugin(name, ptype) {
core_Strophe._connectionPlugins[name] = ptype;
}
};
/* harmony default export */ const core = (core_Strophe);
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/stanza.js
const PARSE_ERROR_NS = 'http://www.w3.org/1999/xhtml';
/**
* @param { string } string
* @param { boolean } [throwErrorIfInvalidNS]
* @return { Element }
*/
function toStanza(string, throwErrorIfInvalidNS) {
const doc = Strophe.xmlHtmlNode(string);
if (doc.getElementsByTagNameNS(PARSE_ERROR_NS, 'parsererror').length) {
throw new Error(`Parser Error: ${string}`);
}
const node = doc.firstElementChild;
if (['message', 'iq', 'presence'].includes(node.nodeName.toLowerCase()) && node.namespaceURI !== 'jabber:client' && node.namespaceURI !== 'jabber:server') {
const err_msg = `Invalid namespaceURI ${node.namespaceURI}`;
if (throwErrorIfInvalidNS) {
throw new Error(err_msg);
} else {
Strophe.log(Strophe.LogLevel.ERROR, err_msg);
}
}
return node;
}
/**
* A Stanza represents a XML element used in XMPP (commonly referred to as
* stanzas).
*/
class Stanza {
/**
* @param { string[] } strings
* @param { any[] } values
*/
constructor(strings, values) {
this.strings = strings;
this.values = values;
}
/**
* @return { string }
*/
toString() {
this.string = this.string || this.strings.reduce((acc, str) => {
const idx = this.strings.indexOf(str);
const value = this.values.length > idx ? this.values[idx].toString() : '';
return acc + str + value;
}, '');
return this.string;
}
/**
* @return { Element }
*/
tree() {
this.node = this.node ?? toStanza(this.toString(), true);
return this.node;
}
}
/**
* Tagged template literal function which generates {@link Stanza } objects
* @example stx`<presence type="${type}" xmlns="jabber:client"><show>${show}</show></presence>`
*
* @param { string[] } strings
* @param { ...any } values
*/
function stx(strings) {
for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
values[_key - 1] = arguments[_key];
}
return new Stanza(strings, values);
}
;// CONCATENATED MODULE: ./node_modules/strophe.js/src/index.js
/*global globalThis*/
globalThis.$build = $build;
globalThis.$iq = $iq;
globalThis.$msg = $msg;
globalThis.$pres = $pres;
globalThis.Strophe = core;
;// CONCATENATED MODULE: ./src/headless/shared/constants.js
const BOSH_WAIT = 59;
const VERSION_NAME = "v10.1.7";
const constants_STATUS_WEIGHTS = {
offline: 6,
unavailable: 5,
xa: 4,
away: 3,
dnd: 2,
chat: 1,
// We don't differentiate between "chat" and "online"
online: 1
};
const ANONYMOUS = 'anonymous';
const CLOSED = 'closed';
const EXTERNAL = 'external';
const LOGIN = 'login';
const LOGOUT = 'logout';
const OPENED = 'opened';
const PREBIND = 'prebind';
const SUCCESS = 'success';
const FAILURE = 'failure';
// Generated from css/images/user.svg
const DEFAULT_IMAGE_TYPE = 'image/svg+xml';
const DEFAULT_IMAGE = 'PD94bWwgdmVyc2lvbj0iMS4wIj8+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiA8cmVjdCB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCIgZmlsbD0iIzU1NSIvPgogPGNpcmNsZSBjeD0iNjQiIGN5PSI0MSIgcj0iMjQiIGZpbGw9IiNmZmYiLz4KIDxwYXRoIGQ9Im0yOC41IDExMiB2LTEyIGMwLTEyIDEwLTI0IDI0LTI0IGgyMyBjMTQgMCAyNCAxMiAyNCAyNCB2MTIiIGZpbGw9IiNmZmYiLz4KPC9zdmc+Cg==';
// XEP-0085 Chat states
// https =//xmpp.org/extensions/xep-0085.html
const INACTIVE = 'inactive';
const ACTIVE = 'active';
const COMPOSING = 'composing';
const PAUSED = 'paused';
const GONE = 'gone';
// Chat types
const PRIVATE_CHAT_TYPE = 'chatbox';
const CHATROOMS_TYPE = 'chatroom';
const HEADLINES_TYPE = 'headline';
const CONTROLBOX_TYPE = 'controlbox';
const CONNECTION_STATUS = {};
CONNECTION_STATUS[core.Status.ATTACHED] = 'ATTACHED';
CONNECTION_STATUS[core.Status.AUTHENTICATING] = 'AUTHENTICATING';
CONNECTION_STATUS[core.Status.AUTHFAIL] = 'AUTHFAIL';
CONNECTION_STATUS[core.Status.CONNECTED] = 'CONNECTED';
CONNECTION_STATUS[core.Status.CONNECTING] = 'CONNECTING';
CONNECTION_STATUS[core.Status.CONNFAIL] = 'CONNFAIL';
CONNECTION_STATUS[core.Status.DISCONNECTED] = 'DISCONNECTED';
CONNECTION_STATUS[core.Status.DISCONNECTING] = 'DISCONNECTING';
CONNECTION_STATUS[core.Status.ERROR] = 'ERROR';
CONNECTION_STATUS[core.Status.RECONNECTING] = 'RECONNECTING';
CONNECTION_STATUS[core.Status.REDIRECT] = 'REDIRECT';
// Add Strophe Namespaces
core.addNamespace('ACTIVITY', 'http://jabber.org/protocol/activity');
core.addNamespace('CARBONS', 'urn:xmpp:carbons:2');
core.addNamespace('CHATSTATES', 'http://jabber.org/protocol/chatstates');
core.addNamespace('CSI', 'urn:xmpp:csi:0');
core.addNamespace('DELAY', 'urn:xmpp:delay');
core.addNamespace('EME', 'urn:xmpp:eme:0');
core.addNamespace('FASTEN', 'urn:xmpp:fasten:0');
core.addNamespace('FORWARD', 'urn:xmpp:forward:0');
core.addNamespace('HINTS', 'urn:xmpp:hints');
core.addNamespace('HTTPUPLOAD', 'urn:xmpp:http:upload:0');
core.addNamespace('MAM', 'urn:xmpp:mam:2');
core.addNamespace('MARKERS', 'urn:xmpp:chat-markers:0');
core.addNamespace('MENTIONS', 'urn:xmpp:mmn:0');
core.addNamespace('MESSAGE_CORRECT', 'urn:xmpp:message-correct:0');
core.addNamespace('MODERATE', 'urn:xmpp:message-moderate:0');
core.addNamespace('NICK', 'http://jabber.org/protocol/nick');
core.addNamespace('OCCUPANTID', 'urn:xmpp:occupant-id:0');
core.addNamespace('OMEMO', 'eu.siacs.conversations.axolotl');
core.addNamespace('OUTOFBAND', 'jabber:x:oob');
core.addNamespace('PUBSUB', 'http://jabber.org/protocol/pubsub');
core.addNamespace('RAI', 'urn:xmpp:rai:0');
core.addNamespace('RECEIPTS', 'urn:xmpp:receipts');
core.addNamespace('REFERENCE', 'urn:xmpp:reference:0');
core.addNamespace('REGISTER', 'jabber:iq:register');
core.addNamespace('RETRACT', 'urn:xmpp:message-retract:0');
core.addNamespace('ROSTERX', 'http://jabber.org/protocol/rosterx');
core.addNamespace('RSM', 'http://jabber.org/protocol/rsm');
core.addNamespace('SID', 'urn:xmpp:sid:0');
core.addNamespace('SPOILER', 'urn:xmpp:spoiler:0');
core.addNamespace('STANZAS', 'urn:ietf:params:xml:ns:xmpp-stanzas');
core.addNamespace('STYLING', 'urn:xmpp:styling:0');
core.addNamespace('VCARD', 'vcard-temp');
core.addNamespace('VCARDUPDATE', 'vcard-temp:x:update');
core.addNamespace('XFORM', 'jabber:x:data');
core.addNamespace('XHTML', 'http://www.w3.org/1999/xhtml');
// Core plugins are whitelisted automatically
// These are just the @converse/headless plugins, for the full converse,
// the other plugins are whitelisted in src/consts.js
const CORE_PLUGINS = ['converse-adhoc', 'converse-bookmarks', 'converse-bosh', 'converse-caps', 'converse-chat', 'converse-chatboxes', 'converse-disco', 'converse-emoji', 'converse-headlines', 'converse-mam', 'converse-muc', 'converse-ping', 'converse-pubsub', 'converse-roster', 'converse-smacks', 'converse-status', 'converse-vcard'];
const URL_PARSE_OPTIONS = {
'start': /(\b|_)(?:([a-z][a-z0-9.+-]*:\/\/)|xmpp:|mailto:|www\.)/gi
};
const CHAT_STATES = ['active', 'composing', 'gone', 'inactive', 'paused'];
const KEYCODES = {
TAB: 9,
ENTER: 13,
SHIFT: 16,
CTRL: 17,
ALT: 18,
ESCAPE: 27,
LEFT_ARROW: 37,
UP_ARROW: 38,
RIGHT_ARROW: 39,
DOWN_ARROW: 40,
FORWARD_SLASH: 47,
AT: 50,
META: 91,
META_RIGHT: 93
};
// EXTERNAL MODULE: ./node_modules/sprintf-js/src/sprintf.js
var sprintf = __webpack_require__(293);
;// CONCATENATED MODULE: ./src/headless/shared/i18n.js
/**
* @namespace i18n
*/
/* harmony default export */ const i18n = ({
initialize() {},
/**
* Overridable string wrapper method which can be used to provide i18n
* support.
*
* The default implementation in @converse/headless simply calls sprintf
* with the passed in arguments.
*
* If you install the full version of Converse, then this method gets
* overwritten in src/i18n/index.js to return a translated string.
* @method __
* @private
* @memberOf i18n
* @param { String } str
*/
__() {
return (0,sprintf.sprintf)(...arguments);
}
});
// EXTERNAL MODULE: ./node_modules/dompurify/dist/purify.js
var purify = __webpack_require__(856);
var purify_default = /*#__PURE__*/__webpack_require__.n(purify);
;// CONCATENATED MODULE: ./node_modules/lodash-es/compact.js
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}
/* harmony default export */ const lodash_es_compact = (compact);
// EXTERNAL MODULE: ./node_modules/sizzle/dist/sizzle.js
var sizzle = __webpack_require__(271);
var sizzle_default = /*#__PURE__*/__webpack_require__.n(sizzle);
;// CONCATENATED MODULE: ./node_modules/@converse/openpromise/openpromise.js
function getOpenPromise() {
const wrapper = {
isResolved: false,
isPending: true,
isRejected: false
};
const promise = new Promise((resolve, reject) => {
wrapper.resolve = resolve;
wrapper.reject = reject;
});
Object.assign(promise, wrapper);
promise.then(function (v) {
promise.isResolved = true;
promise.isPending = false;
promise.isRejected = false;
return v;
}, function (e) {
promise.isResolved = false;
promise.isPending = false;
promise.isRejected = true;
throw e;
});
return promise;
}
;// CONCATENATED MODULE: ./src/headless/shared/settings/constants.js
/**
* @typedef { Object } ConfigurationSettings
* Converse's core configuration values
* @property { Boolean } [allow_non_roster_messaging=false]
* @property { Boolean } [allow_url_history_change=true]
* @property { String } [assets_path='/dist']
* @property { ('login'|'prebind'|'anonymous'|'external') } [authentication='login']
* @property { Boolean } [auto_login=false] - Currently only used in connection with anonymous login
* @property { Boolean } [reuse_scram_keys=false] - Save SCRAM keys after login to allow for future auto login
* @property { Boolean } [auto_reconnect=true]
* @property { Array<String>} [blacklisted_plugins]
* @property { Boolean } [clear_cache_on_logout=false]
* @property { Object } [connection_options]
* @property { String } [credentials_url] - URL from where login credentials can be fetched
* @property { Boolean } [discover_connection_methods=true]
* @property { RegExp } [geouri_regex]
* @property { RegExp } [geouri_replacement='https://www.openstreetmap.org/?mlat=$1&mlon=$2#map=18/$1/$2']
* @property { String } [i18n]
* @property { String } [jid]
* @property { Boolean } [keepalive=true]
* @property { ('debug'|'info'|'eror') } [loglevel='info']
* @property { Array<String> } [locales]
* @property { String } [nickname]
* @property { String } [password]
* @property { ('IndexedDB'|'localStorage') } [persistent_store='IndexedDB']
* @property { String } [rid]
* @property { Element } [root=window.document]
* @property { String } [sid]
* @property { Boolean } [singleton=false]
* @property { Boolean } [strict_plugin_dependencies=false]
* @property { ('overlayed'|'fullscreen'|'mobile') } [view_mode='overlayed']
* @property { String } [websocket_url]
* @property { Array<String>} [whitelisted_plugins]
*/
const DEFAULT_SETTINGS = {
allow_non_roster_messaging: false,
allow_url_history_change: true,
assets_path: '/dist',
authentication: 'login',
// Available values are "login", "prebind", "anonymous" and "external".
auto_login: false,
// Currently only used in connection with anonymous login
reuse_scram_keys: false,
auto_reconnect: true,
blacklisted_plugins: [],
clear_cache_on_logout: false,
connection_options: {},
credentials_url: null,
// URL from where login credentials can be fetched
discover_connection_methods: true,
geouri_regex: /https\:\/\/www.openstreetmap.org\/.*#map=[0-9]+\/([\-0-9.]+)\/([\-0-9.]+)\S*/g,
geouri_replacement: 'https://www.openstreetmap.org/?mlat=$1&mlon=$2#map=18/$1/$2',
i18n: undefined,
jid: undefined,
keepalive: true,
loglevel: 'info',
locales: ['af', 'ar', 'bg', 'ca', 'cs', 'da', 'de', 'el', 'en', 'eo', 'es', 'eu', 'fa', 'fi', 'fr', 'gl', 'he', 'hi', 'hu', 'id', 'it', 'ja', 'lt', 'mr', 'nb', 'nl', 'oc', 'pl', 'pt', 'pt_BR', 'ro', 'ru', 'sv', 'th', 'tr', 'ug', 'uk', 'vi', 'zh_CN', 'zh_TW'],
nickname: undefined,
password: undefined,
persistent_store: 'IndexedDB',
rid: undefined,
root: window.document,
sid: undefined,
singleton: false,
strict_plugin_dependencies: false,
stanza_timeout: 20000,
view_mode: 'overlayed',
// Choices are 'overlayed', 'fullscreen', 'mobile'
websocket_url: undefined,
whitelisted_plugins: []
};
// EXTERNAL MODULE: ./node_modules/localforage-driver-memory/_bundle/umd.js
var umd = __webpack_require__(245);
;// CONCATENATED MODULE: ./node_modules/lodash-es/cloneDeep.js
/** Used to compose bitmasks for cloning. */
var cloneDeep_CLONE_DEEP_FLAG = 1,
cloneDeep_CLONE_SYMBOLS_FLAG = 4;
/**
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @see _.clone
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
*/
function cloneDeep(value) {
return _baseClone(value, cloneDeep_CLONE_DEEP_FLAG | cloneDeep_CLONE_SYMBOLS_FLAG);
}
/* harmony default export */ const lodash_es_cloneDeep = (cloneDeep);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isString.js
/** `Object#toString` result references. */
var isString_stringTag = '[object String]';
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!lodash_es_isArray(value) && lodash_es_isObjectLike(value) && _baseGetTag(value) == isString_stringTag);
}
/* harmony default export */ const lodash_es_isString = (isString);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/idb.js
function getIDB() {
/* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */
try {
if (typeof indexedDB !== 'undefined') {
return indexedDB;
}
if (typeof webkitIndexedDB !== 'undefined') {
return webkitIndexedDB;
}
if (typeof mozIndexedDB !== 'undefined') {
return mozIndexedDB;
}
if (typeof OIndexedDB !== 'undefined') {
return OIndexedDB;
}
if (typeof msIndexedDB !== 'undefined') {
return msIndexedDB;
}
} catch (e) {
return;
}
}
var idb = getIDB();
/* harmony default export */ const utils_idb = (idb);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/isIndexedDBValid.js
function isIndexedDBValid() {
try {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
if (!utils_idb || !utils_idb.open) {
return false;
}
// We mimic PouchDB here;
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;
// Safari <10.1 does not meet our requirements for IDB support
// (see: https://github.com/pouchdb/pouchdb/issues/5572).
// Safari 10.1 shipped with fetch, we can use that to detect it.
// Note: this creates issues with `window.fetch` polyfills and
// overrides; see:
// https://github.com/localForage/localForage/issues/856
return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&
// some outdated implementations of IDB that appear on Samsung
// and HTC Android devices <4.4 are missing IDBKeyRange
// See: https://github.com/mozilla/localForage/issues/128
// See: https://github.com/mozilla/localForage/issues/272
typeof IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
}
/* harmony default export */ const utils_isIndexedDBValid = (isIndexedDBValid);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/createBlob.js
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function createBlob(parts, properties) {
/* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
var builder = new Builder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
/* harmony default export */ const utils_createBlob = (createBlob);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/promise.js
// This is CommonJS because lie is an external dependency, so Rollup
// can just ignore it.
if (typeof Promise === 'undefined') {
// In the "nopromises" build this will just throw if you don't have
// a global promise object, but it would throw anyway later.
__webpack_require__(236);
}
/* harmony default export */ const utils_promise = (Promise);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/executeCallback.js
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
/* harmony default export */ const utils_executeCallback = (executeCallback);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/executeTwoCallbacks.js
function executeTwoCallbacks(promise, callback, errorCallback) {
if (typeof callback === 'function') {
promise.then(callback);
}
if (typeof errorCallback === 'function') {
promise.catch(errorCallback);
}
}
/* harmony default export */ const utils_executeTwoCallbacks = (executeTwoCallbacks);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/normalizeKey.js
function normalizeKey(key) {
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
console.warn(`${key} used as a key, but it is not a string.`);
key = String(key);
}
return key;
}
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/getCallback.js
function getCallback() {
if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
return arguments[arguments.length - 1];
}
}
;// CONCATENATED MODULE: ./node_modules/localforage/src/drivers/indexeddb.js
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
const DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
let supportsBlobs;
const dbContexts = {};
const indexeddb_toString = Object.prototype.toString;
// Transaction Modes
const READ_ONLY = 'readonly';
const READ_WRITE = 'readwrite';
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
//
// Blobs are not supported in all versions of IndexedDB, notably
// Chrome <37 and Android <5. In those versions, storing a blob will throw.
//
// Various other blob bugs exist in Chrome v37-42 (inclusive).
// Detecting them is expensive and confusing to users, and Chrome 37-42
// is at very low usage worldwide, so we do a hacky userAgent check instead.
//
// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
// Code borrowed from PouchDB. See:
// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js
//
function _checkBlobSupportWithoutCaching(idb) {
return new utils_promise(function (resolve) {
var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
var blob = utils_createBlob(['']);
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.onabort = function (e) {
// If the transaction aborts now its due to not being able to
// write to the database, likely due to the disk being full
e.preventDefault();
e.stopPropagation();
resolve(false);
};
txn.oncomplete = function () {
var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
var matchedEdge = navigator.userAgent.match(/Edge\//);
// MS Edge pretends to be Chrome 42:
// https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
};
}).catch(function () {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return utils_promise.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function (value) {
supportsBlobs = value;
return supportsBlobs;
});
}
function _deferReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Create a deferred object representing the current database operation.
var deferredOperation = {};
deferredOperation.promise = new utils_promise(function (resolve, reject) {
deferredOperation.resolve = resolve;
deferredOperation.reject = reject;
});
// Enqueue the deferred operation.
dbContext.deferredOperations.push(deferredOperation);
// Chain its promise to the database readiness.
if (!dbContext.dbReady) {
dbContext.dbReady = deferredOperation.promise;
} else {
dbContext.dbReady = dbContext.dbReady.then(function () {
return deferredOperation.promise;
});
}
}
function _advanceReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Dequeue a deferred operation.
var deferredOperation = dbContext.deferredOperations.pop();
// Resolve its promise (which is part of the database readiness
// chain of promises).
if (deferredOperation) {
deferredOperation.resolve();
return deferredOperation.promise;
}
}
function _rejectReadiness(dbInfo, err) {
var dbContext = dbContexts[dbInfo.name];
// Dequeue a deferred operation.
var deferredOperation = dbContext.deferredOperations.pop();
// Reject its promise (which is part of the database readiness
// chain of promises).
if (deferredOperation) {
deferredOperation.reject(err);
return deferredOperation.promise;
}
}
function _getConnection(dbInfo, upgradeNeeded) {
return new utils_promise(function (resolve, reject) {
dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
if (dbInfo.db) {
if (upgradeNeeded) {
_deferReadiness(dbInfo);
dbInfo.db.close();
} else {
return resolve(dbInfo.db);
}
}
var dbArgs = [dbInfo.name];
if (upgradeNeeded) {
dbArgs.push(dbInfo.version);
}
var openreq = utils_idb.open.apply(utils_idb, dbArgs);
if (upgradeNeeded) {
openreq.onupgradeneeded = function (e) {
var db = openreq.result;
try {
db.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// Added when support for blob shims was added
db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
} catch (ex) {
if (ex.name === 'ConstraintError') {
console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
} else {
throw ex;
}
}
};
}
openreq.onerror = function (e) {
e.preventDefault();
reject(openreq.error);
};
openreq.onsuccess = function () {
var db = openreq.result;
db.onversionchange = function (e) {
// Triggered when the database is modified (e.g. adding an objectStore) or
// deleted (even when initiated by other sessions in different tabs).
// Closing the connection here prevents those operations from being blocked.
// If the database is accessed again later by this instance, the connection
// will be reopened or the database recreated as needed.
e.target.close();
};
resolve(db);
_advanceReadiness(dbInfo);
};
});
}
function _getOriginalConnection(dbInfo) {
return _getConnection(dbInfo, false);
}
function _getUpgradedConnection(dbInfo) {
return _getConnection(dbInfo, true);
}
function _isUpgradeNeeded(dbInfo, defaultVersion) {
if (!dbInfo.db) {
return true;
}
var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
var isDowngrade = dbInfo.version < dbInfo.db.version;
var isUpgrade = dbInfo.version > dbInfo.db.version;
if (isDowngrade) {
// If the version is not the default one
// then warn for impossible downgrade.
if (dbInfo.version !== defaultVersion) {
console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
}
// Align the versions to prevent errors.
dbInfo.version = dbInfo.db.version;
}
if (isUpgrade || isNewStore) {
// If the store is new then increment the version (if needed).
// This will trigger an "upgradeneeded" event which is required
// for creating a store.
if (isNewStore) {
var incVersion = dbInfo.db.version + 1;
if (incVersion > dbInfo.version) {
dbInfo.version = incVersion;
}
}
return true;
}
return false;
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new utils_promise(function (resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function (e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return utils_createBlob([arrayBuff], {
type: encodedBlob.type
});
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Specialize the default `ready()` function by making it dependent
// on the current database operations. Thus, the driver will be actually
// ready when it's been initialized (default) *and* there are no pending
// operations on the database (initiated by some other instances).
function _fullyReady(callback) {
var self = this;
var promise = self._initReady().then(function () {
var dbContext = dbContexts[self._dbInfo.name];
if (dbContext && dbContext.dbReady) {
return dbContext.dbReady;
}
});
utils_executeTwoCallbacks(promise, callback, callback);
return promise;
}
// Try to establish a new db connection to replace the
// current one which is broken (i.e. experiencing
// InvalidStateError while creating a transaction).
function _tryReconnect(dbInfo) {
_deferReadiness(dbInfo);
var dbContext = dbContexts[dbInfo.name];
var forages = dbContext.forages;
for (var i = 0; i < forages.length; i++) {
const forage = forages[i];
if (forage._dbInfo.db) {
forage._dbInfo.db.close();
forage._dbInfo.db = null;
}
}
dbInfo.db = null;
return _getOriginalConnection(dbInfo).then(db => {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
}).then(db => {
// store the latest db reference
// in case the db was upgraded
dbInfo.db = dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
forages[i]._dbInfo.db = db;
}
}).catch(err => {
_rejectReadiness(dbInfo, err);
throw err;
});
}
// FF doesn't like Promises (micro-tasks) and IDDB store operations,
// so we have to do it with callbacks
function createTransaction(dbInfo, mode, callback, retries) {
if (retries === undefined) {
retries = 1;
}
try {
var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
callback(null, tx);
} catch (err) {
if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {
return utils_promise.resolve().then(() => {
if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
// increase the db version, to create the new ObjectStore
if (dbInfo.db) {
dbInfo.version = dbInfo.db.version + 1;
}
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
}).then(() => {
return _tryReconnect(dbInfo).then(function () {
createTransaction(dbInfo, mode, callback, retries - 1);
});
}).catch(callback);
}
callback(err);
}
}
function createDbContext() {
return {
// Running localForages sharing a database.
forages: [],
// Shared database.
db: null,
// Database readiness (promise).
dbReady: null,
// Deferred operations on the database.
deferredOperations: []
};
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
// Get the current context of the database;
var dbContext = dbContexts[dbInfo.name];
// ...or create a new context.
if (!dbContext) {
dbContext = createDbContext();
// Register the new context in the global container.
dbContexts[dbInfo.name] = dbContext;
}
// Register itself as a running localForage in the current context.
dbContext.forages.push(self);
// Replace the default `ready()` function with the specialized one.
if (!self._initReady) {
self._initReady = self.ready;
self.ready = _fullyReady;
}
// Create an array of initialization states of the related localForages.
var initPromises = [];
function ignoreErrors() {
// Don't handle errors here,
// just makes sure related localForages aren't pending.
return utils_promise.resolve();
}
for (var j = 0; j < dbContext.forages.length; j++) {
var forage = dbContext.forages[j];
if (forage !== self) {
// Don't wait for itself...
initPromises.push(forage._initReady().catch(ignoreErrors));
}
}
// Take a snapshot of the related localForages.
var forages = dbContext.forages.slice(0);
// Initialize the connection process only when
// all the related localForages aren't pending.
return utils_promise.all(initPromises).then(function () {
dbInfo.db = dbContext.db;
// Get the connection or open a new one without upgrade.
return _getOriginalConnection(dbInfo);
}).then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
}).then(function (db) {
dbInfo.db = dbContext.db = db;
self._dbInfo = dbInfo;
// Share the final connection amongst related localForages.
for (var k = 0; k < forages.length; k++) {
var forage = forages[k];
if (forage !== self) {
// Self is already up-to-date.
forage._dbInfo.db = dbInfo.db;
forage._dbInfo.version = dbInfo.version;
}
}
});
}
function getItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new utils_promise(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function () {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new utils_promise(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function () {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
// when the iterator callback returns any
// (non-`undefined`) value, then we stop
// the iteration immediately
if (result !== void 0) {
resolve(result);
} else {
cursor.continue();
}
} else {
resolve();
}
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
key = normalizeKey(key);
var promise = new utils_promise(function (resolve, reject) {
var dbInfo;
self.ready().then(function () {
dbInfo = self._dbInfo;
if (indexeddb_toString.call(value) === '[object Blob]') {
return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
if (blobSupport) {
return value;
}
return _encodeBlob(value);
});
}
return value;
}).then(function (value) {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
transaction.oncomplete = function () {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new utils_promise(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `.delete()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store.delete(key);
transaction.oncomplete = function () {
resolve();
};
transaction.onerror = function () {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new utils_promise(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function () {
resolve();
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
} catch (e) {
reject(e);
}
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
function indexeddb_length(callback) {
var self = this;
var promise = new utils_promise(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.count();
req.onsuccess = function () {
resolve(req.result);
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new utils_promise(function (resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var advanced = false;
var req = store.openKeyCursor();
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
function indexeddb_keys(callback) {
var self = this;
var promise = new utils_promise(function (resolve, reject) {
self.ready().then(function () {
createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
if (err) {
return reject(err);
}
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var req = store.openKeyCursor();
var keys = [];
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor.continue();
};
req.onerror = function () {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
function dropInstance(options, callback) {
callback = getCallback.apply(this, arguments);
var currentConfig = this.config();
options = typeof options !== 'function' && options || {};
if (!options.name) {
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = utils_promise.reject('Invalid arguments');
} else {
const isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;
const dbPromise = isCurrentDb ? utils_promise.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(db => {
const dbContext = dbContexts[options.name];
const forages = dbContext.forages;
dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
forages[i]._dbInfo.db = db;
}
return db;
});
if (!options.storeName) {
promise = dbPromise.then(db => {
_deferReadiness(options);
const dbContext = dbContexts[options.name];
const forages = dbContext.forages;
db.close();
for (var i = 0; i < forages.length; i++) {
const forage = forages[i];
forage._dbInfo.db = null;
}
const dropDBPromise = new utils_promise((resolve, reject) => {
var req = utils_idb.deleteDatabase(options.name);
req.onerror = () => {
const db = req.result;
if (db) {
db.close();
}
reject(req.error);
};
req.onblocked = () => {
// Closing all open connections in onversionchange handler should prevent this situation, but if
// we do get here, it just means the request remains pending - eventually it will succeed or error
console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed');
};
req.onsuccess = () => {
const db = req.result;
if (db) {
db.close();
}
resolve(db);
};
});
return dropDBPromise.then(db => {
dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
const forage = forages[i];
_advanceReadiness(forage._dbInfo);
}
}).catch(err => {
(_rejectReadiness(options, err) || utils_promise.resolve()).catch(() => {});
throw err;
});
});
} else {
promise = dbPromise.then(db => {
if (!db.objectStoreNames.contains(options.storeName)) {
return;
}
const newVersion = db.version + 1;
_deferReadiness(options);
const dbContext = dbContexts[options.name];
const forages = dbContext.forages;
db.close();
for (let i = 0; i < forages.length; i++) {
const forage = forages[i];
forage._dbInfo.db = null;
forage._dbInfo.version = newVersion;
}
const dropObjectPromise = new utils_promise((resolve, reject) => {
const req = utils_idb.open(options.name, newVersion);
req.onerror = err => {
const db = req.result;
db.close();
reject(err);
};
req.onupgradeneeded = () => {
var db = req.result;
db.deleteObjectStore(options.storeName);
};
req.onsuccess = () => {
const db = req.result;
db.close();
resolve(db);
};
});
return dropObjectPromise.then(db => {
dbContext.db = db;
for (let j = 0; j < forages.length; j++) {
const forage = forages[j];
forage._dbInfo.db = db;
_advanceReadiness(forage._dbInfo);
}
}).catch(err => {
(_rejectReadiness(options, err) || utils_promise.resolve()).catch(() => {});
throw err;
});
});
}
}
utils_executeCallback(promise, callback);
return promise;
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
_support: utils_isIndexedDBValid(),
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: indexeddb_length,
key: key,
keys: indexeddb_keys,
dropInstance: dropInstance
};
/* harmony default export */ const indexeddb = (asyncStorage);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/isWebSQLValid.js
function isWebSQLValid() {
return typeof openDatabase === 'function';
}
/* harmony default export */ const utils_isWebSQLValid = (isWebSQLValid);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/serializer.js
/* eslint-disable no-bitwise */
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
var serializer_toString = Object.prototype.toString;
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i += 4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
/*jslint bitwise: true */
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if (bytes.length % 3 === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serializer_serialize(value, callback) {
var valueType = '';
if (value) {
valueType = serializer_toString.call(value);
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (valueType === '[object ArrayBuffer]' || value.buffer && serializer_toString.call(value.buffer) === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueType === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueType === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueType === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueType === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueType === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueType === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueType === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueType === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueType === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueType === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function () {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ", value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return utils_createBlob([buffer], {
type: blobType
});
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
var localforageSerializer = {
serialize: serializer_serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
/* harmony default export */ const serializer = (localforageSerializer);
;// CONCATENATED MODULE: ./node_modules/localforage/src/drivers/websql.js
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
function createDbTable(t, dbInfo, callback, errorCallback) {
t.executeSql(`CREATE TABLE IF NOT EXISTS ${dbInfo.storeName} ` + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function websql_initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
}
}
var dbInfoPromise = new utils_promise(function (resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
} catch (e) {
return reject(e);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function (t) {
createDbTable(t, dbInfo, function () {
self._dbInfo = dbInfo;
resolve();
}, function (t, error) {
reject(error);
});
}, reject);
});
dbInfo.serializer = serializer;
return dbInfoPromise;
}
function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {
t.executeSql(sqlStatement, args, callback, function (t, error) {
if (error.code === error.SYNTAX_ERR) {
t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [dbInfo.storeName], function (t, results) {
if (!results.rows.length) {
// if the table is missing (was deleted)
// re-create it table and retry
createDbTable(t, dbInfo, function () {
t.executeSql(sqlStatement, args, callback, errorCallback);
}, errorCallback);
} else {
errorCallback(t, error);
}
}, errorCallback);
} else {
errorCallback(t, error);
}
}, errorCallback);
}
function websql_getItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new utils_promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, `SELECT * FROM ${dbInfo.storeName} WHERE key = ? LIMIT 1`, [key], function (t, results) {
var result = results.rows.length ? results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
resolve(result);
}, function (t, error) {
reject(error);
});
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
function websql_iterate(iterator, callback) {
var self = this;
var promise = new utils_promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, `SELECT * FROM ${dbInfo.storeName}`, [], function (t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void 0) {
resolve(result);
return;
}
}
resolve();
}, function (t, error) {
reject(error);
});
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
function _setItem(key, value, callback, retriesLeft) {
var self = this;
key = normalizeKey(key);
var promise = new utils_promise(function (resolve, reject) {
self.ready().then(function () {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, `INSERT OR REPLACE INTO ${dbInfo.storeName} ` + '(key, value) VALUES (?, ?)', [key, value], function () {
resolve(originalValue);
}, function (t, error) {
reject(error);
});
}, function (sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// Try to re-run the transaction.
if (retriesLeft > 0) {
resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));
return;
}
reject(sqlError);
}
});
}
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
function websql_setItem(key, value, callback) {
return _setItem.apply(this, [key, value, callback, 1]);
}
function websql_removeItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new utils_promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, `DELETE FROM ${dbInfo.storeName} WHERE key = ?`, [key], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function websql_clear(callback) {
var self = this;
var promise = new utils_promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, `DELETE FROM ${dbInfo.storeName}`, [], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function websql_length(callback) {
var self = this;
var promise = new utils_promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
// Ahhh, SQL makes this one soooooo easy.
tryExecuteSql(t, dbInfo, `SELECT COUNT(key) as c FROM ${dbInfo.storeName}`, [], function (t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function (t, error) {
reject(error);
});
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function websql_key(n, callback) {
var self = this;
var promise = new utils_promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, `SELECT key FROM ${dbInfo.storeName} WHERE id = ? LIMIT 1`, [n + 1], function (t, results) {
var result = results.rows.length ? results.rows.item(0).key : null;
resolve(result);
}, function (t, error) {
reject(error);
});
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
function websql_keys(callback) {
var self = this;
var promise = new utils_promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
tryExecuteSql(t, dbInfo, `SELECT key FROM ${dbInfo.storeName}`, [], function (t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function (t, error) {
reject(error);
});
});
}).catch(reject);
});
utils_executeCallback(promise, callback);
return promise;
}
// https://www.w3.org/TR/webdatabase/#databases
// > There is no way to enumerate or delete the databases available for an origin from this API.
function getAllStoreNames(db) {
return new utils_promise(function (resolve, reject) {
db.transaction(function (t) {
t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) {
var storeNames = [];
for (var i = 0; i < results.rows.length; i++) {
storeNames.push(results.rows.item(i).name);
}
resolve({
db,
storeNames
});
}, function (t, error) {
reject(error);
});
}, function (sqlError) {
reject(sqlError);
});
});
}
function websql_dropInstance(options, callback) {
callback = getCallback.apply(this, arguments);
var currentConfig = this.config();
options = typeof options !== 'function' && options || {};
if (!options.name) {
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = utils_promise.reject('Invalid arguments');
} else {
promise = new utils_promise(function (resolve) {
var db;
if (options.name === currentConfig.name) {
// use the db reference of the current instance
db = self._dbInfo.db;
} else {
db = openDatabase(options.name, '', '', 0);
}
if (!options.storeName) {
// drop all database tables
resolve(getAllStoreNames(db));
} else {
resolve({
db,
storeNames: [options.storeName]
});
}
}).then(function (operationInfo) {
return new utils_promise(function (resolve, reject) {
operationInfo.db.transaction(function (t) {
function dropTable(storeName) {
return new utils_promise(function (resolve, reject) {
t.executeSql(`DROP TABLE IF EXISTS ${storeName}`, [], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
}
var operations = [];
for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {
operations.push(dropTable(operationInfo.storeNames[i]));
}
utils_promise.all(operations).then(function () {
resolve();
}).catch(function (e) {
reject(e);
});
}, function (sqlError) {
reject(sqlError);
});
});
});
}
utils_executeCallback(promise, callback);
return promise;
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: websql_initStorage,
_support: utils_isWebSQLValid(),
iterate: websql_iterate,
getItem: websql_getItem,
setItem: websql_setItem,
removeItem: websql_removeItem,
clear: websql_clear,
length: websql_length,
key: websql_key,
keys: websql_keys,
dropInstance: websql_dropInstance
};
/* harmony default export */ const websql = (webSQLStorage);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/isLocalStorageValid.js
function isLocalStorageValid() {
try {
return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&
// in IE8 typeof localStorage.setItem === 'object'
!!localStorage.setItem;
} catch (e) {
return false;
}
}
/* harmony default export */ const utils_isLocalStorageValid = (isLocalStorageValid);
;// CONCATENATED MODULE: ./node_modules/localforage/src/drivers/localstorage.js
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).
function _getKeyPrefix(options, defaultConfig) {
var keyPrefix = options.name + '/';
if (options.storeName !== defaultConfig.storeName) {
keyPrefix += options.storeName + '/';
}
return keyPrefix;
}
// Check if localStorage throws when saving an item
function checkIfLocalStorageThrows() {
var localStorageTestKey = '_localforage_support_test';
try {
localStorage.setItem(localStorageTestKey, true);
localStorage.removeItem(localStorageTestKey);
return false;
} catch (e) {
return true;
}
}
// Check if localStorage is usable and allows to save an item
// This method checks if localStorage is usable in Safari Private Browsing
// mode, or in any other case where the available quota for localStorage
// is 0 and there wasn't any saved items yet.
function _isLocalStorageUsable() {
return !checkIfLocalStorageThrows() || localStorage.length > 0;
}
// Config the localStorage backend, using options set in the config.
function localstorage_initStorage(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);
if (!_isLocalStorageUsable()) {
return utils_promise.reject();
}
self._dbInfo = dbInfo;
dbInfo.serializer = serializer;
return utils_promise.resolve();
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function localstorage_clear(callback) {
var self = this;
var promise = self.ready().then(function () {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
utils_executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function localstorage_getItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
return result;
});
utils_executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function localstorage_iterate(iterator, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var keyPrefix = dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
// We use a dedicated iterator instead of the `i` variable below
// so other keys we fetch in localStorage aren't counted in
// the `iterationNumber` argument passed to the `iterate()`
// callback.
//
// See: github.com/mozilla/localForage/pull/435#discussion_r38061530
var iterationNumber = 1;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) !== 0) {
continue;
}
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = dbInfo.serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
if (value !== void 0) {
return value;
}
}
});
utils_executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function localstorage_key(n, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
utils_executeCallback(promise, callback);
return promise;
}
function localstorage_keys(callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
var itemKey = localStorage.key(i);
if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
keys.push(itemKey.substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
utils_executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function localstorage_length(callback) {
var self = this;
var promise = self.keys().then(function (keys) {
return keys.length;
});
utils_executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function localstorage_removeItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
utils_executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function localstorage_setItem(key, value, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function () {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new utils_promise(function (resolve, reject) {
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
try {
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
utils_executeCallback(promise, callback);
return promise;
}
function localstorage_dropInstance(options, callback) {
callback = getCallback.apply(this, arguments);
options = typeof options !== 'function' && options || {};
if (!options.name) {
var currentConfig = this.config();
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) {
promise = utils_promise.reject('Invalid arguments');
} else {
promise = new utils_promise(function (resolve) {
if (!options.storeName) {
resolve(`${options.name}/`);
} else {
resolve(_getKeyPrefix(options, self._defaultConfig));
}
}).then(function (keyPrefix) {
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
}
utils_executeCallback(promise, callback);
return promise;
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: localstorage_initStorage,
_support: utils_isLocalStorageValid(),
iterate: localstorage_iterate,
getItem: localstorage_getItem,
setItem: localstorage_setItem,
removeItem: localstorage_removeItem,
clear: localstorage_clear,
length: localstorage_length,
key: localstorage_key,
keys: localstorage_keys,
dropInstance: localstorage_dropInstance
};
/* harmony default export */ const localstorage = (localStorageWrapper);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/includes.js
const sameValue = (x, y) => x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);
const includes = (array, searchElement) => {
const len = array.length;
let i = 0;
while (i < len) {
if (sameValue(array[i], searchElement)) {
return true;
}
i++;
}
return false;
};
/* harmony default export */ const utils_includes = (includes);
;// CONCATENATED MODULE: ./node_modules/localforage/src/utils/isArray.js
const isArray_isArray = Array.isArray || function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
/* harmony default export */ const utils_isArray = (isArray_isArray);
;// CONCATENATED MODULE: ./node_modules/localforage/src/localforage.js
// Drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
const DefinedDrivers = {};
const DriverSupport = {};
const DefaultDrivers = {
INDEXEDDB: indexeddb,
WEBSQL: websql,
LOCALSTORAGE: localstorage
};
const DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];
const OptionalDriverMethods = ['dropInstance'];
const LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);
const DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function () {
const _args = arguments;
return localForageInstance.ready().then(function () {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (let i = 1; i < arguments.length; i++) {
const arg = arguments[i];
if (arg) {
for (let key in arg) {
if (arg.hasOwnProperty(key)) {
if (utils_isArray(arg[key])) {
arguments[0][key] = arg[key].slice();
} else {
arguments[0][key] = arg[key];
}
}
}
}
}
return arguments[0];
}
class LocalForage {
constructor(options) {
for (let driverTypeKey in DefaultDrivers) {
if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
const driver = DefaultDrivers[driverTypeKey];
const driverName = driver._driver;
this[driverTypeKey] = driverName;
if (!DefinedDrivers[driverName]) {
// we don't need to wait for the promise,
// since the default drivers can be defined
// in a blocking manner
this.defineDriver(driver);
}
}
}
this._defaultConfig = extend({}, DefaultConfig);
this._config = extend({}, this._defaultConfig, options);
this._driverSet = null;
this._initDriver = null;
this._ready = false;
this._dbInfo = null;
this._wrapLibraryMethodsWithReady();
this.setDriver(this._config.driver).catch(() => {});
}
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
config(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if (typeof options === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " + 'has been used.');
}
for (let i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
if (i === 'version' && typeof options[i] !== 'number') {
return new Error('Database version must be a number.');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
return this.setDriver(this._config.driver);
}
return true;
} else if (typeof options === 'string') {
return this._config[options];
} else {
return this._config;
}
}
// Used to define a custom driver, shared across all instances of
// localForage.
defineDriver(driverObject, callback, errorCallback) {
const promise = new utils_promise(function (resolve, reject) {
try {
const driverName = driverObject._driver;
const complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
const driverMethods = LibraryMethods.concat('_initStorage');
for (let i = 0, len = driverMethods.length; i < len; i++) {
const driverMethodName = driverMethods[i];
// when the property is there,
// it should be a method even when optional
const isRequired = !utils_includes(OptionalDriverMethods, driverMethodName);
if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {
reject(complianceError);
return;
}
}
const configureMissingMethods = function () {
const methodNotImplementedFactory = function (methodName) {
return function () {
const error = new Error(`Method ${methodName} is not implemented by the current driver`);
const promise = utils_promise.reject(error);
utils_executeCallback(promise, arguments[arguments.length - 1]);
return promise;
};
};
for (let i = 0, len = OptionalDriverMethods.length; i < len; i++) {
const optionalDriverMethod = OptionalDriverMethods[i];
if (!driverObject[optionalDriverMethod]) {
driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
}
}
};
configureMissingMethods();
const setDriverSupport = function (support) {
if (DefinedDrivers[driverName]) {
console.info(`Redefining LocalForage driver: ${driverName}`);
}
DefinedDrivers[driverName] = driverObject;
DriverSupport[driverName] = support;
// don't use a then, so that we can define
// drivers that have simple _support methods
// in a blocking manner
resolve();
};
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
driverObject._support().then(setDriverSupport, reject);
} else {
setDriverSupport(!!driverObject._support);
}
} else {
setDriverSupport(true);
}
} catch (e) {
reject(e);
}
});
utils_executeTwoCallbacks(promise, callback, errorCallback);
return promise;
}
driver() {
return this._driver || null;
}
getDriver(driverName, callback, errorCallback) {
const getDriverPromise = DefinedDrivers[driverName] ? utils_promise.resolve(DefinedDrivers[driverName]) : utils_promise.reject(new Error('Driver not found.'));
utils_executeTwoCallbacks(getDriverPromise, callback, errorCallback);
return getDriverPromise;
}
getSerializer(callback) {
const serializerPromise = utils_promise.resolve(serializer);
utils_executeTwoCallbacks(serializerPromise, callback);
return serializerPromise;
}
ready(callback) {
const self = this;
const promise = self._driverSet.then(() => {
if (self._ready === null) {
self._ready = self._initDriver();
}
return self._ready;
});
utils_executeTwoCallbacks(promise, callback, callback);
return promise;
}
setDriver(drivers, callback, errorCallback) {
const self = this;
if (!utils_isArray(drivers)) {
drivers = [drivers];
}
const supportedDrivers = this._getSupportedDrivers(drivers);
function setDriverToConfig() {
self._config.driver = self.driver();
}
function extendSelfWithDriver(driver) {
self._extend(driver);
setDriverToConfig();
self._ready = self._initStorage(self._config);
return self._ready;
}
function initDriver(supportedDrivers) {
return function () {
let currentDriverIndex = 0;
function driverPromiseLoop() {
while (currentDriverIndex < supportedDrivers.length) {
let driverName = supportedDrivers[currentDriverIndex];
currentDriverIndex++;
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(extendSelfWithDriver).catch(driverPromiseLoop);
}
setDriverToConfig();
const error = new Error('No available storage method found.');
self._driverSet = utils_promise.reject(error);
return self._driverSet;
}
return driverPromiseLoop();
};
}
// There might be a driver initialization in progress
// so wait for it to finish in order to avoid a possible
// race condition to set _dbInfo
const oldDriverSetDone = this._driverSet !== null ? this._driverSet.catch(() => utils_promise.resolve()) : utils_promise.resolve();
this._driverSet = oldDriverSetDone.then(() => {
const driverName = supportedDrivers[0];
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(driver => {
self._driver = driver._driver;
setDriverToConfig();
self._wrapLibraryMethodsWithReady();
self._initDriver = initDriver(supportedDrivers);
});
}).catch(() => {
setDriverToConfig();
const error = new Error('No available storage method found.');
self._driverSet = utils_promise.reject(error);
return self._driverSet;
});
utils_executeTwoCallbacks(this._driverSet, callback, errorCallback);
return this._driverSet;
}
supports(driverName) {
return !!DriverSupport[driverName];
}
_extend(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
}
_getSupportedDrivers(drivers) {
const supportedDrivers = [];
for (let i = 0, len = drivers.length; i < len; i++) {
const driverName = drivers[i];
if (this.supports(driverName)) {
supportedDrivers.push(driverName);
}
}
return supportedDrivers;
}
_wrapLibraryMethodsWithReady() {
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (let i = 0, len = LibraryMethods.length; i < len; i++) {
callWhenReady(this, LibraryMethods[i]);
}
}
createInstance(options) {
return new LocalForage(options);
}
}
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
/* harmony default export */ const localforage = (new LocalForage());
;// CONCATENATED MODULE: ./node_modules/lodash-es/_assignMergeValue.js
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !lodash_es_eq(object[key], value)) ||
(value === undefined && !(key in object))) {
_baseAssignValue(object, key, value);
}
}
/* harmony default export */ const _assignMergeValue = (assignMergeValue);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isArrayLikeObject.js
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return lodash_es_isObjectLike(value) && lodash_es_isArrayLike(value);
}
/* harmony default export */ const lodash_es_isArrayLikeObject = (isArrayLikeObject);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_safeGet.js
/**
* Gets the value at `key`, unless `key` is "__proto__" or "constructor".
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function safeGet(object, key) {
if (key === 'constructor' && typeof object[key] === 'function') {
return;
}
if (key == '__proto__') {
return;
}
return object[key];
}
/* harmony default export */ const _safeGet = (safeGet);
;// CONCATENATED MODULE: ./node_modules/lodash-es/toPlainObject.js
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return _copyObject(value, lodash_es_keysIn(value));
}
/* harmony default export */ const lodash_es_toPlainObject = (toPlainObject);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseMergeDeep.js
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = _safeGet(object, key),
srcValue = _safeGet(source, key),
stacked = stack.get(srcValue);
if (stacked) {
_assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = lodash_es_isArray(srcValue),
isBuff = !isArr && lodash_es_isBuffer(srcValue),
isTyped = !isArr && !isBuff && lodash_es_isTypedArray(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (lodash_es_isArray(objValue)) {
newValue = objValue;
}
else if (lodash_es_isArrayLikeObject(objValue)) {
newValue = _copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = _cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = _cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (lodash_es_isPlainObject(srcValue) || lodash_es_isArguments(srcValue)) {
newValue = objValue;
if (lodash_es_isArguments(objValue)) {
newValue = lodash_es_toPlainObject(objValue);
}
else if (!lodash_es_isObject(objValue) || lodash_es_isFunction(objValue)) {
newValue = _initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
_assignMergeValue(object, key, newValue);
}
/* harmony default export */ const _baseMergeDeep = (baseMergeDeep);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseMerge.js
/**
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMerge(object, source, srcIndex, customizer, stack) {
if (object === source) {
return;
}
_baseFor(source, function(srcValue, key) {
stack || (stack = new _Stack);
if (lodash_es_isObject(srcValue)) {
_baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(_safeGet(object, key), srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
_assignMergeValue(object, key, newValue);
}
}, lodash_es_keysIn);
}
/* harmony default export */ const _baseMerge = (baseMerge);
;// CONCATENATED MODULE: ./node_modules/lodash-es/merge.js
/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/
var merge = _createAssigner(function(object, source, srcIndex) {
_baseMerge(object, source, srcIndex);
});
/* harmony default export */ const lodash_es_merge = (merge);
;// CONCATENATED MODULE: ./node_modules/lodash-es/mergeWith.js
/**
* This method is like `_.merge` except that it accepts `customizer` which
* is invoked to produce the merged values of the destination and source
* properties. If `customizer` returns `undefined`, merging is handled by the
* method instead. The `customizer` is invoked with six arguments:
* (objValue, srcValue, key, object, source, stack).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} customizer The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* function customizer(objValue, srcValue) {
* if (_.isArray(objValue)) {
* return objValue.concat(srcValue);
* }
* }
*
* var object = { 'a': [1], 'b': [2] };
* var other = { 'a': [3], 'b': [4] };
*
* _.mergeWith(object, other, customizer);
* // => { 'a': [1, 3], 'b': [2, 4] }
*/
var mergeWith = _createAssigner(function(object, source, srcIndex, customizer) {
_baseMerge(object, source, srcIndex, customizer);
});
/* harmony default export */ const lodash_es_mergeWith = (mergeWith);
;// CONCATENATED MODULE: ./node_modules/lodash-es/now.js
/**
* Gets the timestamp of the number of milliseconds that have elapsed since
* the Unix epoch (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Date
* @returns {number} Returns the timestamp.
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => Logs the number of milliseconds it took for the deferred invocation.
*/
var now = function() {
return _root.Date.now();
};
/* harmony default export */ const lodash_es_now = (now);
;// CONCATENATED MODULE: ./node_modules/mergebounce/mergebounce.js
/** Error message constants. */
const mergebounce_FUNC_ERROR_TEXT = 'Expected a function';
/* Built-in method references for those with the same name as other `lodash` methods. */
const mergebounce_nativeMax = Math.max;
const nativeMin = Math.min;
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
*
* This function differs from lodash's debounce by merging all passed objects
* before passing them to the final invoked function.
*
* Because of this, invoking can only happen on the trailing edge, since
* passed-in data would be discarded if invoking happened on the leading edge.
*
* If `wait` is `0`, `func` invocation is deferred until to the next tick,
* similar to `setTimeout` with a timeout of `0`.
*
* @static
* @category Function
* @param {Function} func The function to mergebounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.concatArrays=false]
* By default arrays will be treated as objects when being merged. When
* merging two arrays, the values in the 2nd arrray will replace the
* corresponding values (i.e. those with the same indexes) in the first array.
* When `concatArrays` is set to `true`, arrays will be concatenated instead.
* @param {boolean} [options.dedupeArrays=false]
* This option is similar to `concatArrays`, except that the concatenated
* array will also be deduplicated. Thus any entries that are concatenated to the
* existing array, which are already contained in the existing array, will
* first be removed.
* @param {boolean} [options.promise=false]
* By default, when calling a merge-debounced function that doesn't execute
* immediately, you'll receive the result from its previous execution, or
* `undefined` if it has never executed before. By setting the `promise`
* option to `true`, a promise will be returned instead of the previous
* execution result when the function is debounced. The promise will resolve
* with the result of the next execution, as soon as it happens.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* window.addEventListener('resize', mergebounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* element.addEventListner('click', mergebounce(sendMail, 300));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* const mergebounced = mergebounce(batchLog, 250, { 'maxWait': 1000 });
* const source = new EventSource('/stream');
* jQuery(source).on('message', mergebounced);
*
* // Cancel the trailing debounced invocation.
* window.addEventListener('popstate', mergebounced.cancel);
*/
function mergebounce(func, wait) {
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
let lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
maxing = false;
let promise = options.promise ? getOpenPromise() : null;
if (typeof func != 'function') {
throw new TypeError(mergebounce_FUNC_ERROR_TEXT);
}
wait = lodash_es_toNumber(wait) || 0;
if (lodash_es_isObject(options)) {
maxing = 'maxWait' in options;
maxWait = maxing ? mergebounce_nativeMax(lodash_es_toNumber(options.maxWait) || 0, wait) : maxWait;
}
function invokeFunc(time) {
const args = lastArgs;
const thisArg = lastThis;
const existingPromise = promise;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
if (options.promise) {
existingPromise.resolve(result);
promise = getOpenPromise();
}
return options.promise ? existingPromise : result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
return options.promise ? promise : result;
}
function remainingWait(time) {
const timeSinceLastCall = time - lastCallTime;
const timeSinceLastInvoke = time - lastInvokeTime;
const timeWaiting = wait - timeSinceLastCall;
return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
}
function shouldInvoke(time) {
const timeSinceLastCall = time - lastCallTime;
const timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
}
function timerExpired() {
const time = lodash_es_now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return options.promise ? promise : result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(lodash_es_now());
}
function concatArrays(objValue, srcValue) {
if (Array.isArray(objValue) && Array.isArray(srcValue)) {
if (options?.dedupeArrays) {
return objValue.concat(srcValue.filter(i => objValue.indexOf(i) === -1));
} else {
return objValue.concat(srcValue);
}
}
}
function mergeArguments(args) {
if (lastArgs?.length) {
if (!args.length) {
return lastArgs;
}
if (options?.concatArrays || options?.dedupeArrays) {
return lodash_es_mergeWith(lastArgs, args, concatArrays);
} else {
return lodash_es_merge(lastArgs, args);
}
} else {
return args || [];
}
}
function debounced() {
const time = lodash_es_now();
const isInvoking = shouldInvoke(time);
lastArgs = mergeArguments(Array.from(arguments));
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
clearTimeout(timerId);
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return options.promise ? promise : result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
/* harmony default export */ const mergebounce_mergebounce = (mergebounce);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/drivers/sessionStorage.js
// Copyright 2014 Mozilla
// Copyright 2015 Thodoris Greasidis
// Copyright 2018 JC Brand
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const sessionStorage_serialize = serializer["serialize"];
const sessionStorage_deserialize = serializer["deserialize"];
function isSessionStorageValid() {
// If the app is running inside a Google Chrome packaged webapp, or some
// other context where sessionStorage isn't available, we don't use
// sessionStorage. This feature detection is preferred over the old
// `if (window.chrome && window.chrome.runtime)` code.
// See: https://github.com/mozilla/localForage/issues/68
try {
// If sessionStorage isn't available, we get outta here!
// This should be inside a try catch
if (sessionStorage && 'setItem' in sessionStorage) {
return true;
}
} catch (e) {
console.log(e);
}
return false;
}
function sessionStorage_getKeyPrefix(options, defaultConfig) {
let keyPrefix = options.name + '/';
if (options.storeName !== defaultConfig.storeName) {
keyPrefix += options.storeName + '/';
}
return keyPrefix;
}
const dbInfo = {
'serializer': {
'serialize': sessionStorage_serialize,
'deserialize': sessionStorage_deserialize
}
};
function sessionStorage_initStorage(options) {
dbInfo.keyPrefix = sessionStorage_getKeyPrefix(options, this._defaultConfig);
if (options) {
for (const i in options) {
// eslint-disable-line guard-for-in
dbInfo[i] = options[i];
}
}
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function sessionStorage_clear(callback) {
const promise = this.ready().then(function () {
const keyPrefix = dbInfo.keyPrefix;
for (let i = sessionStorage.length - 1; i >= 0; i--) {
const key = sessionStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
sessionStorage.removeItem(key);
}
}
});
utils_executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function sessionStorage_getItem(key, callback) {
key = normalizeKey(key);
const promise = this.ready().then(function () {
let result = sessionStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
return result;
});
utils_executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function sessionStorage_iterate(iterator, callback) {
const self = this;
const promise = self.ready().then(function () {
const keyPrefix = dbInfo.keyPrefix;
const keyPrefixLength = keyPrefix.length;
const length = sessionStorage.length;
// We use a dedicated iterator instead of the `i` variable below
// so other keys we fetch in sessionStorage aren't counted in
// the `iterationNumber` argument passed to the `iterate()`
// callback.
//
// See: github.com/mozilla/localForage/pull/435#discussion_r38061530
let iterationNumber = 1;
for (let i = 0; i < length; i++) {
const key = sessionStorage.key(i);
if (key.indexOf(keyPrefix) !== 0) {
continue;
}
let value = sessionStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = dbInfo.serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
if (value !== void 0) {
// eslint-disable-line no-void
return value;
}
}
});
utils_executeCallback(promise, callback);
return promise;
}
// Same as sessionStorage's key() method, except takes a callback.
function sessionStorage_key(n, callback) {
const self = this;
const promise = self.ready().then(function () {
let result;
try {
result = sessionStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
utils_executeCallback(promise, callback);
return promise;
}
function sessionStorage_keys(callback) {
const self = this;
const promise = self.ready().then(function () {
const length = sessionStorage.length;
const keys = [];
for (let i = 0; i < length; i++) {
const itemKey = sessionStorage.key(i);
if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
keys.push(itemKey.substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
utils_executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function sessionStorage_length(callback) {
const self = this;
const promise = self.keys().then(function (keys) {
return keys.length;
});
utils_executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function sessionStorage_removeItem(key, callback) {
key = normalizeKey(key);
const promise = this.ready().then(function () {
sessionStorage.removeItem(dbInfo.keyPrefix + key);
});
utils_executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
async function sessionStorage_setItem(key, value, callback) {
key = normalizeKey(key);
await this.ready();
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
value = value ?? null;
// Save the original value to pass to the callback.
const originalValue = value;
dbInfo.serializer.serialize(value, (value, error) => {
if (error) {
throw error;
} else {
try {
sessionStorage.setItem(dbInfo.keyPrefix + key, value);
utils_executeCallback(Promise.resolve(originalValue), callback);
} catch (e) {
if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
console.error("Your sesionStorage capacity is used up.");
throw e;
}
throw e;
}
}
});
}
function sessionStorage_dropInstance(options, callback) {
callback = getCallback.apply(this, arguments);
options = typeof options !== 'function' && options || {};
if (!options.name) {
const currentConfig = this.config();
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
const self = this;
let promise;
if (!options.name) {
promise = Promise.reject(new Error('Invalid arguments'));
} else {
promise = new Promise(function (resolve) {
if (!options.storeName) {
resolve(`${options.name}/`);
} else {
resolve(sessionStorage_getKeyPrefix(options, self._defaultConfig));
}
}).then(function (keyPrefix) {
for (let i = sessionStorage.length - 1; i >= 0; i--) {
const key = sessionStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
sessionStorage.removeItem(key);
}
}
});
}
utils_executeCallback(promise, callback);
return promise;
}
const sessionStorageWrapper = {
_driver: 'sessionStorageWrapper',
_initStorage: sessionStorage_initStorage,
_support: isSessionStorageValid(),
iterate: sessionStorage_iterate,
getItem: sessionStorage_getItem,
setItem: sessionStorage_setItem,
removeItem: sessionStorage_removeItem,
clear: sessionStorage_clear,
length: sessionStorage_length,
key: sessionStorage_key,
keys: sessionStorage_keys,
dropInstance: sessionStorage_dropInstance
};
/* harmony default export */ const drivers_sessionStorage = (sessionStorageWrapper);
// EXTERNAL MODULE: ./node_modules/localforage-setitems/dist/localforage-setitems.js
var localforage_setitems = __webpack_require__(459);
// EXTERNAL MODULE: ./node_modules/@converse/localforage-getitems/dist/localforage-getitems.js
var localforage_getitems = __webpack_require__(487);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/storage.js
/**
* IndexedDB, localStorage and sessionStorage adapter
*/
const IN_MEMORY = umd._driver;
localforage.defineDriver(umd);
(0,localforage_setitems.extendPrototype)(localforage);
(0,localforage_getitems.extendPrototype)(localforage);
class Storage {
constructor(id, type) {
let batchedWrites = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (type === 'local' && !window.localStorage) {
throw new Error("Skeletor.storage: Environment does not support localStorage.");
} else if (type === 'session' && !window.sessionStorage) {
throw new Error("Skeletor.storage: Environment does not support sessionStorage.");
}
if (lodash_es_isString(type)) {
this.storeInitialized = this.initStore(type, batchedWrites);
} else {
this.store = type;
if (batchedWrites) {
this.store.debouncedSetItems = mergebounce_mergebounce(items => this.store.setItems(items), 50, {
'promise': true
});
}
this.storeInitialized = Promise.resolve();
}
this.name = id;
}
async initStore(type, batchedWrites) {
if (type === 'session') {
localforage.setDriver(drivers_sessionStorage._driver);
} else if (type === 'local') {
await localforage.config({
'driver': localforage.LOCALSTORAGE
});
} else if (type === 'in_memory') {
localforage.config({
'driver': IN_MEMORY
});
} else if (type !== 'indexed') {
throw new Error("Skeletor.storage: No storage type was specified");
}
this.store = localforage;
if (batchedWrites) {
this.store.debouncedSetItems = mergebounce_mergebounce(items => this.store.setItems(items), 50, {
'promise': true
});
}
}
flush() {
return this.store.debouncedSetItems?.flush();
}
async clear() {
await this.store.removeItem(this.name).catch(e => console.error(e));
const re = new RegExp(`^${this.name}-`);
const keys = await this.store.keys();
const removed_keys = keys.filter(k => re.test(k));
await Promise.all(removed_keys.map(k => this.store.removeItem(k).catch(e => console.error(e))));
}
sync() {
const that = this;
async function localSync(method, model, options) {
let resp, errorMessage, promise, new_attributes;
// We get the collection (and if necessary the model attribute.
// Waiting for storeInitialized will cause another iteration of
// the event loop, after which the collection reference will
// be removed from the model.
const collection = model.collection;
if (['patch', 'update'].includes(method)) {
new_attributes = lodash_es_cloneDeep(model.attributes);
}
await that.storeInitialized;
try {
const original_attributes = model.attributes;
switch (method) {
case "read":
if (model.id !== undefined) {
resp = await that.find(model);
} else {
resp = await that.findAll();
}
break;
case "create":
resp = await that.create(model, options);
break;
case 'patch':
case "update":
if (options.wait) {
// When `wait` is set to true, Skeletor waits until
// confirmation of storage before setting the values on
// the model.
// However, the new attributes needs to be sent, so it
// sets them manually on the model and then removes
// them after calling `sync`.
// Because our `sync` method is asynchronous and we
// wait for `storeInitialized`, the attributes are
// already restored once we get here, so we need to do
// the attributes dance again.
model.attributes = new_attributes;
}
promise = that.update(model, options);
if (options.wait) {
model.attributes = original_attributes;
}
resp = await promise;
break;
case "delete":
resp = await that.destroy(model, collection);
break;
}
} catch (error) {
if (error.code === 22 && that.getStorageSize() === 0) {
errorMessage = "Private browsing is unsupported";
} else {
errorMessage = error.message;
}
}
if (resp) {
if (options && options.success) {
// When storing, we don't pass back the response (which is
// the set attributes returned from localforage because
// Skeletor sets them again on the model and due to the async
// nature of localforage it can cause stale attributes to be
// set on a model after it's been updated in the meantime.
const data = method === "read" ? resp : null;
options.success(data, options);
}
} else {
errorMessage = errorMessage ? errorMessage : "Record Not Found";
if (options && options.error) {
options.error(errorMessage);
}
}
}
localSync.__name__ = 'localSync';
return localSync;
}
removeCollectionReference(model, collection) {
if (!collection) {
return;
}
const ids = collection.filter(m => m.id !== model.id).map(m => this.getItemName(m.id));
return this.store.setItem(this.name, ids);
}
addCollectionReference(model, collection) {
if (!collection) {
return;
}
const ids = collection.map(m => this.getItemName(m.id));
const new_id = this.getItemName(model.id);
if (!ids.includes(new_id)) {
ids.push(new_id);
}
return this.store.setItem(this.name, ids);
}
getCollectionReferenceData(model) {
if (!model.collection) {
return {};
}
const ids = model.collection.map(m => this.getItemName(m.id));
const new_id = this.getItemName(model.id);
if (!ids.includes(new_id)) {
ids.push(new_id);
}
const result = {};
result[this.name] = ids;
return result;
}
async save(model) {
if (this.store.setItems) {
const items = {};
items[this.getItemName(model.id)] = model.toJSON();
Object.assign(items, this.getCollectionReferenceData(model));
return this.store.debouncedSetItems ? this.store.debouncedSetItems(items) : this.store.setItems(items);
} else {
const key = this.getItemName(model.id);
const data = await this.store.setItem(key, model.toJSON());
await this.addCollectionReference(model, model.collection);
return data;
}
}
create(model, options) {
/* Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
* have an id of it's own.
*/
if (!model.id) {
model.id = guid();
model.set(model.idAttribute, model.id, options);
}
return this.save(model);
}
update(model) {
return this.save(model);
}
find(model) {
return this.store.getItem(this.getItemName(model.id));
}
async findAll() {
/* Return the array of all models currently in storage.
*/
const keys = await this.store.getItem(this.name);
if (keys?.length) {
const items = await this.store.getItems(keys);
return Object.values(items);
}
return [];
}
async destroy(model, collection) {
await this.flush();
await this.store.removeItem(this.getItemName(model.id));
await this.removeCollectionReference(model, collection);
return model;
}
getStorageSize() {
return this.store.length;
}
getItemName(id) {
return this.name + "-" + id;
}
}
Storage.sessionStorageInitialized = localforage.defineDriver(drivers_sessionStorage);
Storage.localForage = localforage;
/* harmony default export */ const storage = (Storage);
;// CONCATENATED MODULE: ./src/headless/utils/storage.js
function getDefaultStore() {
if (shared_converse.config.get('trusted')) {
const is_non_persistent = shared_api.settings.get('persistent_store') === 'sessionStorage';
return is_non_persistent ? 'session' : 'persistent';
} else {
return 'session';
}
}
function storeUsesIndexedDB(store) {
return store === 'persistent' && shared_api.settings.get('persistent_store') === 'IndexedDB';
}
function createStore(id, store) {
const name = store || getDefaultStore();
const s = shared_converse.storage[name];
if (typeof s === 'undefined') {
throw new TypeError(`createStore: Could not find store for ${id}`);
}
return new storage(id, s, storeUsesIndexedDB(store));
}
function initStorage(model, id, type) {
const store = type || getDefaultStore();
model.browserStorage = createStore(id, store);
if (storeUsesIndexedDB(store)) {
const flush = () => model.browserStorage.flush();
window.addEventListener(shared_converse.unloadevent, flush);
model.on('destroy', () => window.removeEventListener(shared_converse.unloadevent, flush));
model.listenTo(shared_converse, 'beforeLogout', flush);
}
}
;// CONCATENATED MODULE: ./src/headless/shared/settings/utils.js
let app_settings;
let init_settings = {}; // Container for settings passed in via converse.initialize
let user_settings; // User settings, populated via api.users.settings
function getAppSettings() {
return app_settings;
}
function initAppSettings(settings) {
init_settings = settings;
app_settings = {};
Object.assign(app_settings, Events);
// Allow only whitelisted settings to be overwritten via converse.initialize
const allowed_settings = lodash_es_pick(settings, Object.keys(DEFAULT_SETTINGS));
lodash_es_assignIn(app_settings, DEFAULT_SETTINGS, allowed_settings);
}
function getInitSettings() {
return init_settings;
}
function getAppSetting(key) {
if (Object.keys(DEFAULT_SETTINGS).includes(key)) {
return app_settings[key];
}
}
function extendAppSettings(settings) {
utils_core.merge(DEFAULT_SETTINGS, settings);
// When updating the settings, we need to avoid overwriting the
// initialization_settings (i.e. the settings passed in via converse.initialize).
const allowed_keys = Object.keys(lodash_es_pick(settings, Object.keys(DEFAULT_SETTINGS)));
const allowed_site_settings = lodash_es_pick(init_settings, allowed_keys);
const updated_settings = lodash_es_assignIn(lodash_es_pick(settings, allowed_keys), allowed_site_settings);
utils_core.merge(app_settings, updated_settings);
}
function registerListener(name, func, context) {
app_settings.on(name, func, context);
}
function unregisterListener(name, func) {
app_settings.off(name, func);
}
function updateAppSettings(key, val) {
if (key == null) return this; // eslint-disable-line no-eq-null
let attrs;
if (lodash_es_isObject(key)) {
attrs = key;
} else if (typeof key === 'string') {
attrs = {};
attrs[key] = val;
}
const allowed_keys = Object.keys(lodash_es_pick(attrs, Object.keys(DEFAULT_SETTINGS)));
const changed = {};
allowed_keys.forEach(k => {
const val = attrs[k];
if (!lodash_es_isEqual(app_settings[k], val)) {
changed[k] = val;
app_settings[k] = val;
}
});
Object.keys(changed).forEach(k => app_settings.trigger('change:' + k, changed[k]));
app_settings.trigger('change', changed);
}
/**
* @async
*/
function initUserSettings() {
if (!shared_converse.bare_jid) {
const msg = "No JID to fetch user settings for";
log.error(msg);
throw Error(msg);
}
if (!user_settings?.fetched) {
const id = `converse.user-settings.${shared_converse.bare_jid}`;
user_settings = new Model({
id
});
initStorage(user_settings, id);
user_settings.fetched = user_settings.fetch({
'promise': true
});
}
return user_settings.fetched;
}
async function getUserSettings() {
await initUserSettings();
return user_settings;
}
async function updateUserSettings(data, options) {
await initUserSettings();
return user_settings.save(data, options);
}
async function clearUserSettings() {
await initUserSettings();
return user_settings.clear();
}
;// CONCATENATED MODULE: ./src/headless/shared/settings/api.js
/**
* This grouping allows access to the
* [configuration settings](/docs/html/configuration.html#configuration-settings)
* of Converse.
*
* @namespace _converse.api.settings
* @memberOf _converse.api
*/
const settings_api = {
/**
* Allows new configuration settings to be specified, or new default values for
* existing configuration settings to be specified.
*
* Note, calling this method *after* converse.initialize has been
* called will *not* change the initialization settings provided via
* `converse.initialize`.
*
* @method _converse.api.settings.extend
* @param { object } settings The configuration settings
* @example
* _converse.api.settings.extend({
* 'enable_foo': true
* });
*
* // The user can then override the default value of the configuration setting when
* // calling `converse.initialize`.
* converse.initialize({
* 'enable_foo': false
* });
*/
extend(settings) {
return extendAppSettings(settings);
},
update(settings) {
log.warn('The api.settings.update method has been deprecated and will be removed. ' + 'Please use api.settings.extend instead.');
return this.extend(settings);
},
/**
* @method _converse.api.settings.get
* @returns {*} Value of the particular configuration setting.
* @example _converse.api.settings.get("play_sounds");
*/
get(key) {
return getAppSetting(key);
},
/**
* Set one or many configuration settings.
*
* Note, this is not an alternative to calling {@link converse.initialize}, which still needs
* to be called. Generally, you'd use this method after Converse is already
* running and you want to change the configuration on-the-fly.
*
* @method _converse.api.settings.set
* @param { Object | string } [settings_or_key]
* An object containing configuration settings.
* Alternatively to passing in an object, you can pass in a key and a value.
* @param { string } [value]
* @example _converse.api.settings.set("play_sounds", true);
* @example
* _converse.api.settings.set({
* "play_sounds": true,
* "hide_offline_users": true
* });
*/
set(settings_or_key, value) {
updateAppSettings(settings_or_key, value);
},
/**
* The `listen` namespace exposes methods for creating event listeners
* (aka handlers) for events related to settings.
*
* @namespace _converse.api.settings.listen
* @memberOf _converse.api.settings
*/
listen: {
/**
* Register an event listener for the passed in event.
* @method _converse.api.settings.listen.on
* @param { ('change') } name - The name of the event to listen for.
* Currently there is only the 'change' event.
* @param { Function } handler - The event handler function
* @param { Object } [context] - The context of the `this` attribute of the
* handler function.
* @example _converse.api.settings.listen.on('change', callback);
*/
on(name, handler, context) {
registerListener(name, handler, context);
},
/**
* To stop listening to an event, you can use the `not` method.
* @method _converse.api.settings.listen.not
* @param { String } name The event's name
* @param { Function } handler The callback method that is to no longer be called when the event fires
* @example _converse.api.settings.listen.not('change', callback);
*/
not(name, handler) {
unregisterListener(name, handler);
}
}
};
/**
* API for accessing and setting user settings. User settings are
* different from the application settings from {@link _converse.api.settings}
* because they are per-user and set via user action.
* @namespace _converse.api.user.settings
* @memberOf _converse.api.user
*/
const user_settings_api = {
/**
* Returns the user settings model. Useful when you want to listen for change events.
* @async
* @method _converse.api.user.settings.getModel
* @returns {Promise<Model>}
* @example const settings = await _converse.api.user.settings.getModel();
*/
getModel() {
return getUserSettings();
},
/**
* Get the value of a particular user setting.
* @method _converse.api.user.settings.get
* @param { String } key - The setting name
* @param {*} [fallback] - An optional fallback value if the user setting is undefined
* @returns {Promise} Promise which resolves with the value of the particular configuration setting.
* @example _converse.api.user.settings.get("foo");
*/
async get(key, fallback) {
const user_settings = await getUserSettings();
return user_settings.get(key) === undefined ? fallback : user_settings.get(key);
},
/**
* Set one or many user settings.
* @async
* @method _converse.api.user.settings.set
* @param { Object } [settings] An object containing configuration settings.
* @param { string } [key] Alternatively to passing in an object, you can pass in a key and a value.
* @param { string } [value]
* @example _converse.api.user.settings.set("foo", "bar");
* @example
* _converse.api.user.settings.set({
* "foo": "bar",
* "baz": "buz"
* });
*/
set(key, val) {
if (lodash_es_isObject(key)) {
return updateUserSettings(key, {
'promise': true
});
} else {
const o = {};
o[key] = val;
return updateUserSettings(o, {
'promise': true
});
}
},
/**
* Clears all the user settings
* @async
* @method _converse.api.user.settings.clear
*/
clear() {
return clearUserSettings();
}
};
;// CONCATENATED MODULE: ./src/headless/utils/stanza.js
const stanza_PARSE_ERROR_NS = 'http://www.w3.org/1999/xhtml';
function stanza_toStanza(string, throwErrorIfInvalidNS) {
const doc = core.xmlHtmlNode(string);
if (doc.getElementsByTagNameNS(stanza_PARSE_ERROR_NS, 'parsererror').length) {
throw new Error(`Parser Error: ${string}`);
}
const node = doc.firstElementChild;
if (['message', 'iq', 'presence'].includes(node.nodeName.toLowerCase()) && node.namespaceURI !== 'jabber:client' && node.namespaceURI !== 'jabber:server') {
const err_msg = `Invalid namespaceURI ${node.namespaceURI}`;
log.error(err_msg);
if (throwErrorIfInvalidNS) throw new Error(err_msg);
}
return node;
}
/**
* A Stanza represents a XML element used in XMPP (commonly referred to as
* stanzas).
*/
class stanza_Stanza {
constructor(strings, values) {
this.strings = strings;
this.values = values;
}
toString() {
this.string = this.string || this.strings.reduce((acc, str) => {
const idx = this.strings.indexOf(str);
const value = this.values.length > idx ? this.values[idx].toString() : '';
return acc + str + value;
}, '');
return this.string;
}
tree() {
this.node = this.node ?? stanza_toStanza(this.toString(), true);
return this.node;
}
}
/**
* Tagged template literal function which generates {@link Stanza } objects
*
* Similar to the `html` function, from Lit.
*
* @example stx`<presence type="${type}"><show>${show}</show></presence>`
*/
function stanza_stx(strings) {
for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
values[_key - 1] = arguments[_key];
}
return new stanza_Stanza(strings, values);
}
;// CONCATENATED MODULE: ./src/headless/utils/core.js
/**
* @copyright The Converse.js contributors
* @license Mozilla Public License (MPLv2)
* @description This is the core utilities module.
*/
/**
* The utils object
* @namespace u
*/
const u = {};
function isElement(el) {
return el instanceof Element || el instanceof HTMLDocument;
}
function isError(obj) {
return Object.prototype.toString.call(obj) === "[object Error]";
}
function core_isFunction(val) {
return typeof val === 'function';
}
function isEmptyMessage(attrs) {
if (attrs instanceof Model) {
attrs = attrs.attributes;
}
return !attrs['oob_url'] && !attrs['file'] && !(attrs['is_encrypted'] && attrs['plaintext']) && !attrs['message'] && !attrs['body'];
}
/**
* We distinguish between UniView and MultiView instances.
*
* UniView means that only one chat is visible, even though there might be multiple ongoing chats.
* MultiView means that multiple chats may be visible simultaneously.
*/
function isUniView() {
return ['mobile', 'fullscreen', 'embedded'].includes(settings_api.get("view_mode"));
}
function shouldClearCache() {
const {
api
} = shared_converse;
return !shared_converse.config.get('trusted') || api.settings.get('clear_cache_on_logout') || shared_converse.isTestEnv();
}
async function tearDown() {
const {
api
} = shared_converse;
await api.trigger('beforeTearDown', {
'synchronous': true
});
window.removeEventListener('click', shared_converse.onUserActivity);
window.removeEventListener('focus', shared_converse.onUserActivity);
window.removeEventListener('keypress', shared_converse.onUserActivity);
window.removeEventListener('mousemove', shared_converse.onUserActivity);
window.removeEventListener(shared_converse.unloadevent, shared_converse.onUserActivity);
window.clearInterval(shared_converse.everySecondTrigger);
api.trigger('afterTearDown');
return shared_converse;
}
function clearSession() {
shared_converse.session?.destroy();
delete shared_converse.session;
shouldClearCache() && shared_converse.api.user.settings.clear();
/**
* Synchronouse event triggered once the user session has been cleared,
* for example when the user has logged out or when Converse has
* disconnected for some other reason.
* @event _converse#clearSession
*/
return shared_converse.api.trigger('clearSession', {
'synchronous': true
});
}
/**
* Given a message object, return its text with @ chars
* inserted before the mentioned nicknames.
*/
function prefixMentions(message) {
let text = message.getMessageText();
(message.get('references') || []).sort((a, b) => b.begin - a.begin).forEach(ref => {
text = `${text.slice(0, ref.begin)}@${text.slice(ref.begin)}`;
});
return text;
}
u.isTagEqual = function (stanza, name) {
if (stanza.tree?.()) {
return u.isTagEqual(stanza.tree(), name);
} else if (!(stanza instanceof Element)) {
throw Error("isTagEqual called with value which isn't " + "an element or Strophe.Builder instance");
} else {
return core.isTagEqual(stanza, name);
}
};
u.getJIDFromURI = function (jid) {
return jid.startsWith('xmpp:') && jid.endsWith('?join') ? jid.replace(/^xmpp:/, '').replace(/\?join$/, '') : jid;
};
u.getLongestSubstring = function (string, candidates) {
function reducer(accumulator, current_value) {
if (string.startsWith(current_value)) {
if (current_value.length > accumulator.length) {
return current_value;
} else {
return accumulator;
}
} else {
return accumulator;
}
}
return candidates.reduce(reducer, '');
};
function isValidJID(jid) {
if (typeof jid === 'string') {
return lodash_es_compact(jid.split('@')).length === 2 && !jid.startsWith('@') && !jid.endsWith('@');
}
return false;
}
u.isValidMUCJID = function (jid) {
return !jid.startsWith('@') && !jid.endsWith('@');
};
u.isSameBareJID = function (jid1, jid2) {
if (typeof jid1 !== 'string' || typeof jid2 !== 'string') {
return false;
}
return core.getBareJidFromJid(jid1).toLowerCase() === core.getBareJidFromJid(jid2).toLowerCase();
};
u.isSameDomain = function (jid1, jid2) {
if (typeof jid1 !== 'string' || typeof jid2 !== 'string') {
return false;
}
return core.getDomainFromJid(jid1).toLowerCase() === core.getDomainFromJid(jid2).toLowerCase();
};
u.isNewMessage = function (message) {
/* Given a stanza, determine whether it's a new
* message, i.e. not a MAM archived one.
*/
if (message instanceof Element) {
return !(sizzle_default()(`result[xmlns="${core.NS.MAM}"]`, message).length && sizzle_default()(`delay[xmlns="${core.NS.DELAY}"]`, message).length);
} else if (message instanceof Model) {
message = message.attributes;
}
return !(message['is_delayed'] && message['is_archived']);
};
u.shouldCreateMessage = function (attrs) {
return attrs['retracted'] ||
// Retraction received *before* the message
!isEmptyMessage(attrs);
};
u.shouldCreateGroupchatMessage = function (attrs) {
return attrs.nick && (u.shouldCreateMessage(attrs) || attrs.is_tombstone);
};
u.isChatRoom = function (model) {
return model && model.get('type') === 'chatroom';
};
function isErrorObject(o) {
return o instanceof Error;
}
u.isErrorStanza = function (stanza) {
if (!isElement(stanza)) {
return false;
}
return stanza.getAttribute('type') === 'error';
};
u.isForbiddenError = function (stanza) {
if (!isElement(stanza)) {
return false;
}
return sizzle_default()(`error[type="auth"] forbidden[xmlns="${core.NS.STANZAS}"]`, stanza).length > 0;
};
u.isServiceUnavailableError = function (stanza) {
if (!isElement(stanza)) {
return false;
}
return sizzle_default()(`error[type="cancel"] service-unavailable[xmlns="${core.NS.STANZAS}"]`, stanza).length > 0;
};
/**
* Merge the second object into the first one.
* @method u#merge
* @param { Object } dst
* @param { Object } src
*/
function core_merge(dst, src) {
for (const k in src) {
if (!Object.prototype.hasOwnProperty.call(src, k)) continue;
if (k === "__proto__" || k === "constructor") continue;
if (lodash_es_isObject(dst[k])) {
core_merge(dst[k], src[k]);
} else {
dst[k] = src[k];
}
}
}
u.getOuterWidth = function (el) {
let include_margin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
let width = el.offsetWidth;
if (!include_margin) {
return width;
}
const style = window.getComputedStyle(el);
width += parseInt(style.marginLeft ? style.marginLeft : 0, 10) + parseInt(style.marginRight ? style.marginRight : 0, 10);
return width;
};
/**
* Converts an HTML string into a DOM element.
* Expects that the HTML string has only one top-level element,
* i.e. not multiple ones.
* @private
* @method u#stringToElement
* @param { String } s - The HTML string
*/
u.stringToElement = function (s) {
var div = document.createElement('div');
div.innerHTML = s;
return div.firstElementChild;
};
/**
* Checks whether the DOM element matches the given selector.
* @private
* @method u#matchesSelector
* @param { Element } el - The DOM element
* @param { String } selector - The selector
*/
u.matchesSelector = function (el, selector) {
const match = el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector;
return match ? match.call(el, selector) : false;
};
/**
* Returns a list of children of the DOM element that match the selector.
* @private
* @method u#queryChildren
* @param { Element } el - the DOM element
* @param { String } selector - the selector they should be matched against
*/
u.queryChildren = function (el, selector) {
return Array.from(el.childNodes).filter(el => u.matchesSelector(el, selector));
};
u.contains = function (attr, query) {
const checker = (item, key) => item.get(key).toLowerCase().includes(query.toLowerCase());
return function (item) {
if (typeof attr === 'object') {
return Object.keys(attr).reduce((acc, k) => acc || checker(item, k), false);
} else if (typeof attr === 'string') {
return checker(item, attr);
} else {
throw new TypeError('contains: wrong attribute type. Must be string or array.');
}
};
};
u.isOfType = function (type, item) {
return item.get('type') == type;
};
u.isInstance = function (type, item) {
return item instanceof type;
};
u.getAttribute = function (key, item) {
return item.get(key);
};
u.contains.not = function (attr, query) {
return function (item) {
return !u.contains(attr, query)(item);
};
};
u.rootContains = function (root, el) {
// The document element does not have the contains method in IE.
if (root === document && !root.contains) {
return document.head.contains(el) || document.body.contains(el);
}
return root.contains ? root.contains(el) : window.HTMLElement.prototype.contains.call(root, el);
};
u.createFragmentFromText = function (markup) {
/* Returns a DocumentFragment containing DOM nodes based on the
* passed-in markup text.
*/
// http://stackoverflow.com/questions/9334645/create-node-from-markup-string
var frag = document.createDocumentFragment(),
tmp = document.createElement('body'),
child;
tmp.innerHTML = markup;
// Append elements in a loop to a DocumentFragment, so that the
// browser does not re-render the document for each node.
while (child = tmp.firstChild) {
// eslint-disable-line no-cond-assign
frag.appendChild(child);
}
return frag;
};
u.isPersistableModel = function (model) {
return model.collection && model.collection.browserStorage;
};
u.getResolveablePromise = getOpenPromise;
u.getOpenPromise = getOpenPromise;
u.interpolate = function (string, o) {
return string.replace(/{{{([^{}]*)}}}/g, (a, b) => {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
});
};
/**
* Call the callback once all the events have been triggered
* @private
* @method u#onMultipleEvents
* @param { Array } events: An array of objects, with keys `object` and
* `event`, representing the event name and the object it's triggered upon.
* @param { Function } callback: The function to call once all events have
* been triggered.
*/
u.onMultipleEvents = function () {
let events = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let callback = arguments.length > 1 ? arguments[1] : undefined;
let triggered = [];
function handler(result) {
triggered.push(result);
if (events.length === triggered.length) {
callback(triggered);
triggered = [];
}
}
events.forEach(e => e.object.on(e.event, handler));
};
function safeSave(model, attributes, options) {
if (u.isPersistableModel(model)) {
model.save(attributes, options);
} else {
model.set(attributes, options);
}
}
u.safeSave = safeSave;
u.siblingIndex = function (el) {
/* eslint-disable no-cond-assign */
for (var i = 0; el = el.previousElementSibling; i++);
return i;
};
/**
* Returns the current word being written in the input element
* @method u#getCurrentWord
* @param { HTMLElement } input - The HTMLElement in which text is being entered
* @param { number } [index] - An optional rightmost boundary index. If given, the text
* value of the input element will only be considered up until this index.
* @param { string } [delineator] - An optional string delineator to
* differentiate between words.
* @private
*/
u.getCurrentWord = function (input, index, delineator) {
if (!index) {
index = input.selectionEnd || undefined;
}
let [word] = input.value.slice(0, index).split(/\s/).slice(-1);
if (delineator) {
[word] = word.split(delineator).slice(-1);
}
return word;
};
u.isMentionBoundary = s => s !== '@' && RegExp(`(\\p{Z}|\\p{P})`, 'u').test(s);
u.replaceCurrentWord = function (input, new_value) {
const caret = input.selectionEnd || undefined;
const current_word = lodash_es_last(input.value.slice(0, caret).split(/\s/));
const value = input.value;
const mention_boundary = u.isMentionBoundary(current_word[0]) ? current_word[0] : '';
input.value = value.slice(0, caret - current_word.length) + mention_boundary + `${new_value} ` + value.slice(caret);
const selection_end = caret - current_word.length + new_value.length + 1;
input.selectionEnd = mention_boundary ? selection_end + 1 : selection_end;
};
u.triggerEvent = function (el, name) {
let type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "Event";
let bubbles = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
let cancelable = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
const evt = document.createEvent(type);
evt.initEvent(name, bubbles, cancelable);
el.dispatchEvent(evt);
};
u.getSelectValues = function (select) {
const result = [];
const options = select && select.options;
for (var i = 0, iLen = options.length; i < iLen; i++) {
const opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
};
function getRandomInt(max) {
return Math.random() * max | 0;
}
u.placeCaretAtEnd = function (textarea) {
if (textarea !== document.activeElement) {
textarea.focus();
}
// Double the length because Opera is inconsistent about whether a carriage return is one character or two.
const len = textarea.value.length * 2;
// Timeout seems to be required for Blink
setTimeout(() => textarea.setSelectionRange(len, len), 1);
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Chrome)
this.scrollTop = 999999;
};
function getUniqueId(suffix) {
const uuid = crypto.randomUUID?.() ?? 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = getRandomInt(16);
const v = c === 'x' ? r : r & 0x3 | 0x8;
return v.toString(16);
});
if (typeof suffix === "string" || typeof suffix === "number") {
return uuid + ":" + suffix;
} else {
return uuid;
}
}
/**
* Clears the specified timeout and interval.
* @method u#clearTimers
* @param { number } timeout - Id if the timeout to clear.
* @param { number } interval - Id of the interval to clear.
* @private
* @copyright Simen Bekkhus 2016
* @license MIT
*/
function clearTimers(timeout, interval) {
clearTimeout(timeout);
clearInterval(interval);
}
/**
* Creates a {@link Promise} that resolves if the passed in function returns a truthy value.
* Rejects if it throws or does not return truthy within the given max_wait.
* @method u#waitUntil
* @param { Function } func - The function called every check_delay,
* and the result of which is the resolved value of the promise.
* @param { number } [max_wait=300] - The time to wait before rejecting the promise.
* @param { number } [check_delay=3] - The time to wait before each invocation of {func}.
* @returns {Promise} A promise resolved with the value of func,
* or rejected with the exception thrown by it or it times out.
* @copyright Simen Bekkhus 2016
* @license MIT
*/
function waitUntil(func) {
let max_wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 300;
let check_delay = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 3;
// Run the function once without setting up any listeners in case it's already true
try {
const result = func();
if (result) {
return Promise.resolve(result);
}
} catch (e) {
return Promise.reject(e);
}
const promise = getOpenPromise();
const timeout_err = new Error();
function checker() {
try {
const result = func();
if (result) {
clearTimers(max_wait_timeout, interval);
promise.resolve(result);
}
} catch (e) {
clearTimers(max_wait_timeout, interval);
promise.reject(e);
}
}
const interval = setInterval(checker, check_delay);
function handler() {
clearTimers(max_wait_timeout, interval);
const err_msg = `Wait until promise timed out: \n\n${timeout_err.stack}`;
console.trace();
log.error(err_msg);
promise.reject(new Error(err_msg));
}
const max_wait_timeout = setTimeout(handler, max_wait);
return promise;
}
;
function setUnloadEvent() {
if ('onpagehide' in window) {
// Pagehide gets thrown in more cases than unload. Specifically it
// gets thrown when the page is cached and not just
// closed/destroyed. It's the only viable event on mobile Safari.
// https://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/
shared_converse.unloadevent = 'pagehide';
} else if ('onbeforeunload' in window) {
shared_converse.unloadevent = 'beforeunload';
} else if ('onunload' in window) {
shared_converse.unloadevent = 'unload';
}
}
function replacePromise(name) {
const existing_promise = shared_converse.promises[name];
if (!existing_promise) {
throw new Error(`Tried to replace non-existing promise: ${name}`);
}
if (existing_promise.replace) {
const promise = getOpenPromise();
promise.replace = existing_promise.replace;
shared_converse.promises[name] = promise;
} else {
log.debug(`Not replacing promise "${name}"`);
}
}
const core_element = document.createElement('div');
function decodeHTMLEntities(str) {
if (str && typeof str === 'string') {
core_element.innerHTML = purify_default().sanitize(str);
str = core_element.textContent;
core_element.textContent = '';
}
return str;
}
function saveWindowState(ev) {
// XXX: eventually we should be able to just use
// document.visibilityState (when we drop support for older
// browsers).
let state;
const event_map = {
'focus': "visible",
'focusin': "visible",
'pageshow': "visible",
'blur': "hidden",
'focusout': "hidden",
'pagehide': "hidden"
};
ev = ev || document.createEvent('Events');
if (ev.type in event_map) {
state = event_map[ev.type];
} else {
state = document.hidden ? "hidden" : "visible";
}
shared_converse.windowState = state;
/**
* Triggered when window state has changed.
* Used to determine when a user left the page and when came back.
* @event _converse#windowStateChanged
* @type { object }
* @property{ string } state - Either "hidden" or "visible"
* @example _converse.api.listen.on('windowStateChanged', obj => { ... });
*/
shared_converse.api.trigger('windowStateChanged', {
state
});
}
/* harmony default export */ const utils_core = (Object.assign({
shouldClearCache,
waitUntil,
// TODO: remove. Only the API should be used
isErrorObject,
getRandomInt,
getUniqueId,
isElement,
isEmptyMessage,
isValidJID,
merge: core_merge,
prefixMentions,
saveWindowState,
stx: stanza_stx,
toStanza: stanza_toStanza
}, u));
;// CONCATENATED MODULE: ./src/headless/log.js
const LEVELS = {
'debug': 0,
'info': 1,
'warn': 2,
'error': 3,
'fatal': 4
};
/* eslint-disable @typescript-eslint/no-empty-function */
const logger = Object.assign({
'debug': console?.log ? console.log.bind(console) : function noop() {},
'error': console?.log ? console.log.bind(console) : function noop() {},
'info': console?.log ? console.log.bind(console) : function noop() {},
'warn': console?.log ? console.log.bind(console) : function noop() {}
}, console);
/* eslint-enable @typescript-eslint/no-empty-function */
/**
* The log namespace
* @namespace log
*/
/* harmony default export */ const log = ({
/**
* The the log-level, which determines how verbose the logging is.
* @method log#setLogLevel
* @param { number } level - The loglevel which allows for filtering of log messages
*/
setLogLevel(level) {
if (!['debug', 'info', 'warn', 'error', 'fatal'].includes(level)) {
throw new Error(`Invalid loglevel: ${level}`);
}
this.loglevel = level;
},
/**
* Logs messages to the browser's developer console.
* Available loglevels are 0 for 'debug', 1 for 'info', 2 for 'warn',
* 3 for 'error' and 4 for 'fatal'.
* When using the 'error' or 'warn' loglevels, a full stacktrace will be
* logged as well.
* @method log#log
* @param { string | Error } message - The message to be logged
* @param { number } level - The loglevel which allows for filtering of log messages
*/
log(message, level) {
let style = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
if (LEVELS[level] < LEVELS[this.loglevel]) {
return;
}
if (level === 'error' || level === 'fatal') {
style = style || 'color: maroon';
} else if (level === 'debug') {
style = style || 'color: green';
}
if (message instanceof Error) {
message = message.stack;
} else if (isElement(message)) {
message = message.outerHTML;
}
const prefix = style ? '%c' : '';
if (level === 'error') {
logger.error(`${prefix} ERROR: ${message}`, style);
} else if (level === 'warn') {
logger.warn(`${prefix} ${new Date().toISOString()} WARNING: ${message}`, style);
} else if (level === 'fatal') {
logger.error(`${prefix} FATAL: ${message}`, style);
} else if (level === 'debug') {
logger.debug(`${prefix} ${new Date().toISOString()} DEBUG: ${message}`, style);
} else {
logger.info(`${prefix} ${new Date().toISOString()} INFO: ${message}`, style);
}
},
debug(message, style) {
this.log(message, 'debug', style);
},
error(message, style) {
this.log(message, 'error', style);
},
info(message, style) {
this.log(message, 'info', style);
},
warn(message, style) {
this.log(message, 'warn', style);
},
fatal(message, style) {
this.log(message, 'fatal', style);
}
});
;// CONCATENATED MODULE: ./node_modules/pluggable.js/src/pluggable.js
/*
____ __ __ __ _
/ __ \/ /_ __ ___ ___ ____ _/ /_ / /__ (_)____
/ /_/ / / / / / __ \/ __ \/ __/ / __ \/ / _ \ / / ___/
/ ____/ / /_/ / /_/ / /_/ / /_/ / /_/ / / __/ / (__ )
/_/ /_/\__,_/\__, /\__, /\__/_/_.___/_/\___(_)_/ /____/
/____//____/ /___/
*/
// Pluggable.js lets you to make your Javascript code pluggable while still
// keeping sensitive objects and data private through closures.
// `wrappedOverride` creates a partially applied wrapper function
// that makes sure to set the proper super method when the
// overriding method is called. This is done to enable
// chaining of plugin methods, all the way up to the
// original method.
function wrappedOverride(key, value, super_method, default_super) {
if (typeof super_method === "function") {
if (typeof this.__super__ === "undefined") {
/* We're not on the context of the plugged object.
* This can happen when the overridden method is called via
* an event handler or when it's a constructor.
*
* In this case, we simply tack on the __super__ obj.
*/
this.__super__ = default_super;
}
this.__super__[key] = super_method.bind(this);
}
for (var _len = arguments.length, args = new Array(_len > 4 ? _len - 4 : 0), _key = 4; _key < _len; _key++) {
args[_key - 4] = arguments[_key];
}
return value.apply(this, args);
}
// The `PluginSocket` class contains the plugin architecture, and gets
// created whenever `pluggable.enable(obj);` is called on the object
// that you want to make pluggable.
// You can also see it as the thing into which the plugins are plugged.
// It takes two parameters, first, the object being made pluggable, and
// then the name by which the pluggable object may be referenced on the
// __super__ object (inside overrides).
class PluginSocket {
constructor(plugged, name) {
this.name = name;
this.plugged = plugged;
if (typeof this.plugged.__super__ === 'undefined') {
this.plugged.__super__ = {};
} else if (typeof this.plugged.__super__ === 'string') {
this.plugged.__super__ = {
'__string__': this.plugged.__super__
};
}
this.plugged.__super__[name] = this.plugged;
this.plugins = {};
this.initialized_plugins = [];
}
// `_overrideAttribute` overrides an attribute on the original object
// (the thing being plugged into).
//
// If the attribute being overridden is a function, then the original
// function will still be available via the `__super__` attribute.
//
// If the same function is being overridden multiple times, then
// the original function will be available at the end of a chain of
// functions, starting from the most recent override, all the way
// back to the original function, each being referenced by the
// previous' __super__ attribute.
//
// For example:
//
// `plugin2.MyFunc.__super__.myFunc => plugin1.MyFunc.__super__.myFunc => original.myFunc`
_overrideAttribute(key, plugin) {
const value = plugin.overrides[key];
if (typeof value === "function") {
const default_super = {};
default_super[this.name] = this.plugged;
const super_method = this.plugged[key];
this.plugged[key] = function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return wrappedOverride.apply(this, [key, value, super_method, default_super, ...args]);
};
} else {
this.plugged[key] = value;
}
}
_extendObject(obj, attributes) {
if (!obj.prototype.__super__) {
obj.prototype.__super__ = {};
obj.prototype.__super__[this.name] = this.plugged;
}
for (const [key, value] of Object.entries(attributes)) {
if (key === 'events') {
obj.prototype[key] = Object.assign(value, obj.prototype[key]);
} else if (typeof value === 'function') {
// We create a partially applied wrapper function, that
// makes sure to set the proper super method when the
// overriding method is called. This is done to enable
// chaining of plugin methods, all the way up to the
// original method.
const default_super = {};
default_super[this.name] = this.plugged;
const super_method = obj.prototype[key];
obj.prototype[key] = function () {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return wrappedOverride.apply(this, [key, value, super_method, default_super, ...args]);
};
} else {
obj.prototype[key] = value;
}
}
}
// Plugins can specify dependencies (by means of the
// `dependencies` list attribute) which refers to dependencies
// which will be initialized first, before the plugin itself gets initialized.
//
// If `strict_plugin_dependencies` is set to `false` (on the object being
// made pluggable), then no error will be thrown if any of these plugins aren't
// available.
loadPluginDependencies(plugin) {
plugin.dependencies?.forEach(name => {
const dep = this.plugins[name];
if (dep) {
if (dep.dependencies?.includes(plugin.__name__)) {
/* FIXME: circular dependency checking is only one level deep. */
throw "Found a circular dependency between the plugins \"" + plugin.__name__ + "\" and \"" + name + "\"";
}
this.initializePlugin(dep);
} else {
this.throwUndefinedDependencyError("Could not find dependency \"" + name + "\" " + "for the plugin \"" + plugin.__name__ + "\". " + "If it's needed, make sure it's loaded by require.js");
}
});
}
throwUndefinedDependencyError(msg) {
if (this.plugged.strict_plugin_dependencies) {
throw msg;
} else {
if (console.warn) {
console.warn(msg);
} else {
console.log(msg);
}
}
}
// `applyOverrides` is called by initializePlugin. It applies any
// and all overrides of methods or Backbone views and models that
// are defined on any of the plugins.
applyOverrides(plugin) {
Object.keys(plugin.overrides || {}).forEach(key => {
const override = plugin.overrides[key];
if (typeof override === "object") {
if (typeof this.plugged[key] === 'undefined') {
this.throwUndefinedDependencyError(`Plugin "${plugin.__name__}" tried to override "${key}" but it's not found.`);
} else {
this._extendObject(this.plugged[key], override);
}
} else {
this._overrideAttribute(key, plugin);
}
});
}
// `initializePlugin` applies the overrides (if any) defined on all
// the registered plugins and then calls the initialize method of the plugin
initializePlugin(plugin) {
if (!Object.keys(this.allowed_plugins).includes(plugin.__name__)) {
/* Don't initialize disallowed plugins. */
return;
}
if (this.initialized_plugins.includes(plugin.__name__)) {
/* Don't initialize plugins twice, otherwise we get
* infinite recursion in overridden methods.
*/
return;
}
if (typeof plugin.enabled === 'boolean' && plugin.enabled || plugin.enabled?.(this.plugged) || plugin.enabled == null) {
// isNil
Object.assign(plugin, this.properties);
if (plugin.dependencies) {
this.loadPluginDependencies(plugin);
}
this.applyOverrides(plugin);
if (typeof plugin.initialize === "function") {
plugin.initialize.bind(plugin)(this);
}
this.initialized_plugins.push(plugin.__name__);
}
}
// `registerPlugin` registers (or inserts, if you'd like) a plugin,
// by adding it to the `plugins` map on the PluginSocket instance.
registerPlugin(name, plugin) {
if (name in this.plugins) {
throw new Error('Error: Plugin name ' + name + ' is already taken');
}
plugin.__name__ = name;
this.plugins[name] = plugin;
}
// `initializePlugins` should get called once all plugins have been
// registered. It will then iterate through all the plugins, calling
// `initializePlugin` for each.
// The passed in properties variable is an object with attributes and methods
// which will be attached to the plugins.
initializePlugins() {
let properties = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let whitelist = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
let blacklist = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
if (!Object.keys(this.plugins).length) {
return;
}
this.properties = properties;
this.allowed_plugins = {};
for (const [key, plugin] of Object.entries(this.plugins)) {
if ((!whitelist.length || whitelist.includes(key)) && !blacklist.includes(key)) {
this.allowed_plugins[key] = plugin;
}
}
Object.values(this.allowed_plugins).forEach(o => this.initializePlugin(o));
}
}
function enable(object, name, attrname) {
// Call the `enable` method to make an object pluggable
//
// It takes three parameters:
// - `object`: The object that gets made pluggable.
// - `name`: The string name by which the now pluggable object
// may be referenced on the __super__ obj (in overrides).
// The default value is "plugged".
// - `attrname`: The string name of the attribute on the now
// pluggable object, which refers to the PluginSocket instance
// that gets created.
if (typeof attrname === "undefined") {
attrname = "pluginSocket";
}
if (typeof name === 'undefined') {
name = 'plugged';
}
object[attrname] = new PluginSocket(object, name);
return object;
}
/* harmony default export */ const pluggable = ({
enable
});
;// CONCATENATED MODULE: ./node_modules/lodash-es/_createBaseEach.js
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!lodash_es_isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
/* harmony default export */ const _createBaseEach = (createBaseEach);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseEach.js
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = _createBaseEach(_baseForOwn);
/* harmony default export */ const _baseEach = (baseEach);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSome.js
/**
* The base implementation of `_.some` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function baseSome(collection, predicate) {
var result;
_baseEach(collection, function(value, index, collection) {
result = predicate(value, index, collection);
return !result;
});
return !!result;
}
/* harmony default export */ const _baseSome = (baseSome);
;// CONCATENATED MODULE: ./node_modules/lodash-es/some.js
/**
* Checks if `predicate` returns truthy for **any** element of `collection`.
* Iteration is stopped once `predicate` returns truthy. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.some(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.some(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.some(users, 'active');
* // => true
*/
function some(collection, predicate, guard) {
var func = lodash_es_isArray(collection) ? _arraySome : _baseSome;
if (guard && _isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, _baseIteratee(predicate, 3));
}
/* harmony default export */ const lodash_es_some = (some);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/history.js
// Backbone.js 1.4.0
// (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
// Backbone may be freely distributed under the MIT license.
// History
// -------
// Handles cross-browser history management, based on either
// [pushState](http://diveintohtml5.info/history.html) and real URLs, or
// [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
// and URL fragments. If the browser supports neither (old IE, natch),
// falls back to polling.
const history_History = function () {
this.handlers = [];
this.checkUrl = this.checkUrl.bind(this);
// Ensure that `History` can be used outside of the browser.
if (typeof window !== 'undefined') {
this.location = window.location;
this.history = window.history;
}
};
history_History.extend = inherits;
// Cached regex for stripping a leading hash/slash and trailing space.
const routeStripper = /^[#\/]|\s+$/g;
// Cached regex for stripping leading and trailing slashes.
const rootStripper = /^\/+|\/+$/g;
// Cached regex for stripping urls of hash.
const pathStripper = /#.*$/;
// Has the history handling already been started?
history_History.started = false;
// Set up all inheritable **History** properties and methods.
Object.assign(history_History.prototype, Events, {
// The default interval to poll for hash changes, if necessary, is
// twenty times a second.
interval: 50,
// Are we at the app root?
atRoot: function () {
const path = this.location.pathname.replace(/[^\/]$/, '$&/');
return path === this.root && !this.getSearch();
},
// Does the pathname match the root?
matchRoot: function () {
const path = this.decodeFragment(this.location.pathname);
const rootPath = path.slice(0, this.root.length - 1) + '/';
return rootPath === this.root;
},
// Unicode characters in `location.pathname` are percent encoded so they're
// decoded for comparison. `%25` should not be decoded since it may be part
// of an encoded parameter.
decodeFragment: function (fragment) {
return decodeURI(fragment.replace(/%25/g, '%2525'));
},
// In IE6, the hash fragment and search params are incorrect if the
// fragment contains `?`.
getSearch: function () {
const match = this.location.href.replace(/#.*/, '').match(/\?.+/);
return match ? match[0] : '';
},
// Gets the true hash value. Cannot use location.hash directly due to bug
// in Firefox where location.hash will always be decoded.
getHash: function (window) {
const match = (window || this).location.href.match(/#(.*)$/);
return match ? match[1] : '';
},
// Get the pathname and search params, without the root.
getPath: function () {
const path = this.decodeFragment(this.location.pathname + this.getSearch()).slice(this.root.length - 1);
return path.charAt(0) === '/' ? path.slice(1) : path;
},
// Get the cross-browser normalized URL fragment from the path or hash.
getFragment: function (fragment) {
if (fragment == null) {
if (this._usePushState || !this._wantsHashChange) {
fragment = this.getPath();
} else {
fragment = this.getHash();
}
}
return fragment.replace(routeStripper, '');
},
// Start the hash change handling, returning `true` if the current URL matches
// an existing route, and `false` otherwise.
start: function (options) {
if (history_History.started) throw new Error('history has already been started');
history_History.started = true;
// Figure out the initial configuration. Do we need an iframe?
// Is pushState desired ... is it available?
this.options = lodash_es_assignIn({
root: '/'
}, this.options, options);
this.root = this.options.root;
this._wantsHashChange = this.options.hashChange !== false;
this._hasHashChange = 'onhashchange' in window && (document.documentMode === undefined || document.documentMode > 7);
this._useHashChange = this._wantsHashChange && this._hasHashChange;
this._wantsPushState = !!this.options.pushState;
this._hasPushState = !!(this.history && this.history.pushState);
this._usePushState = this._wantsPushState && this._hasPushState;
this.fragment = this.getFragment();
// Normalize root to always include a leading and trailing slash.
this.root = ('/' + this.root + '/').replace(rootStripper, '/');
// Transition from hashChange to pushState or vice versa if both are
// requested.
if (this._wantsHashChange && this._wantsPushState) {
// If we've started off with a route from a `pushState`-enabled
// browser, but we're currently in a browser that doesn't support it...
if (!this._hasPushState && !this.atRoot()) {
const rootPath = this.root.slice(0, -1) || '/';
this.location.replace(rootPath + '#' + this.getPath());
// Return immediately as browser will do redirect to new url
return true;
// Or if we've started out with a hash-based route, but we're currently
// in a browser where it could be `pushState`-based instead...
} else if (this._hasPushState && this.atRoot()) {
this.navigate(this.getHash(), {
replace: true
});
}
}
// Proxy an iframe to handle location events if the browser doesn't
// support the `hashchange` event, HTML5 history, or the user wants
// `hashChange` but not `pushState`.
if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
this.iframe = document.createElement('iframe');
this.iframe.src = 'javascript:0';
this.iframe.style.display = 'none';
this.iframe.tabIndex = -1;
const body = document.body;
// Using `appendChild` will throw on IE < 9 if the document is not ready.
const iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;
iWindow.document.open();
iWindow.document.close();
iWindow.location.hash = '#' + this.fragment;
}
// Depending on whether we're using pushState or hashes, and whether
// 'onhashchange' is supported, determine how we check the URL state.
if (this._usePushState) {
addEventListener('popstate', this.checkUrl, false);
} else if (this._useHashChange && !this.iframe) {
addEventListener('hashchange', this.checkUrl, false);
} else if (this._wantsHashChange) {
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}
if (!this.options.silent) return this.loadUrl();
},
// Disable history, perhaps temporarily. Not useful in a real app,
// but possibly useful for unit testing Routers.
stop: function () {
// Remove window listeners.
if (this._usePushState) {
removeEventListener('popstate', this.checkUrl, false);
} else if (this._useHashChange && !this.iframe) {
removeEventListener('hashchange', this.checkUrl, false);
}
// Clean up the iframe if necessary.
if (this.iframe) {
document.body.removeChild(this.iframe);
this.iframe = null;
}
// Some environments will throw when clearing an undefined interval.
if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
history_History.started = false;
},
// Add a route to be tested when the fragment changes. Routes added later
// may override previous routes.
route: function (route, callback) {
this.handlers.unshift({
route: route,
callback: callback
});
},
// Checks the current URL to see if it has changed, and if it has,
// calls `loadUrl`, normalizing across the hidden iframe.
checkUrl: function (e) {
let current = this.getFragment();
// If the user pressed the back button, the iframe's hash will have
// changed and we should use that for comparison.
if (current === this.fragment && this.iframe) {
current = this.getHash(this.iframe.contentWindow);
}
if (current === this.fragment) return false;
if (this.iframe) this.navigate(current);
this.loadUrl();
},
// Attempt to load the current URL fragment. If a route succeeds with a
// match, returns `true`. If no defined routes matches the fragment,
// returns `false`.
loadUrl: function (fragment) {
// If the root doesn't match, no routes can match either.
if (!this.matchRoot()) return false;
fragment = this.fragment = this.getFragment(fragment);
return lodash_es_some(this.handlers, function (handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
},
// Save a fragment into the hash history, or replace the URL state if the
// 'replace' option is passed. You are responsible for properly URL-encoding
// the fragment in advance.
//
// The options object can contain `trigger: true` if you wish to have the
// route callback be fired (not usually desirable), or `replace: true`, if
// you wish to modify the current URL without adding an entry to the history.
navigate: function (fragment, options) {
if (!history_History.started) return false;
if (!options || options === true) options = {
trigger: !!options
};
// Normalize the fragment.
fragment = this.getFragment(fragment || '');
// Don't include a trailing slash on the root.
let rootPath = this.root;
if (fragment === '' || fragment.charAt(0) === '?') {
rootPath = rootPath.slice(0, -1) || '/';
}
const url = rootPath + fragment;
// Strip the fragment of the query and hash for matching.
fragment = fragment.replace(pathStripper, '');
// Decode for matching.
const decodedFragment = this.decodeFragment(fragment);
if (this.fragment === decodedFragment) return;
this.fragment = decodedFragment;
// If pushState is available, we use it to set the fragment as a real URL.
if (this._usePushState) {
this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
// If hash changes haven't been explicitly disabled, update the hash
// fragment to store history.
} else if (this._wantsHashChange) {
this._updateHash(this.location, fragment, options.replace);
if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) {
const iWindow = this.iframe.contentWindow;
// Opening and closing the iframe tricks IE7 and earlier to push a
// history entry on hash-tag change. When replace is true, we don't
// want this.
if (!options.replace) {
iWindow.document.open();
iWindow.document.close();
}
this._updateHash(iWindow.location, fragment, options.replace);
}
// If you've told us that you explicitly don't want fallback hashchange-
// based history, then `navigate` becomes a page refresh.
} else {
return this.location.assign(url);
}
if (options.trigger) return this.loadUrl(fragment);
},
// Update the hash location, either replacing the current entry, or adding
// a new one to the browser history.
_updateHash: function (location, fragment, replace) {
if (replace) {
const href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(href + '#' + fragment);
} else {
// Some browsers require that `hash` contains a leading #.
location.hash = '#' + fragment;
}
}
});
/* harmony default export */ const src_history = (history_History);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsRegExp.js
/** `Object#toString` result references. */
var _baseIsRegExp_regexpTag = '[object RegExp]';
/**
* The base implementation of `_.isRegExp` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
*/
function baseIsRegExp(value) {
return lodash_es_isObjectLike(value) && _baseGetTag(value) == _baseIsRegExp_regexpTag;
}
/* harmony default export */ const _baseIsRegExp = (baseIsRegExp);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isRegExp.js
/* Node.js helper references. */
var nodeIsRegExp = _nodeUtil && _nodeUtil.isRegExp;
/**
* Checks if `value` is classified as a `RegExp` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
* @example
*
* _.isRegExp(/abc/);
* // => true
*
* _.isRegExp('/abc/');
* // => false
*/
var isRegExp = nodeIsRegExp ? _baseUnary(nodeIsRegExp) : _baseIsRegExp;
/* harmony default export */ const lodash_es_isRegExp = (isRegExp);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/router.js
// Backbone.js 1.4.0
// (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
// Backbone may be freely distributed under the MIT license.
// Router
// ------
// Routers map faux-URLs to actions, and fire events when routes are
// matched. Creating a new one sets its `routes` hash, if not set statically.
const Router = function () {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.history = options.history || new src_history();
this.preinitialize.apply(this, arguments);
if (options.routes) this.routes = options.routes;
this._bindRoutes();
this.initialize.apply(this, arguments);
};
Router.extend = inherits;
// Cached regular expressions for matching named param parts and splatted
// parts of route strings.
const optionalParam = /\((.*?)\)/g;
const namedParam = /(\(\?)?:\w+/g;
const splatParam = /\*\w+/g;
const escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
// Set up all inheritable **Router** properties and methods.
Object.assign(Router.prototype, Events, {
// preinitialize is an empty function by default. You can override it with a function
// or object. preinitialize will run before any instantiation logic is run in the Router.
preinitialize: function () {},
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function () {},
// Manually bind a single named route to a callback. For example:
//
// this.route('search/:query/p:num', 'search', function(query, num) {
// ...
// });
//
route: function (route, name, callback) {
if (!lodash_es_isRegExp(route)) route = this._routeToRegExp(route);
if (lodash_es_isFunction(name)) {
callback = name;
name = '';
}
if (!callback) callback = this[name];
this.history.route(route, fragment => {
const args = this._extractParameters(route, fragment);
if (this.execute(callback, args, name) !== false) {
this.trigger.apply(this, ['route:' + name].concat(args));
this.trigger('route', name, args);
this.history.trigger('route', this, name, args);
}
});
return this;
},
// Execute a route handler with the provided parameters. This is an
// excellent place to do pre-route setup or post-route cleanup.
execute: function (callback, args, name) {
if (callback) callback.apply(this, args);
},
// Simple proxy to `history` to save a fragment into the history.
navigate: function (fragment, options) {
this.history.navigate(fragment, options);
return this;
},
// Bind all defined routes to `history`. We have to reverse the
// order of the routes here to support behavior where the most general
// routes can be defined at the bottom of the route map.
_bindRoutes: function () {
if (!this.routes) return;
this.routes = lodash_es_result(this, 'routes');
let route;
const routes = lodash_es_keys(this.routes);
while ((route = routes.pop()) != null) {
this.route(route, this.routes[route]);
}
},
// Convert a route string into a regular expression, suitable for matching
// against the current location hash.
_routeToRegExp: function (route) {
route = route.replace(escapeRegExp, '\\$&').replace(optionalParam, '(?:$1)?').replace(namedParam, function (match, optional) {
return optional ? match : '([^/?]+)';
}).replace(splatParam, '([^?]*?)');
return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
},
// Given a route, and a URL fragment that it matches, return the array of
// extracted decoded parameters. Empty or unmatched parameters will be
// treated as `null` to normalize cross-browser behavior.
_extractParameters: function (route, fragment) {
const params = route.exec(fragment).slice(1);
return params.map(function (param, i) {
// Don't decode the search params.
if (i === params.length - 1) return param || null;
return param ? decodeURIComponent(param) : null;
});
}
});
;// CONCATENATED MODULE: ./src/headless/shared/_converse.js
/**
* A private, closured object containing the private api (via {@link _converse.api})
* as well as private methods and internal data-structures.
* @global
* @namespace _converse
*/
const _converse_converse = {
log: log,
shouldClearCache: shouldClearCache,
// TODO: Should be moved to utils with next major release
VERSION_NAME: VERSION_NAME,
templates: {},
promises: {
'initialized': getOpenPromise()
},
// TODO: remove constants in next major release
ANONYMOUS: ANONYMOUS,
CLOSED: CLOSED,
EXTERNAL: EXTERNAL,
LOGIN: LOGIN,
LOGOUT: LOGOUT,
OPENED: OPENED,
PREBIND: PREBIND,
SUCCESS: SUCCESS,
FAILURE: FAILURE,
DEFAULT_IMAGE_TYPE: DEFAULT_IMAGE_TYPE,
DEFAULT_IMAGE: DEFAULT_IMAGE,
INACTIVE: INACTIVE,
ACTIVE: ACTIVE,
COMPOSING: COMPOSING,
PAUSED: PAUSED,
GONE: GONE,
PRIVATE_CHAT_TYPE: PRIVATE_CHAT_TYPE,
CHATROOMS_TYPE: CHATROOMS_TYPE,
HEADLINES_TYPE: HEADLINES_TYPE,
CONTROLBOX_TYPE: CONTROLBOX_TYPE,
// Set as module attr so that we can override in tests.
// TODO: replace with config settings
TIMEOUTS: {
PAUSED: 10000,
INACTIVE: 90000
},
default_connection_options: {
'explicitResourceBinding': true
},
router: new Router(),
isTestEnv: () => {
return getInitSettings()['bosh_service_url'] === 'montague.lit/http-bind';
},
getDefaultStore: getDefaultStore,
createStore: createStore,
/**
* Translate the given string based on the current locale.
* @method __
* @private
* @memberOf _converse
* @param { String } str
*/
'__': function () {
return i18n.__(...arguments);
},
/**
* A no-op method which is used to signal to gettext that the passed in string
* should be included in the pot translation file.
*
* In contrast to the double-underscore method, the triple underscore method
* doesn't actually translate the strings.
*
* One reason for this method might be because we're using strings we cannot
* send to the translation function because they require variable interpolation
* and we don't yet have the variables at scan time.
*
* @method ___
* @private
* @memberOf _converse
* @param { String } str
*/
'___': str => str
};
// Make _converse an event emitter
Object.assign(_converse_converse, Events);
// Make _converse pluggable
pluggable.enable(_converse_converse, '_converse', 'pluggable');
/* harmony default export */ const shared_converse = (_converse_converse);
// EXTERNAL MODULE: ./node_modules/dayjs/plugin/advancedFormat.js
var advancedFormat = __webpack_require__(734);
var advancedFormat_default = /*#__PURE__*/__webpack_require__.n(advancedFormat);
;// CONCATENATED MODULE: ./src/headless/shared/connection/api.js
/**
* This grouping collects API functions related to the XMPP connection.
*
* @namespace _converse.api.connection
* @memberOf _converse.api
*/
/* harmony default export */ const connection_api = ({
/**
* @method _converse.api.connection.authenticated
* @memberOf _converse.api.connection
* @returns {boolean} Whether we're authenticated to the XMPP server or not
*/
authenticated() {
return shared_converse?.connection?.authenticated && true;
},
/**
* @method _converse.api.connection.connected
* @memberOf _converse.api.connection
* @returns {boolean} Whether there is an established connection or not.
*/
connected() {
return shared_converse?.connection?.connected && true;
},
/**
* Terminates the connection.
*
* @method _converse.api.connection.disconnect
* @memberOf _converse.api.connection
*/
disconnect() {
if (shared_converse.connection) {
shared_converse.connection.disconnect();
}
},
/**
* Can be called once the XMPP connection has dropped and we want
* to attempt reconnection.
* Only needs to be called once, if reconnect fails Converse will
* attempt to reconnect every two seconds, alternating between BOSH and
* Websocket if URLs for both were provided.
* @method reconnect
* @memberOf _converse.api.connection
*/
reconnect() {
const {
__,
connection
} = shared_converse;
connection.setConnectionStatus(core.Status.RECONNECTING, __('The connection has dropped, attempting to reconnect.'));
if (connection?.reconnecting) {
return connection.debouncedReconnect();
} else {
return connection.reconnect();
}
},
/**
* Utility method to determine the type of connection we have
* @method isType
* @memberOf _converse.api.connection
* @returns {boolean}
*/
isType(type) {
return shared_converse.connection.isType(type);
}
});
;// CONCATENATED MODULE: ./src/headless/shared/api/events.js
/* harmony default export */ const events = ({
/**
* Lets you trigger events, which can be listened to via
* {@link _converse.api.listen.on} or {@link _converse.api.listen.once}
* (see [_converse.api.listen](http://localhost:8000/docs/html/api/-_converse.api.listen.html)).
*
* Some events also double as promises and can be waited on via {@link _converse.api.waitUntil}.
*
* @method _converse.api.trigger
* @param { string } name - The event name
* @param {...any} [argument] - Argument to be passed to the event handler
* @param { object } [options]
* @param { boolean } [options.synchronous] - Whether the event is synchronous or not.
* When a synchronous event is fired, a promise will be returned
* by {@link _converse.api.trigger} which resolves once all the
* event handlers' promises have been resolved.
*/
async trigger(name) {
if (!shared_converse._events) {
return;
}
const args = Array.from(arguments);
const options = args.pop();
if (options && options.synchronous) {
const events = shared_converse._events[name] || [];
const event_args = args.splice(1);
await Promise.all(events.map(e => e.callback.apply(e.ctx, event_args)));
} else {
shared_converse.trigger.apply(shared_converse, arguments);
}
const promise = shared_converse.promises[name];
if (promise !== undefined) {
promise.resolve();
}
},
/**
* Triggers a hook which can be intercepted by registered listeners via
* {@link _converse.api.listen.on} or {@link _converse.api.listen.once}.
* (see [_converse.api.listen](http://localhost:8000/docs/html/api/-_converse.api.listen.html)).
* A hook is a special kind of event which allows you to intercept a data
* structure in order to modify it, before passing it back.
* @async
* @param { string } name - The hook name
* @param {...any} context - The context to which the hook applies (could be for example, a {@link _converse.ChatBox})).
* @param {...any} data - The data structure to be intercepted and modified by the hook listeners.
* @returns {Promise<any>} - A promise that resolves with the modified data structure.
*/
hook(name, context, data) {
const events = shared_converse._events[name] || [];
if (events.length) {
// Create a chain of promises, with each one feeding its output to
// the next. The first input is a promise with the original data
// sent to this hook.
return events.reduce((o, e) => o.then(d => e.callback(context, d)), Promise.resolve(data));
} else {
return data;
}
},
/**
* Converse emits events to which you can subscribe to.
*
* The `listen` namespace exposes methods for creating event listeners
* (aka handlers) for these events.
*
* @namespace _converse.api.listen
* @memberOf _converse
*/
listen: {
/**
* Lets you listen to an event exactly once.
* @method _converse.api.listen.once
* @param { string } name The event's name
* @param { function } callback The callback method to be called when the event is emitted.
* @param { object } [context] The value of the `this` parameter for the callback.
* @example _converse.api.listen.once('message', function (messageXML) { ... });
*/
once: shared_converse.once.bind(shared_converse),
/**
* Lets you subscribe to an event.
* Every time the event fires, the callback method specified by `callback` will be called.
* @method _converse.api.listen.on
* @param { string } name The event's name
* @param { function } callback The callback method to be called when the event is emitted.
* @param { object } [context] The value of the `this` parameter for the callback.
* @example _converse.api.listen.on('message', function (messageXML) { ... });
*/
on: shared_converse.on.bind(shared_converse),
/**
* To stop listening to an event, you can use the `not` method.
* @method _converse.api.listen.not
* @param { string } name The event's name
* @param { function } callback The callback method that is to no longer be called when the event fires
* @example _converse.api.listen.not('message', function (messageXML);
*/
not: shared_converse.off.bind(shared_converse),
/**
* Subscribe to an incoming stanza
* Every a matched stanza is received, the callback method specified by
* `callback` will be called.
* @method _converse.api.listen.stanza
* @param { string } name The stanza's name
* @param { object } options Matching options (e.g. 'ns' for namespace, 'type' for stanza type, also 'id' and 'from');
* @param { function } handler The callback method to be called when the stanza appears
*/
stanza(name, options, handler) {
if (utils_core(options)) {
handler = options;
options = {};
} else {
options = options || {};
}
shared_converse.connection.addHandler(handler, options.ns, name, options.type, options.id, options.from, options);
}
}
});
;// CONCATENATED MODULE: ./src/headless/shared/api/promise.js
/* harmony default export */ const promise = ({
/**
* Converse and its plugins trigger various events which you can listen to via the
* {@link _converse.api.listen} namespace.
*
* Some of these events are also available as [ES2015 Promises](http://es6-features.org/#PromiseUsage)
* although not all of them could logically act as promises, since some events
* might be fired multpile times whereas promises are to be resolved (or
* rejected) only once.
*
* Events which are also promises include:
*
* * [cachedRoster](/docs/html/events.html#cachedroster)
* * [chatBoxesFetched](/docs/html/events.html#chatBoxesFetched)
* * [pluginsInitialized](/docs/html/events.html#pluginsInitialized)
* * [roster](/docs/html/events.html#roster)
* * [rosterContactsFetched](/docs/html/events.html#rosterContactsFetched)
* * [rosterGroupsFetched](/docs/html/events.html#rosterGroupsFetched)
* * [rosterInitialized](/docs/html/events.html#rosterInitialized)
*
* The various plugins might also provide promises, and they do this by using the
* `promises.add` api method.
*
* @namespace _converse.api.promises
* @memberOf _converse.api
*/
promises: {
/**
* By calling `promises.add`, a new [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* is made available for other code or plugins to depend on via the
* {@link _converse.api.waitUntil} method.
*
* Generally, it's the responsibility of the plugin which adds the promise to
* also resolve it.
*
* This is done by calling {@link _converse.api.trigger}, which not only resolves the
* promise, but also emits an event with the same name (which can be listened to
* via {@link _converse.api.listen}).
*
* @method _converse.api.promises.add
* @param {string|array} [name|names] The name or an array of names for the promise(s) to be added
* @param { boolean } [replace=true] Whether this promise should be replaced with a new one when the user logs out.
* @example _converse.api.promises.add('foo-completed');
*/
add(promises) {
let replace = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
promises = Array.isArray(promises) ? promises : [promises];
promises.forEach(name => {
const promise = getOpenPromise();
promise.replace = replace;
shared_converse.promises[name] = promise;
});
}
},
/**
* Wait until a promise is resolved or until the passed in function returns
* a truthy value.
* @method _converse.api.waitUntil
* @param {string|function} condition - The name of the promise to wait for,
* or a function which should eventually return a truthy value.
* @returns {Promise}
*/
waitUntil(condition) {
if (core_isFunction(condition)) {
return waitUntil(condition);
} else {
const promise = shared_converse.promises[condition];
if (promise === undefined) {
return null;
}
return promise;
}
}
});
;// CONCATENATED MODULE: ./src/headless/shared/errors.js
/**
* Custom error for indicating timeouts
* @namespace converse.env
*/
class TimeoutError extends Error {}
;// CONCATENATED MODULE: ./src/headless/shared/api/send.js
/* harmony default export */ const send = ({
/**
* Allows you to send XML stanzas.
* @method _converse.api.send
* @param { Element | Stanza } stanza
* @return { void }
* @example
* const msg = converse.env.$msg({
* 'from': 'juliet@example.com/balcony',
* 'to': 'romeo@example.net',
* 'type':'chat'
* });
* _converse.api.send(msg);
*/
send(stanza) {
const {
api
} = shared_converse;
if (!api.connection.connected()) {
log.warn("Not sending stanza because we're not connected!");
log.warn(core.serialize(stanza));
return;
}
if (typeof stanza === 'string') {
stanza = stanza_toStanza(stanza);
} else if (stanza?.tree) {
stanza = stanza.tree();
}
if (stanza.tagName === 'iq') {
return api.sendIQ(stanza);
} else {
shared_converse.connection.send(stanza);
api.trigger('send', stanza);
}
},
/**
* Send an IQ stanza
* @method _converse.api.sendIQ
* @param { Element } stanza
* @param { number } [timeout] - The default timeout value is taken from
* the `stanza_timeout` configuration setting.
* @param { Boolean } [reject=true] - Whether an error IQ should cause the promise
* to be rejected. If `false`, the promise will resolve instead of being rejected.
* @returns { Promise } A promise which resolves (or potentially rejected) once we
* receive a `result` or `error` stanza or once a timeout is reached.
* If the IQ stanza being sent is of type `result` or `error`, there's
* nothing to wait for, so an already resolved promise is returned.
*/
sendIQ(stanza, timeout) {
let reject = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
const {
api,
connection
} = shared_converse;
let promise;
stanza = stanza.tree?.() ?? stanza;
if (['get', 'set'].includes(stanza.getAttribute('type'))) {
timeout = timeout || api.settings.get('stanza_timeout');
if (reject) {
promise = new Promise((resolve, reject) => connection.sendIQ(stanza, resolve, reject, timeout));
promise.catch(e => {
if (e === null) {
throw new TimeoutError(`Timeout error after ${timeout}ms for the following IQ stanza: ${core.serialize(stanza)}`);
}
});
} else {
promise = new Promise(resolve => connection.sendIQ(stanza, resolve, resolve, timeout));
}
} else {
shared_converse.connection.sendIQ(stanza);
promise = Promise.resolve();
}
api.trigger('send', stanza);
return promise;
}
});
;// CONCATENATED MODULE: ./src/headless/shared/api/presence.js
/* harmony default export */ const presence = ({
/**
* @namespace _converse.api.user.presence
* @memberOf _converse.api.user
*/
presence: {
/**
* Send out a presence stanza
* @method _converse.api.user.presence.send
* @param { String } [type]
* @param { String } [to]
* @param { String } [status] - An optional status message
* @param { Array<Element>|Array<Strophe.Builder>|Element|Strophe.Builder } [child_nodes]
* Nodes(s) to be added as child nodes of the `presence` XML element.
*/
async send(type, to, status, child_nodes) {
await shared_api.waitUntil('statusInitialized');
if (child_nodes && !Array.isArray(child_nodes)) {
child_nodes = [child_nodes];
}
const model = shared_converse.xmppstatus;
const presence = await model.constructPresence(type, to, status);
child_nodes?.map(c => c?.tree() ?? c).forEach(c => presence.cnode(c).up());
shared_api.send(presence);
if (['away', 'chat', 'dnd', 'online', 'xa', undefined].includes(type)) {
const mucs = await shared_api.rooms.get();
mucs.forEach(muc => muc.sendStatusPresence(type, status, child_nodes));
}
}
}
});
;// CONCATENATED MODULE: ./node_modules/lodash-es/debounce.js
/** Error message constants. */
var debounce_FUNC_ERROR_TEXT = 'Expected a function';
/* Built-in method references for those with the same name as other `lodash` methods. */
var debounce_nativeMax = Math.max,
debounce_nativeMin = Math.min;
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(debounce_FUNC_ERROR_TEXT);
}
wait = lodash_es_toNumber(wait) || 0;
if (lodash_es_isObject(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? debounce_nativeMax(lodash_es_toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
timeWaiting = wait - timeSinceLastCall;
return maxing
? debounce_nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
: timeWaiting;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
function timerExpired() {
var time = lodash_es_now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(lodash_es_now());
}
function debounced() {
var time = lodash_es_now(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
clearTimeout(timerId);
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
/* harmony default export */ const lodash_es_debounce = (debounce);
// EXTERNAL MODULE: ./node_modules/localforage-webextensionstorage-driver/local.js
var local = __webpack_require__(2);
// EXTERNAL MODULE: ./node_modules/localforage-webextensionstorage-driver/sync.js
var localforage_webextensionstorage_driver_sync = __webpack_require__(63);
;// CONCATENATED MODULE: ./src/headless/shared/connection/index.js
const i = Object.keys(core.Status).reduce((max, k) => Math.max(max, core.Status[k]), 0);
core.Status.RECONNECTING = i + 1;
/**
* The Connection class manages the connection to the XMPP server. It's
* agnostic concerning the underlying protocol (i.e. websocket, long-polling
* via BOSH or websocket inside a shared worker).
*/
class connection_Connection extends core.Connection {
constructor(service, options) {
super(service, options);
this.debouncedReconnect = lodash_es_debounce(this.reconnect, 3000);
}
static generateResource() {
return `/converse.js-${Math.floor(Math.random() * 139749528).toString()}`;
}
async bind() {
/**
* Synchronous event triggered before we send an IQ to bind the user's
* JID resource for this session.
* @event _converse#beforeResourceBinding
*/
await shared_api.trigger('beforeResourceBinding', {
'synchronous': true
});
super.bind();
}
async onDomainDiscovered(response) {
const text = await response.text();
const xrd = new window.DOMParser().parseFromString(text, "text/xml").firstElementChild;
if (xrd.nodeName != "XRD" || xrd.namespaceURI != "http://docs.oasis-open.org/ns/xri/xrd-1.0") {
return log.warn("Could not discover XEP-0156 connection methods");
}
const bosh_links = sizzle_default()(`Link[rel="urn:xmpp:alt-connections:xbosh"]`, xrd);
const ws_links = sizzle_default()(`Link[rel="urn:xmpp:alt-connections:websocket"]`, xrd);
const bosh_methods = bosh_links.map(el => el.getAttribute('href'));
const ws_methods = ws_links.map(el => el.getAttribute('href'));
if (bosh_methods.length === 0 && ws_methods.length === 0) {
log.warn("Neither BOSH nor WebSocket connection methods have been specified with XEP-0156.");
} else {
// TODO: support multiple endpoints
shared_api.settings.set("websocket_url", ws_methods.pop());
shared_api.settings.set('bosh_service_url', bosh_methods.pop());
this.service = shared_api.settings.get("websocket_url") || shared_api.settings.get('bosh_service_url');
this.setProtocol();
}
}
/**
* Adds support for XEP-0156 by quering the XMPP server for alternate
* connection methods. This allows users to use the websocket or BOSH
* connection of their own XMPP server instead of a proxy provided by the
* host of Converse.js.
* @method Connnection.discoverConnectionMethods
*/
async discoverConnectionMethods(domain) {
// Use XEP-0156 to check whether this host advertises websocket or BOSH connection methods.
const options = {
'mode': 'cors',
'headers': {
'Accept': 'application/xrd+xml, text/xml'
}
};
const url = `https://${domain}/.well-known/host-meta`;
let response;
try {
response = await fetch(url, options);
} catch (e) {
log.error(`Failed to discover alternative connection methods at ${url}`);
log.error(e);
return;
}
if (response.status >= 200 && response.status < 400) {
await this.onDomainDiscovered(response);
} else {
log.warn("Could not discover XEP-0156 connection methods");
}
}
/**
* Establish a new XMPP session by logging in with the supplied JID and
* password.
* @method Connnection.connect
* @param { String } jid
* @param { String } password
* @param { Funtion } callback
*/
async connect(jid, password, callback) {
if (shared_api.settings.get("discover_connection_methods")) {
const domain = core.getDomainFromJid(jid);
await this.discoverConnectionMethods(domain);
}
if (!shared_api.settings.get('bosh_service_url') && !shared_api.settings.get("websocket_url")) {
throw new Error("You must supply a value for either the bosh_service_url or websocket_url or both.");
}
super.connect(jid, password, callback || this.onConnectStatusChanged, BOSH_WAIT);
}
/**
* Switch to a different transport if a service URL is available for it.
*
* When reconnecting with a new transport, we call setUserJID
* so that a new resource is generated, to avoid multiple
* server-side sessions with the same resource.
*
* We also call `_proto._doDisconnect` so that connection event handlers
* for the old transport are removed.
*/
async switchTransport() {
if (shared_api.connection.isType('websocket') && shared_api.settings.get('bosh_service_url')) {
await setUserJID(shared_converse.bare_jid);
this._proto._doDisconnect();
this._proto = new core.Bosh(this);
this.service = shared_api.settings.get('bosh_service_url');
} else if (shared_api.connection.isType('bosh') && shared_api.settings.get("websocket_url")) {
if (shared_api.settings.get("authentication") === ANONYMOUS) {
// When reconnecting anonymously, we need to connect with only
// the domain, not the full JID that we had in our previous
// (now failed) session.
await setUserJID(shared_api.settings.get("jid"));
} else {
await setUserJID(shared_converse.bare_jid);
}
this._proto._doDisconnect();
this._proto = new core.Websocket(this);
this.service = shared_api.settings.get("websocket_url");
}
}
async reconnect() {
log.debug('RECONNECTING: the connection has dropped, attempting to reconnect.');
this.reconnecting = true;
await tearDown();
const conn_status = shared_converse.connfeedback.get('connection_status');
if (conn_status === core.Status.CONNFAIL) {
this.switchTransport();
} else if (conn_status === core.Status.AUTHFAIL && shared_api.settings.get("authentication") === ANONYMOUS) {
// When reconnecting anonymously, we need to connect with only
// the domain, not the full JID that we had in our previous
// (now failed) session.
await setUserJID(shared_api.settings.get("jid"));
}
/**
* Triggered when the connection has dropped, but Converse will attempt
* to reconnect again.
* @event _converse#will-reconnect
*/
shared_api.trigger('will-reconnect');
if (shared_api.settings.get("authentication") === ANONYMOUS) {
await clearSession();
}
return shared_api.user.login();
}
/**
* Called as soon as a new connection has been established, either
* by logging in or by attaching to an existing BOSH session.
* @method Connection.onConnected
* @param { Boolean } reconnecting - Whether Converse.js reconnected from an earlier dropped session.
*/
async onConnected(reconnecting) {
delete this.reconnecting;
this.flush(); // Solves problem of returned PubSub BOSH response not received by browser
await setUserJID(this.jid);
// Save the current JID in persistent storage so that we can attempt to
// recreate the session from SCRAM keys
if (shared_converse.config.get('trusted')) {
localStorage.setItem('conversejs-session-jid', shared_converse.bare_jid);
}
/**
* Synchronous event triggered after we've sent an IQ to bind the
* user's JID resource for this session.
* @event _converse#afterResourceBinding
*/
await shared_api.trigger('afterResourceBinding', reconnecting, {
'synchronous': true
});
if (reconnecting) {
/**
* After the connection has dropped and converse.js has reconnected.
* Any Strophe stanza handlers (as registered via `converse.listen.stanza`) will
* have to be registered anew.
* @event _converse#reconnected
* @example _converse.api.listen.on('reconnected', () => { ... });
*/
shared_api.trigger('reconnected');
} else {
/**
* Triggered after the connection has been established and Converse
* has got all its ducks in a row.
* @event _converse#initialized
*/
shared_api.trigger('connected');
}
}
/**
* Used to keep track of why we got disconnected, so that we can
* decide on what the next appropriate action is (in onDisconnected)
* @method Connection.setDisconnectionCause
* @param { Number } cause - The status number as received from Strophe.
* @param { String } [reason] - An optional user-facing message as to why
* there was a disconnection.
* @param { Boolean } [override] - An optional flag to replace any previous
* disconnection cause and reason.
*/
setDisconnectionCause(cause, reason, override) {
if (cause === undefined) {
delete this.disconnection_cause;
delete this.disconnection_reason;
} else if (this.disconnection_cause === undefined || override) {
this.disconnection_cause = cause;
this.disconnection_reason = reason;
}
}
setConnectionStatus(status, message) {
this.status = status;
shared_converse.connfeedback.set({
'connection_status': status,
message
});
}
async finishDisconnection() {
// Properly tear down the session so that it's possible to manually connect again.
log.debug('DISCONNECTED');
delete this.reconnecting;
this.reset();
tearDown();
await clearSession();
delete shared_converse.connection;
/**
* Triggered after converse.js has disconnected from the XMPP server.
* @event _converse#disconnected
* @memberOf _converse
* @example _converse.api.listen.on('disconnected', () => { ... });
*/
shared_api.trigger('disconnected');
}
/**
* Gets called once strophe's status reaches Strophe.Status.DISCONNECTED.
* Will either start a teardown process for converse.js or attempt
* to reconnect.
* @method onDisconnected
*/
onDisconnected() {
if (shared_api.settings.get("auto_reconnect")) {
const reason = this.disconnection_reason;
if (this.disconnection_cause === core.Status.AUTHFAIL) {
if (shared_api.settings.get("credentials_url") || shared_api.settings.get("authentication") === ANONYMOUS) {
// If `credentials_url` is set, we reconnect, because we might
// be receiving expirable tokens from the credentials_url.
//
// If `authentication` is anonymous, we reconnect because we
// might have tried to attach with stale BOSH session tokens
// or with a cached JID and password
return shared_api.connection.reconnect();
} else {
return this.finishDisconnection();
}
} else if (this.status === core.Status.CONNECTING) {
// Don't try to reconnect if we were never connected to begin
// with, otherwise an infinite loop can occur (e.g. when the
// BOSH service URL returns a 404).
const {
__
} = shared_converse;
this.setConnectionStatus(core.Status.CONNFAIL, __('An error occurred while connecting to the chat server.'));
return this.finishDisconnection();
} else if (this.disconnection_cause === LOGOUT || reason === core.ErrorCondition.NO_AUTH_MECH || reason === "host-unknown" || reason === "remote-connection-failed") {
return this.finishDisconnection();
}
shared_api.connection.reconnect();
} else {
return this.finishDisconnection();
}
}
/**
* Callback method called by Strophe as the Connection goes
* through various states while establishing or tearing down a
* connection.
* @param { Number } status
* @param { String } message
*/
onConnectStatusChanged(status, message) {
const {
__
} = shared_converse;
log.debug(`Status changed to: ${CONNECTION_STATUS[status]}`);
if (status === core.Status.ATTACHFAIL) {
this.setConnectionStatus(status);
this.worker_attach_promise?.resolve(false);
} else if (status === core.Status.CONNECTED || status === core.Status.ATTACHED) {
if (this.worker_attach_promise?.isResolved && this.status === core.Status.ATTACHED) {
// A different tab must have attached, so nothing to do for us here.
return;
}
this.setConnectionStatus(status);
this.worker_attach_promise?.resolve(true);
// By default we always want to send out an initial presence stanza.
shared_converse.send_initial_presence = true;
this.setDisconnectionCause();
if (this.reconnecting) {
log.debug(status === core.Status.CONNECTED ? 'Reconnected' : 'Reattached');
this.onConnected(true);
} else {
log.debug(status === core.Status.CONNECTED ? 'Connected' : 'Attached');
if (this.restored) {
// No need to send an initial presence stanza when
// we're restoring an existing session.
shared_converse.send_initial_presence = false;
}
this.onConnected();
}
} else if (status === core.Status.DISCONNECTED) {
this.setDisconnectionCause(status, message);
this.onDisconnected();
} else if (status === core.Status.BINDREQUIRED) {
this.bind();
} else if (status === core.Status.ERROR) {
this.setConnectionStatus(status, __('An error occurred while connecting to the chat server.'));
} else if (status === core.Status.CONNECTING) {
this.setConnectionStatus(status);
} else if (status === core.Status.AUTHENTICATING) {
this.setConnectionStatus(status);
} else if (status === core.Status.AUTHFAIL) {
if (!message) {
message = __('Your XMPP address and/or password is incorrect. Please try again.');
}
this.setConnectionStatus(status, message);
this.setDisconnectionCause(status, message, true);
this.onDisconnected();
} else if (status === core.Status.CONNFAIL) {
let feedback = message;
if (message === "host-unknown" || message == "remote-connection-failed") {
feedback = __("Sorry, we could not connect to the XMPP host with domain: %1$s", `\"${core.getDomainFromJid(this.jid)}\"`);
} else if (message !== undefined && message === core?.ErrorCondition?.NO_AUTH_MECH) {
feedback = __("The XMPP server did not offer a supported authentication mechanism");
}
this.setConnectionStatus(status, feedback);
this.setDisconnectionCause(status, message);
} else if (status === core.Status.DISCONNECTING) {
this.setDisconnectionCause(status, message);
}
}
isType(type) {
if (type.toLowerCase() === 'websocket') {
return this._proto instanceof core.Websocket;
} else if (type.toLowerCase() === 'bosh') {
return core.Bosh && this._proto instanceof core.Bosh;
}
}
hasResumed() {
if (shared_api.settings.get("connection_options")?.worker || this.isType('bosh')) {
return shared_converse.connfeedback.get('connection_status') === core.Status.ATTACHED;
} else {
// Not binding means that the session was resumed.
return !this.do_bind;
}
}
restoreWorkerSession() {
this.attach(this.onConnectStatusChanged);
this.worker_attach_promise = getOpenPromise();
return this.worker_attach_promise;
}
}
/**
* The MockConnection class is used during testing, to mock an XMPP connection.
* @class
*/
class MockConnection extends connection_Connection {
constructor(service, options) {
super(service, options);
this.sent_stanzas = [];
this.IQ_stanzas = [];
this.IQ_ids = [];
this.features = core.xmlHtmlNode('<stream:features xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">' + '<ver xmlns="urn:xmpp:features:rosterver"/>' + '<csi xmlns="urn:xmpp:csi:0"/>' + '<this xmlns="http://jabber.org/protocol/caps" ver="UwBpfJpEt3IoLYfWma/o/p3FFRo=" hash="sha-1" node="http://prosody.im"/>' + '<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">' + '<required/>' + '</bind>' + `<sm xmlns='urn:xmpp:sm:3'/>` + '<session xmlns="urn:ietf:params:xml:ns:xmpp-session">' + '<optional/>' + '</session>' + '</stream:features>').firstChild;
this._proto._processRequest = () => {};
this._proto._disconnect = () => this._onDisconnectTimeout();
this._proto._onDisconnectTimeout = () => {};
this._proto._connect = () => {
this.connected = true;
this.mock = true;
this.jid = 'romeo@montague.lit/orchard';
this._changeConnectStatus(core.Status.BINDREQUIRED);
};
}
_processRequest() {// eslint-disable-line class-methods-use-this
// Don't attempt to send out stanzas
}
sendIQ(iq, callback, errback) {
iq = iq.tree?.() ?? iq;
this.IQ_stanzas.push(iq);
const id = super.sendIQ(iq, callback, errback);
this.IQ_ids.push(id);
return id;
}
send(stanza) {
stanza = stanza.tree?.() ?? stanza;
this.sent_stanzas.push(stanza);
return super.send(stanza);
}
async bind() {
await shared_api.trigger('beforeResourceBinding', {
'synchronous': true
});
this.authenticated = true;
if (!shared_converse.no_connection_on_bind) {
this._changeConnectStatus(core.Status.CONNECTED);
}
}
}
;// CONCATENATED MODULE: ./src/headless/utils/init.js
function setUpXMLLogging() {
const lmap = {};
lmap[core.LogLevel.DEBUG] = 'debug';
lmap[core.LogLevel.INFO] = 'info';
lmap[core.LogLevel.WARN] = 'warn';
lmap[core.LogLevel.ERROR] = 'error';
lmap[core.LogLevel.FATAL] = 'fatal';
core.log = (level, msg) => log.log(msg, lmap[level]);
core.error = msg => log.error(msg);
shared_converse.connection.xmlInput = body => log.debug(body.outerHTML, 'color: darkgoldenrod');
shared_converse.connection.xmlOutput = body => log.debug(body.outerHTML, 'color: darkcyan');
}
function getConnectionServiceURL() {
const {
api
} = shared_converse;
if (('WebSocket' in window || 'MozWebSocket' in window) && api.settings.get("websocket_url")) {
return api.settings.get('websocket_url');
} else if (api.settings.get('bosh_service_url')) {
return api.settings.get('bosh_service_url');
}
return '';
}
function initConnection() {
const api = shared_converse.api;
if (!api.settings.get('bosh_service_url')) {
if (api.settings.get("authentication") === PREBIND) {
throw new Error("authentication is set to 'prebind' but we don't have a BOSH connection");
}
}
const XMPPConnection = shared_converse.isTestEnv() ? MockConnection : connection_Connection;
shared_converse.connection = new XMPPConnection(getConnectionServiceURL(), Object.assign(shared_converse.default_connection_options, api.settings.get("connection_options"), {
'keepalive': api.settings.get("keepalive")
}));
setUpXMLLogging();
/**
* Triggered once the `Connection` constructor has been initialized, which
* will be responsible for managing the connection to the XMPP server.
*
* @event _converse#connectionInitialized
*/
api.trigger('connectionInitialized');
}
function initPlugins(_converse) {
// If initialize gets called a second time (e.g. during tests), then we
// need to re-apply all plugins (for a new converse instance), and we
// therefore need to clear this array that prevents plugins from being
// initialized twice.
// If initialize is called for the first time, then this array is empty
// in any case.
_converse.pluggable.initialized_plugins = [];
const whitelist = CORE_PLUGINS.concat(_converse.api.settings.get("whitelisted_plugins"));
if (_converse.api.settings.get("singleton")) {
['converse-bookmarks', 'converse-controlbox', 'converse-headline', 'converse-register'].forEach(name => _converse.api.settings.get("blacklisted_plugins").push(name));
}
_converse.pluggable.initializePlugins({
_converse
}, whitelist, _converse.api.settings.get("blacklisted_plugins"));
/**
* Triggered once all plugins have been initialized. This is a useful event if you want to
* register event handlers but would like your own handlers to be overridable by
* plugins. In that case, you need to first wait until all plugins have been
* initialized, so that their overrides are active. One example where this is used
* is in [converse-notifications.js](https://github.com/jcbrand/converse.js/blob/master/src/converse-notification.js)`.
*
* Also available as an [ES2015 Promise](http://es6-features.org/#PromiseUsage)
* which can be listened to with `_converse.api.waitUntil`.
*
* @event _converse#pluginsInitialized
* @memberOf _converse
* @example _converse.api.listen.on('pluginsInitialized', () => { ... });
*/
_converse.api.trigger('pluginsInitialized');
}
async function initClientConfig(_converse) {
/* The client config refers to configuration of the client which is
* independent of any particular user.
* What this means is that config values need to persist across
* user sessions.
*/
const id = 'converse.client-config';
_converse.config = new Model({
id,
'trusted': true
});
_converse.config.browserStorage = createStore(id, "session");
await new Promise(r => _converse.config.fetch({
'success': r,
'error': r
}));
/**
* Triggered once the XMPP-client configuration has been initialized.
* The client configuration is independent of any particular and its values
* persist across user sessions.
*
* @event _converse#clientConfigInitialized
* @example
* _converse.api.listen.on('clientConfigInitialized', () => { ... });
*/
_converse.api.trigger('clientConfigInitialized');
}
async function initSessionStorage(_converse) {
await storage.sessionStorageInitialized;
_converse.storage = {
'session': storage.localForage.createInstance({
'name': _converse.isTestEnv() ? 'converse-test-session' : 'converse-session',
'description': 'sessionStorage instance',
'driver': ['sessionStorageWrapper']
})
};
}
function initPersistentStorage(_converse, store_name) {
if (_converse.api.settings.get('persistent_store') === 'sessionStorage') {
return;
} else if (_converse.api.settings.get("persistent_store") === 'BrowserExtLocal') {
storage.localForage.defineDriver(local/* default */.Z).then(() => storage.localForage.setDriver('webExtensionLocalStorage'));
_converse.storage['persistent'] = storage.localForage;
return;
} else if (_converse.api.settings.get("persistent_store") === 'BrowserExtSync') {
storage.localForage.defineDriver(localforage_webextensionstorage_driver_sync/* default */.Z).then(() => storage.localForage.setDriver('webExtensionSyncStorage'));
_converse.storage['persistent'] = storage.localForage;
return;
}
const config = {
'name': _converse.isTestEnv() ? 'converse-test-persistent' : 'converse-persistent',
'storeName': store_name
};
if (_converse.api.settings.get("persistent_store") === 'localStorage') {
config['description'] = 'localStorage instance';
config['driver'] = [storage.localForage.LOCALSTORAGE];
} else if (_converse.api.settings.get("persistent_store") === 'IndexedDB') {
config['description'] = 'indexedDB instance';
config['driver'] = [storage.localForage.INDEXEDDB];
}
_converse.storage['persistent'] = storage.localForage.createInstance(config);
}
function saveJIDtoSession(_converse, jid) {
jid = _converse.session.get('jid') || jid;
if (_converse.api.settings.get("authentication") !== ANONYMOUS && !core.getResourceFromJid(jid)) {
jid = jid.toLowerCase() + connection_Connection.generateResource();
}
_converse.jid = jid;
_converse.bare_jid = core.getBareJidFromJid(jid);
_converse.resource = core.getResourceFromJid(jid);
_converse.domain = core.getDomainFromJid(jid);
_converse.session.save({
'jid': jid,
'bare_jid': _converse.bare_jid,
'resource': _converse.resource,
'domain': _converse.domain,
// We use the `active` flag to determine whether we should use the values from sessionStorage.
// When "cloning" a tab (e.g. via middle-click), the `active` flag will be set and we'll create
// a new empty user session, otherwise it'll be false and we can re-use the user session.
// When the tab is reloaded, the `active` flag is set to `false`.
'active': true
});
// Set JID on the connection object so that when we call `connection.bind`
// the new resource is found by Strophe.js and sent to the XMPP server.
_converse.connection.jid = jid;
}
/**
* Stores the passed in JID for the current user, potentially creating a
* resource if the JID is bare.
*
* Given that we can only create an XMPP connection if we know the domain of
* the server connect to and we only know this once we know the JID, we also
* call {@link initConnection } (if necessary) to make sure that the
* connection is set up.
*
* @emits _converse#setUserJID
* @params { String } jid
*/
async function setUserJID(jid) {
await initSession(shared_converse, jid);
/**
* Triggered whenever the user's JID has been updated
* @event _converse#setUserJID
*/
shared_converse.api.trigger('setUserJID');
return jid;
}
async function initSession(_converse, jid) {
const is_shared_session = _converse.api.settings.get('connection_options').worker;
const bare_jid = core.getBareJidFromJid(jid).toLowerCase();
const id = `converse.session-${bare_jid}`;
if (_converse.session?.get('id') !== id) {
initPersistentStorage(_converse, bare_jid);
_converse.session = new Model({
id
});
initStorage(_converse.session, id, is_shared_session ? "persistent" : "session");
await new Promise(r => _converse.session.fetch({
'success': r,
'error': r
}));
if (!is_shared_session && _converse.session.get('active')) {
// If the `active` flag is set, it means this tab was cloned from
// another (e.g. via middle-click), and its session data was copied over.
_converse.session.clear();
_converse.session.save({
id
});
}
saveJIDtoSession(_converse, jid);
// Set `active` flag to false when the tab gets reloaded
window.addEventListener(_converse.unloadevent, () => _converse.session?.save('active', false));
/**
* Triggered once the user's session has been initialized. The session is a
* cache which stores information about the user's current session.
* @event _converse#userSessionInitialized
* @memberOf _converse
*/
_converse.api.trigger('userSessionInitialized');
} else {
saveJIDtoSession(_converse, jid);
}
}
function registerGlobalEventHandlers(_converse) {
document.addEventListener("visibilitychange", saveWindowState);
saveWindowState({
'type': document.hidden ? "blur" : "focus"
}); // Set initial state
/**
* Called once Converse has registered its global event handlers
* (for events such as window resize or unload).
* Plugins can listen to this event as cue to register their own
* global event handlers.
* @event _converse#registeredGlobalEventHandlers
* @example _converse.api.listen.on('registeredGlobalEventHandlers', () => { ... });
*/
_converse.api.trigger('registeredGlobalEventHandlers');
}
function unregisterGlobalEventHandlers(_converse) {
const {
api
} = _converse;
document.removeEventListener("visibilitychange", saveWindowState);
api.trigger('unregisteredGlobalEventHandlers');
}
// Make sure everything is reset in case this is a subsequent call to
// converse.initialize (happens during tests).
async function cleanup(_converse) {
const {
api
} = _converse;
await api.trigger('cleanup', {
'synchronous': true
});
_converse.router.history.stop();
unregisterGlobalEventHandlers(_converse);
_converse.connection?.reset();
_converse.stopListening();
_converse.off();
if (_converse.promises['initialized'].isResolved) {
api.promises.add('initialized');
}
}
function fetchLoginCredentials() {
let wait = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
return new Promise(lodash_es_debounce(async (resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', shared_converse.api.settings.get("credentials_url"), true);
xhr.setRequestHeader('Accept', 'application/json, text/javascript');
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 400) {
const data = JSON.parse(xhr.responseText);
setUserJID(data.jid).then(() => {
resolve({
jid: data.jid,
password: data.password
});
});
} else {
reject(new Error(`${xhr.status}: ${xhr.responseText}`));
}
};
xhr.onerror = reject;
/**
* *Hook* which allows modifying the server request
* @event _converse#beforeFetchLoginCredentials
*/
xhr = await shared_converse.api.hook('beforeFetchLoginCredentials', this, xhr);
xhr.send();
}, wait));
}
async function getLoginCredentialsFromURL() {
let credentials;
let wait = 0;
while (!credentials) {
try {
credentials = await fetchLoginCredentials(wait); // eslint-disable-line no-await-in-loop
} catch (e) {
log.error('Could not fetch login credentials');
log.error(e);
}
// If unsuccessful, we wait 2 seconds between subsequent attempts to
// fetch the credentials.
wait = 2000;
}
return credentials;
}
async function getLoginCredentialsFromBrowser() {
const jid = localStorage.getItem('conversejs-session-jid');
if (!jid) return null;
try {
const creds = await navigator.credentials.get({
password: true
});
if (creds && creds.type == 'password' && isValidJID(creds.id)) {
// XXX: We don't actually compare `creds.id` with `jid` because
// the user might have been presented a list of credentials with
// which to log in, and we want to respect their wish.
await setUserJID(creds.id);
return {
'jid': creds.id,
'password': creds.password
};
}
} catch (e) {
log.error(e);
return null;
}
}
async function getLoginCredentialsFromSCRAMKeys() {
const jid = localStorage.getItem('conversejs-session-jid');
if (!jid) return null;
await setUserJID(jid);
const login_info = await savedLoginInfo(jid);
const scram_keys = login_info.get('scram_keys');
return scram_keys ? {
jid,
'password': scram_keys
} : null;
}
async function attemptNonPreboundSession(credentials, automatic) {
const {
api
} = shared_converse;
if (api.settings.get("authentication") === LOGIN) {
// XXX: If EITHER ``keepalive`` or ``auto_login`` is ``true`` and
// ``authentication`` is set to ``login``, then Converse will try to log the user in,
// since we don't have a way to distinguish between wether we're
// restoring a previous session (``keepalive``) or whether we're
// automatically setting up a new session (``auto_login``).
// So we can't do the check (!automatic || _converse.api.settings.get("auto_login")) here.
if (credentials) {
return connect(credentials);
} else if (api.settings.get("credentials_url")) {
// We give credentials_url preference, because
// _converse.connection.pass might be an expired token.
return connect(await getLoginCredentialsFromURL());
} else if (shared_converse.jid && (api.settings.get("password") || shared_converse.connection.pass)) {
return connect();
}
if (api.settings.get('reuse_scram_keys')) {
const credentials = await getLoginCredentialsFromSCRAMKeys();
if (credentials) return connect(credentials);
}
if (!shared_converse.isTestEnv() && 'credentials' in navigator) {
const credentials = await getLoginCredentialsFromBrowser();
if (credentials) return connect(credentials);
}
if (!shared_converse.isTestEnv()) log.warn("attemptNonPreboundSession: Couldn't find credentials to log in with");
} else if ([ANONYMOUS, EXTERNAL].includes(api.settings.get("authentication")) && (!automatic || api.settings.get("auto_login"))) {
connect();
}
}
/**
* Fetch the stored SCRAM keys for the given JID, if available.
*
* The user's plaintext password is not stored, nor any material from which
* the user's plaintext password could be recovered.
*
* @param { String } jid - The XMPP address for which to fetch the SCRAM keys
* @returns { Promise } A promise which resolves once we've fetched the previously
* used login keys.
*/
async function savedLoginInfo(jid) {
const id = `converse.scram-keys-${core.getBareJidFromJid(jid)}`;
const login_info = new Model({
id
});
initStorage(login_info, id, 'persistent');
await new Promise(f => login_info.fetch({
'success': f,
'error': f
}));
return login_info;
}
/**
* @param { Object } [credentials]
* @param { string } credentials.password
* @param { Object } credentials.password
* @param { string } credentials.password.ck
* @returns { Promise<void> }
*/
async function connect(credentials) {
const {
api
} = shared_converse;
if ([ANONYMOUS, EXTERNAL].includes(api.settings.get("authentication"))) {
if (!shared_converse.jid) {
throw new Error("Config Error: when using anonymous login " + "you need to provide the server's domain via the 'jid' option. " + "Either when calling converse.initialize, or when calling " + "_converse.api.user.login.");
}
if (!shared_converse.connection.reconnecting) {
shared_converse.connection.reset();
}
shared_converse.connection.connect(shared_converse.jid.toLowerCase());
} else if (api.settings.get("authentication") === LOGIN) {
const password = credentials?.password ?? (shared_converse.connection?.pass || api.settings.get("password"));
if (!password) {
if (api.settings.get("auto_login")) {
throw new Error("autoLogin: If you use auto_login and " + "authentication='login' then you also need to provide a password.");
}
shared_converse.connection.setDisconnectionCause(core.Status.AUTHFAIL, undefined, true);
api.connection.disconnect();
return;
}
if (!shared_converse.connection.reconnecting) {
shared_converse.connection.reset();
shared_converse.connection.service = getConnectionServiceURL();
}
let callback;
// Save the SCRAM data if we're not already logged in with SCRAM
if (shared_converse.config.get('trusted') && shared_converse.jid && api.settings.get("reuse_scram_keys") && !password?.ck) {
// Store scram keys in scram storage
const login_info = await savedLoginInfo(shared_converse.jid);
callback = status => {
const {
scram_keys
} = shared_converse.connection;
if (scram_keys) login_info.save({
scram_keys
});
shared_converse.connection.onConnectStatusChanged(status);
};
}
shared_converse.connection.connect(shared_converse.jid, password, callback);
}
}
;// CONCATENATED MODULE: ./src/headless/shared/api/user.js
/* harmony default export */ const user = ({
/**
* This grouping collects API functions related to the current logged in user.
*
* @namespace _converse.api.user
* @memberOf _converse.api
*/
user: {
settings: user_settings_api,
...presence,
/**
* @method _converse.api.user.jid
* @returns {string} The current user's full JID (Jabber ID)
* @example _converse.api.user.jid())
*/
jid() {
return shared_converse.connection.jid;
},
/**
* Logs the user in.
*
* If called without any parameters, Converse will try
* to log the user in by calling the `prebind_url` or `credentials_url` depending
* on whether prebinding is used or not.
*
* @method _converse.api.user.login
* @param { string } [jid]
* @param { string } [password]
* @param { boolean } [automatic=false] - An internally used flag that indicates whether
* this method was called automatically once the connection has been
* initialized. It's used together with the `auto_login` configuration flag
* to determine whether Converse should try to log the user in if it
* fails to restore a previous auth'd session.
* @returns { Promise<void> }
*/
async login(jid, password) {
let automatic = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
const {
api
} = shared_converse;
jid = jid || api.settings.get('jid');
if (!shared_converse.connection?.jid || jid && !utils_core.isSameDomain(shared_converse.connection.jid, jid)) {
initConnection();
}
if (api.settings.get("connection_options")?.worker && (await shared_converse.connection.restoreWorkerSession())) {
return;
}
if (jid) {
jid = await setUserJID(jid);
}
// See whether there is a BOSH session to re-attach to
const bosh_plugin = shared_converse.pluggable.plugins['converse-bosh'];
if (bosh_plugin?.enabled()) {
if (await shared_converse.restoreBOSHSession()) {
return;
} else if (api.settings.get("authentication") === PREBIND && (!automatic || api.settings.get("auto_login"))) {
return shared_converse.startNewPreboundBOSHSession();
}
}
password = password || api.settings.get("password");
const credentials = jid && password ? {
jid,
password
} : null;
attemptNonPreboundSession(credentials, automatic);
},
/**
* Logs the user out of the current XMPP session.
* @method _converse.api.user.logout
* @example _converse.api.user.logout();
*/
async logout() {
const {
api
} = shared_converse;
/**
* Triggered before the user is logged out
* @event _converse#beforeLogout
*/
await api.trigger('beforeLogout', {
'synchronous': true
});
const promise = getOpenPromise();
const complete = () => {
// Recreate all the promises
Object.keys(shared_converse.promises).forEach(replacePromise);
delete shared_converse.jid;
// Remove the session JID, otherwise the user would just be logged
// in again upon reload. See #2759
localStorage.removeItem('conversejs-session-jid');
/**
* Triggered once the user has logged out.
* @event _converse#logout
*/
api.trigger('logout');
promise.resolve();
};
shared_converse.connection.setDisconnectionCause(LOGOUT, undefined, true);
if (shared_converse.connection !== undefined) {
api.listen.once('disconnected', () => complete());
shared_converse.connection.disconnect();
} else {
complete();
}
return promise;
}
}
});
;// CONCATENATED MODULE: ./src/headless/shared/api/index.js
/**
* ### The private API
*
* The private API methods are only accessible via the closured {@link _converse}
* object, which is only available to plugins.
*
* These methods are kept private (i.e. not global) because they may return
* sensitive data which should be kept off-limits to other 3rd-party scripts
* that might be running in the page.
*
* @namespace _converse.api
* @memberOf _converse
*/
const api_api = shared_converse.api = {
connection: connection_api,
settings: settings_api,
...send,
...user,
...events,
...promise
};
/* harmony default export */ const shared_api = (api_api);
// EXTERNAL MODULE: ./node_modules/dayjs/dayjs.min.js
var dayjs_min = __webpack_require__(484);
var dayjs_min_default = /*#__PURE__*/__webpack_require__.n(dayjs_min);
;// CONCATENATED MODULE: ./src/headless/shared/connection/feedback.js
/* harmony default export */ const feedback = (Model.extend({
defaults: {
'connection_status': core.Status.DISCONNECTED,
'message': ''
},
initialize() {
const {
api
} = shared_converse;
this.on('change', () => api.trigger('connfeedback', shared_converse.connfeedback));
}
}));
// EXTERNAL MODULE: ./node_modules/urijs/src/URI.js
var URI = __webpack_require__(988);
var URI_default = /*#__PURE__*/__webpack_require__.n(URI);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayAggregator.js
/**
* A specialized version of `baseAggregator` for arrays.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
*/
function arrayAggregator(array, setter, iteratee, accumulator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
var value = array[index];
setter(accumulator, value, iteratee(value), array);
}
return accumulator;
}
/* harmony default export */ const _arrayAggregator = (arrayAggregator);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseAggregator.js
/**
* Aggregates elements of `collection` on `accumulator` with keys transformed
* by `iteratee` and values set by `setter`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
*/
function baseAggregator(collection, setter, iteratee, accumulator) {
_baseEach(collection, function(value, key, collection) {
setter(accumulator, value, iteratee(value), collection);
});
return accumulator;
}
/* harmony default export */ const _baseAggregator = (baseAggregator);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_createAggregator.js
/**
* Creates a function like `_.groupBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} [initializer] The accumulator object initializer.
* @returns {Function} Returns the new aggregator function.
*/
function createAggregator(setter, initializer) {
return function(collection, iteratee) {
var func = lodash_es_isArray(collection) ? _arrayAggregator : _baseAggregator,
accumulator = initializer ? initializer() : {};
return func(collection, setter, _baseIteratee(iteratee, 2), accumulator);
};
}
/* harmony default export */ const _createAggregator = (createAggregator);
;// CONCATENATED MODULE: ./node_modules/lodash-es/countBy.js
/** Used for built-in method references. */
var countBy_objectProto = Object.prototype;
/** Used to check objects for own properties. */
var countBy_hasOwnProperty = countBy_objectProto.hasOwnProperty;
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the number of times the key was returned by `iteratee`. The
* iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.5.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.countBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': 1, '6': 2 }
*
* // The `_.property` iteratee shorthand.
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
*/
var countBy = _createAggregator(function(result, value, key) {
if (countBy_hasOwnProperty.call(result, key)) {
++result[key];
} else {
_baseAssignValue(result, key, 1);
}
});
/* harmony default export */ const lodash_es_countBy = (countBy);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseFindIndex.js
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
/* harmony default export */ const _baseFindIndex = (baseFindIndex);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsNaN.js
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
/* harmony default export */ const _baseIsNaN = (baseIsNaN);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_strictIndexOf.js
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/* harmony default export */ const _strictIndexOf = (strictIndexOf);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIndexOf.js
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
return value === value
? _strictIndexOf(array, value, fromIndex)
: _baseFindIndex(array, _baseIsNaN, fromIndex);
}
/* harmony default export */ const _baseIndexOf = (baseIndexOf);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayIncludes.js
/**
* A specialized version of `_.includes` for arrays without support for
* specifying an index to search from.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludes(array, value) {
var length = array == null ? 0 : array.length;
return !!length && _baseIndexOf(array, value, 0) > -1;
}
/* harmony default export */ const _arrayIncludes = (arrayIncludes);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayIncludesWith.js
/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludesWith(array, value, comparator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
/* harmony default export */ const _arrayIncludesWith = (arrayIncludesWith);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseDifference.js
/** Used as the size to enable large array optimizations. */
var _baseDifference_LARGE_ARRAY_SIZE = 200;
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values, iteratee, comparator) {
var index = -1,
includes = _arrayIncludes,
isCommon = true,
length = array.length,
result = [],
valuesLength = values.length;
if (!length) {
return result;
}
if (iteratee) {
values = _arrayMap(values, _baseUnary(iteratee));
}
if (comparator) {
includes = _arrayIncludesWith;
isCommon = false;
}
else if (values.length >= _baseDifference_LARGE_ARRAY_SIZE) {
includes = _cacheHas;
isCommon = false;
values = new _SetCache(values);
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee == null ? value : iteratee(value);
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
return result;
}
/* harmony default export */ const _baseDifference = (baseDifference);
;// CONCATENATED MODULE: ./node_modules/lodash-es/difference.js
/**
* Creates an array of `array` values not included in the other given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* **Note:** Unlike `_.pullAll`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.without, _.xor
* @example
*
* _.difference([2, 1], [2, 3]);
* // => [1]
*/
var difference = _baseRest(function(array, values) {
return lodash_es_isArrayLikeObject(array)
? _baseDifference(array, _baseFlatten(values, 1, lodash_es_isArrayLikeObject, true))
: [];
});
/* harmony default export */ const lodash_es_difference = (difference);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayEvery.js
/**
* A specialized version of `_.every` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
*/
function arrayEvery(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (!predicate(array[index], index, array)) {
return false;
}
}
return true;
}
/* harmony default export */ const _arrayEvery = (arrayEvery);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseEvery.js
/**
* The base implementation of `_.every` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`
*/
function baseEvery(collection, predicate) {
var result = true;
_baseEach(collection, function(value, index, collection) {
result = !!predicate(value, index, collection);
return result;
});
return result;
}
/* harmony default export */ const _baseEvery = (baseEvery);
;// CONCATENATED MODULE: ./node_modules/lodash-es/every.js
/**
* Checks if `predicate` returns truthy for **all** elements of `collection`.
* Iteration is stopped once `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* **Note:** This method returns `true` for
* [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
* [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
* elements of empty collections.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.every(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.every(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.every(users, 'active');
* // => false
*/
function every(collection, predicate, guard) {
var func = lodash_es_isArray(collection) ? _arrayEvery : _baseEvery;
if (guard && _isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, _baseIteratee(predicate, 3));
}
/* harmony default export */ const lodash_es_every = (every);
;// CONCATENATED MODULE: ./node_modules/lodash-es/findIndex.js
/* Built-in method references for those with the same name as other `lodash` methods. */
var findIndex_nativeMax = Math.max;
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : lodash_es_toInteger(fromIndex);
if (index < 0) {
index = findIndex_nativeMax(length + index, 0);
}
return _baseFindIndex(array, _baseIteratee(predicate, 3), index);
}
/* harmony default export */ const lodash_es_findIndex = (findIndex);
;// CONCATENATED MODULE: ./node_modules/lodash-es/findLastIndex.js
/* Built-in method references for those with the same name as other `lodash` methods. */
var findLastIndex_nativeMax = Math.max,
findLastIndex_nativeMin = Math.min;
/**
* This method is like `_.findIndex` except that it iterates over elements
* of `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
* // => 2
*
* // The `_.matches` iteratee shorthand.
* _.findLastIndex(users, { 'user': 'barney', 'active': true });
* // => 0
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastIndex(users, ['active', false]);
* // => 2
*
* // The `_.property` iteratee shorthand.
* _.findLastIndex(users, 'active');
* // => 0
*/
function findLastIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = length - 1;
if (fromIndex !== undefined) {
index = lodash_es_toInteger(fromIndex);
index = fromIndex < 0
? findLastIndex_nativeMax(length + index, 0)
: findLastIndex_nativeMin(index, length - 1);
}
return _baseFindIndex(array, _baseIteratee(predicate, 3), index, true);
}
/* harmony default export */ const lodash_es_findLastIndex = (findLastIndex);
;// CONCATENATED MODULE: ./node_modules/lodash-es/groupBy.js
/** Used for built-in method references. */
var groupBy_objectProto = Object.prototype;
/** Used to check objects for own properties. */
var groupBy_hasOwnProperty = groupBy_objectProto.hasOwnProperty;
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The order of grouped values
* is determined by the order they occur in `collection`. The corresponding
* value of each key is an array of elements responsible for generating the
* key. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.groupBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': [4.2], '6': [6.1, 6.3] }
*
* // The `_.property` iteratee shorthand.
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
var groupBy = _createAggregator(function(result, value, key) {
if (groupBy_hasOwnProperty.call(result, key)) {
result[key].push(value);
} else {
_baseAssignValue(result, key, [value]);
}
});
/* harmony default export */ const lodash_es_groupBy = (groupBy);
;// CONCATENATED MODULE: ./node_modules/lodash-es/indexOf.js
/* Built-in method references for those with the same name as other `lodash` methods. */
var indexOf_nativeMax = Math.max;
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/
function indexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : lodash_es_toInteger(fromIndex);
if (index < 0) {
index = indexOf_nativeMax(length + index, 0);
}
return _baseIndexOf(array, value, index);
}
/* harmony default export */ const lodash_es_indexOf = (indexOf);
;// CONCATENATED MODULE: ./node_modules/lodash-es/keyBy.js
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the last element responsible for generating the key. The
* iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* var array = [
* { 'dir': 'left', 'code': 97 },
* { 'dir': 'right', 'code': 100 }
* ];
*
* _.keyBy(array, function(o) {
* return String.fromCharCode(o.code);
* });
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*
* _.keyBy(array, 'dir');
* // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
*/
var keyBy = _createAggregator(function(result, value, key) {
_baseAssignValue(result, key, value);
});
/* harmony default export */ const lodash_es_keyBy = (keyBy);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_strictLastIndexOf.js
/**
* A specialized version of `_.lastIndexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictLastIndexOf(array, value, fromIndex) {
var index = fromIndex + 1;
while (index--) {
if (array[index] === value) {
return index;
}
}
return index;
}
/* harmony default export */ const _strictLastIndexOf = (strictLastIndexOf);
;// CONCATENATED MODULE: ./node_modules/lodash-es/lastIndexOf.js
/* Built-in method references for those with the same name as other `lodash` methods. */
var lastIndexOf_nativeMax = Math.max,
lastIndexOf_nativeMin = Math.min;
/**
* This method is like `_.indexOf` except that it iterates over elements of
* `array` from right to left.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.lastIndexOf([1, 2, 1, 2], 2);
* // => 3
*
* // Search from the `fromIndex`.
* _.lastIndexOf([1, 2, 1, 2], 2, 2);
* // => 1
*/
function lastIndexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = length;
if (fromIndex !== undefined) {
index = lodash_es_toInteger(fromIndex);
index = index < 0 ? lastIndexOf_nativeMax(length + index, 0) : lastIndexOf_nativeMin(index, length - 1);
}
return value === value
? _strictLastIndexOf(array, value, index)
: _baseFindIndex(array, _baseIsNaN, index, true);
}
/* harmony default export */ const lodash_es_lastIndexOf = (lastIndexOf);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseMap.js
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = lodash_es_isArrayLike(collection) ? Array(collection.length) : [];
_baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
/* harmony default export */ const _baseMap = (baseMap);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSortBy.js
/**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
/* harmony default export */ const _baseSortBy = (baseSortBy);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_compareAscending.js
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = lodash_es_isSymbol(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = lodash_es_isSymbol(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
/* harmony default export */ const _compareAscending = (compareAscending);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_compareMultiple.js
/**
* Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
* specify an order of "desc" for descending or "asc" for ascending sort order
* of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length,
ordersLength = orders.length;
while (++index < length) {
var result = _compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
return result * (order == 'desc' ? -1 : 1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
/* harmony default export */ const _compareMultiple = (compareMultiple);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseOrderBy.js
/**
* The base implementation of `_.orderBy` without param guards.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {string[]} orders The sort orders of `iteratees`.
* @returns {Array} Returns the new sorted array.
*/
function baseOrderBy(collection, iteratees, orders) {
if (iteratees.length) {
iteratees = _arrayMap(iteratees, function(iteratee) {
if (lodash_es_isArray(iteratee)) {
return function(value) {
return _baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
}
}
return iteratee;
});
} else {
iteratees = [lodash_es_identity];
}
var index = -1;
iteratees = _arrayMap(iteratees, _baseUnary(_baseIteratee));
var result = _baseMap(collection, function(value, key, collection) {
var criteria = _arrayMap(iteratees, function(iteratee) {
return iteratee(value);
});
return { 'criteria': criteria, 'index': ++index, 'value': value };
});
return _baseSortBy(result, function(object, other) {
return _compareMultiple(object, other, orders);
});
}
/* harmony default export */ const _baseOrderBy = (baseOrderBy);
;// CONCATENATED MODULE: ./node_modules/lodash-es/sortBy.js
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection thru each iteratee. This method
* performs a stable sort, that is, it preserves the original sort order of
* equal elements. The iteratees are invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to sort by.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 30 },
* { 'user': 'barney', 'age': 34 }
* ];
*
* _.sortBy(users, [function(o) { return o.user; }]);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
*
* _.sortBy(users, ['user', 'age']);
* // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
*/
var sortBy = _baseRest(function(collection, iteratees) {
if (collection == null) {
return [];
}
var length = iteratees.length;
if (length > 1 && _isIterateeCall(collection, iteratees[0], iteratees[1])) {
iteratees = [];
} else if (length > 2 && _isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
iteratees = [iteratees[0]];
}
return _baseOrderBy(collection, _baseFlatten(iteratees, 1), []);
});
/* harmony default export */ const lodash_es_sortBy = (sortBy);
;// CONCATENATED MODULE: ./node_modules/@converse/skeletor/src/collection.js
// Backbone.js 1.4.0
// (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
// Backbone may be freely distributed under the MIT license.
// Collection
// ----------
// If models tend to represent a single row of data, a Collection is
// more analogous to a table full of data ... or a small slice or page of that
// table, or a collection of rows that belong together for a particular reason
// -- all of the messages in this particular folder, all of the documents
// belonging to this particular author, and so on. Collections maintain
// indexes of their models, both in order, and for lookup by `id`.
const slice = Array.prototype.slice;
// Create a new **Collection**, perhaps to contain a specific type of `model`.
// If a `comparator` is specified, the Collection will maintain
// its models in sort order, as they're added and removed.
const Collection = function (models, options) {
options || (options = {});
this.preinitialize.apply(this, arguments);
if (options.model) this.model = options.model;
if (options.comparator !== undefined) this.comparator = options.comparator;
this._reset();
this.initialize.apply(this, arguments);
if (models) this.reset(models, lodash_es_assignIn({
silent: true
}, options));
};
Collection.extend = inherits;
// Default options for `Collection#set`.
const setOptions = {
add: true,
remove: true,
merge: true
};
const addOptions = {
add: true,
remove: false
};
// Splices `insert` into `array` at index `at`.
const collection_splice = function (array, insert, at) {
at = Math.min(Math.max(at, 0), array.length);
const tail = Array(array.length - at);
const length = insert.length;
let i;
for (i = 0; i < tail.length; i++) tail[i] = array[i + at];
for (i = 0; i < length; i++) array[i + at] = insert[i];
for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i];
};
// Define the Collection's inheritable methods.
Object.assign(Collection.prototype, Events, {
// The default model for a collection is just a **Backbone.Model**.
// This should be overridden in most cases.
model: Model,
// preinitialize is an empty function by default. You can override it with a function
// or object. preinitialize will run before any instantiation logic is run in the Collection.
preinitialize: function () {},
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function () {},
// The JSON representation of a Collection is an array of the
// models' attributes.
toJSON: function (options) {
return this.map(function (model) {
return model.toJSON(options);
});
},
// Proxy `Backbone.sync` by default.
sync: function (method, model, options) {
return getSyncMethod(this)(method, model, options);
},
// Add a model, or list of models to the set. `models` may be Backbone
// Models or raw JavaScript objects to be converted to Models, or any
// combination of the two.
add: function (models, options) {
return this.set(models, lodash_es_assignIn({
merge: false
}, options, addOptions));
},
// Remove a model, or a list of models from the set.
remove: function (models, options) {
options = lodash_es_assignIn({}, options);
const singular = !Array.isArray(models);
models = singular ? [models] : models.slice();
const removed = this._removeModels(models, options);
if (!options.silent && removed.length) {
options.changes = {
added: [],
merged: [],
removed: removed
};
this.trigger('update', this, options);
}
return singular ? removed[0] : removed;
},
// Update a collection by `set`-ing a new list of models, adding new ones,
// removing models that are no longer present, and merging models that
// already exist in the collection, as necessary. Similar to **Model#set**,
// the core operation for updating the data contained by the collection.
set: function (models, options) {
if (models == null) return;
options = lodash_es_assignIn({}, setOptions, options);
if (options.parse && !this._isModel(models)) {
models = this.parse(models, options) || [];
}
const singular = !Array.isArray(models);
models = singular ? [models] : models.slice();
let at = options.at;
if (at != null) at = +at;
if (at > this.length) at = this.length;
if (at < 0) at += this.length + 1;
const set = [];
const toAdd = [];
const toMerge = [];
const toRemove = [];
const modelMap = {};
const add = options.add;
const merge = options.merge;
const remove = options.remove;
let sort = false;
const sortable = this.comparator && at == null && options.sort !== false;
const sortAttr = lodash_es_isString(this.comparator) ? this.comparator : null;
// Turn bare objects into model references, and prevent invalid models
// from being added.
let model, i;
for (i = 0; i < models.length; i++) {
model = models[i];
// If a duplicate is found, prevent it from being added and
// optionally merge it into the existing model.
const existing = this.get(model);
if (existing) {
if (merge && model !== existing) {
let attrs = this._isModel(model) ? model.attributes : model;
if (options.parse) attrs = existing.parse(attrs, options);
existing.set(attrs, options);
toMerge.push(existing);
if (sortable && !sort) sort = existing.hasChanged(sortAttr);
}
if (!modelMap[existing.cid]) {
modelMap[existing.cid] = true;
set.push(existing);
}
models[i] = existing;
// If this is a new, valid model, push it to the `toAdd` list.
} else if (add) {
model = models[i] = this._prepareModel(model, options);
if (model) {
toAdd.push(model);
this._addReference(model, options);
modelMap[model.cid] = true;
set.push(model);
}
}
}
// Remove stale models.
if (remove) {
for (i = 0; i < this.length; i++) {
model = this.models[i];
if (!modelMap[model.cid]) toRemove.push(model);
}
if (toRemove.length) this._removeModels(toRemove, options);
}
// See if sorting is needed, update `length` and splice in new models.
let orderChanged = false;
const replace = !sortable && add && remove;
if (set.length && replace) {
orderChanged = this.length !== set.length || lodash_es_some(this.models, (m, index) => m !== set[index]);
this.models.length = 0;
collection_splice(this.models, set, 0);
this.length = this.models.length;
} else if (toAdd.length) {
if (sortable) sort = true;
collection_splice(this.models, toAdd, at == null ? this.length : at);
this.length = this.models.length;
}
// Silently sort the collection if appropriate.
if (sort) this.sort({
silent: true
});
// Unless silenced, it's time to fire all appropriate add/sort/update events.
if (!options.silent) {
for (i = 0; i < toAdd.length; i++) {
if (at != null) options.index = at + i;
model = toAdd[i];
model.trigger('add', model, this, options);
}
if (sort || orderChanged) this.trigger('sort', this, options);
if (toAdd.length || toRemove.length || toMerge.length) {
options.changes = {
added: toAdd,
removed: toRemove,
merged: toMerge
};
this.trigger('update', this, options);
}
}
// Return the added (or merged) model (or models).
return singular ? models[0] : models;
},
clearStore: async function () {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let filter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : o => o;
await Promise.all(this.models.filter(filter).map(m => {
return new Promise(resolve => {
m.destroy(Object.assign(options, {
'success': resolve,
'error': (m, e) => {
console.error(e);
resolve();
}
}));
});
}));
await this.browserStorage.clear();
this.reset();
},
// When you have more items than you want to add or remove individually,
// you can reset the entire set with a new list of models, without firing
// any granular `add` or `remove` events. Fires `reset` when finished.
// Useful for bulk operations and optimizations.
reset: function (models, options) {
options = options ? lodash_es_clone(options) : {};
for (let i = 0; i < this.models.length; i++) {
this._removeReference(this.models[i], options);
}
options.previousModels = this.models;
this._reset();
models = this.add(models, lodash_es_assignIn({
silent: true
}, options));
if (!options.silent) this.trigger('reset', this, options);
return models;
},
// Add a model to the end of the collection.
push: function (model, options) {
return this.add(model, lodash_es_assignIn({
at: this.length
}, options));
},
// Remove a model from the end of the collection.
pop: function (options) {
const model = this.at(this.length - 1);
return this.remove(model, options);
},
// Add a model to the beginning of the collection.
unshift: function (model, options) {
return this.add(model, lodash_es_assignIn({
at: 0
}, options));
},
// Remove a model from the beginning of the collection.
shift: function (options) {
const model = this.at(0);
return this.remove(model, options);
},
// Slice out a sub-array of models from the collection.
slice: function () {
return slice.apply(this.models, arguments);
},
filter: function (callback, thisArg) {
return this.models.filter(lodash_es_isFunction(callback) ? callback : m => m.matches(callback), thisArg);
},
every: function (pred) {
return lodash_es_every(this.models.map(m => m.attributes), pred);
},
difference: function (values) {
return lodash_es_difference(this.models, values);
},
max: function () {
return Math.max.apply(Math, this.models);
},
min: function () {
return Math.min.apply(Math, this.models);
},
drop: function () {
let n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
return this.models.slice(n);
},
some: function (pred) {
return lodash_es_some(this.models.map(m => m.attributes), pred);
},
sortBy: function (iteratee) {
return lodash_es_sortBy(this.models, lodash_es_isFunction(iteratee) ? iteratee : m => lodash_es_isString(iteratee) ? m.get(iteratee) : m.matches(iteratee));
},
isEmpty: function () {
return lodash_es_isEmpty(this.models);
},
keyBy: function (iteratee) {
return lodash_es_keyBy(this.models, iteratee);
},
each: function (callback, thisArg) {
return this.forEach(callback, thisArg);
},
forEach: function (callback, thisArg) {
return this.models.forEach(callback, thisArg);
},
includes: function (item) {
return this.models.includes(item);
},
size: function () {
return this.models.length;
},
countBy: function (f) {
return lodash_es_countBy(this.models, lodash_es_isFunction(f) ? f : m => lodash_es_isString(f) ? m.get(f) : m.matches(f));
},
groupBy: function (pred) {
return lodash_es_groupBy(this.models, lodash_es_isFunction(pred) ? pred : m => lodash_es_isString(pred) ? m.get(pred) : m.matches(pred));
},
indexOf: function (fromIndex) {
return lodash_es_indexOf(this.models, fromIndex);
},
findLastIndex: function (pred, fromIndex) {
return lodash_es_findLastIndex(this.models, lodash_es_isFunction(pred) ? pred : m => lodash_es_isString(pred) ? m.get(pred) : m.matches(pred), fromIndex);
},
lastIndexOf: function (fromIndex) {
return lodash_es_lastIndexOf(this.models, fromIndex);
},
findIndex: function (pred) {
return lodash_es_findIndex(this.models, lodash_es_isFunction(pred) ? pred : m => lodash_es_isString(pred) ? m.get(pred) : m.matches(pred));
},
last: function () {
const length = this.models == null ? 0 : this.models.length;
return length ? this.models[length - 1] : undefined;
},
head: function () {
return this.models[0];
},
first: function () {
return this.head();
},
map: function (cb, thisArg) {
return this.models.map(lodash_es_isFunction(cb) ? cb : m => lodash_es_isString(cb) ? m.get(cb) : m.matches(cb), thisArg);
},
reduce: function (callback, initialValue) {
return this.models.reduce(callback, initialValue || this.models[0]);
},
reduceRight: function (callback, initialValue) {
return this.models.reduceRight(callback, initialValue || this.models[0]);
},
toArray: function () {
return Array.from(this.models);
},
// Get a model from the set by id, cid, model object with id or cid
// properties, or an attributes object that is transformed through modelId.
get: function (obj) {
if (obj == null) return undefined;
return this._byId[obj] || this._byId[this.modelId(this._isModel(obj) ? obj.attributes : obj)] || obj.cid && this._byId[obj.cid];
},
// Returns `true` if the model is in the collection.
has: function (obj) {
return this.get(obj) != null;
},
// Get the model at the given index.
at: function (index) {
if (index < 0) index += this.length;
return this.models[index];
},
// Return models with matching attributes. Useful for simple cases of
// `filter`.
where: function (attrs, first) {
return this[first ? 'find' : 'filter'](attrs);
},
// Return the first model with matching attributes. Useful for simple cases
// of `find`.
findWhere: function (attrs) {
return this.where(attrs, true);
},
find: function (predicate, fromIndex) {
const pred = lodash_es_isFunction(predicate) ? predicate : m => m.matches(predicate);
return this.models.find(pred, fromIndex);
},
// Force the collection to re-sort itself. You don't need to call this under
// normal circumstances, as the set will maintain sort order as each item
// is added.
sort: function (options) {
let comparator = this.comparator;
if (!comparator) throw new Error('Cannot sort a set without a comparator');
options || (options = {});
const length = comparator.length;
if (lodash_es_isFunction(comparator)) comparator = comparator.bind(this);
// Run sort based on type of `comparator`.
if (length === 1 || lodash_es_isString(comparator)) {
this.models = this.sortBy(comparator);
} else {
this.models.sort(comparator);
}
if (!options.silent) this.trigger('sort', this, options);
return this;
},
// Pluck an attribute from each model in the collection.
pluck: function (attr) {
return this.map(attr + '');
},
// Fetch the default set of models for this collection, resetting the
// collection when they arrive. If `reset: true` is passed, the response
// data will be passed through the `reset` method instead of `set`.
fetch: function (options) {
options = lodash_es_assignIn({
parse: true
}, options);
const success = options.success;
const collection = this;
const promise = options.promise && getResolveablePromise();
options.success = function (resp) {
const method = options.reset ? 'reset' : 'set';
collection[method](resp, options);
if (success) success.call(options.context, collection, resp, options);
promise && promise.resolve();
collection.trigger('sync', collection, resp, options);
};
wrapError(this, options);
return promise ? promise : this.sync('read', this, options);
},
// Create a new instance of a model in this collection. Add the model to the
// collection immediately, unless `wait: true` is passed, in which case we
// wait for the server to agree.
create: function (model, options) {
options = options ? lodash_es_clone(options) : {};
const wait = options.wait;
const return_promise = options.promise;
const promise = return_promise && getResolveablePromise();
model = this._prepareModel(model, options);
if (!model) return false;
if (!wait) this.add(model, options);
const collection = this;
const success = options.success;
const error = options.error;
options.success = function (m, resp, callbackOpts) {
if (wait) {
collection.add(m, callbackOpts);
}
if (success) {
success.call(callbackOpts.context, m, resp, callbackOpts);
}
if (return_promise) {
promise.resolve(m);
}
};
options.error = function (model, e, options) {
error && error.call(options.context, model, e, options);
return_promise && promise.reject(e);
};
model.save(null, Object.assign(options, {
'promise': false
}));
if (return_promise) {
return promise;
} else {
return model;
}
},
// **parse** converts a response into a list of models to be added to the
// collection. The default implementation is just to pass it through.
parse: function (resp, options) {
return resp;
},
// Create a new collection with an identical list of models as this one.
clone: function () {
return new this.constructor(this.models, {
model: this.model,
comparator: this.comparator
});
},
// Define how to uniquely identify models in the collection.
modelId: function (attrs) {
return attrs[this.model.prototype?.idAttribute || 'id'];
},
// Get an iterator of all models in this collection.
values: function () {
return new CollectionIterator(this, ITERATOR_VALUES);
},
// Get an iterator of all model IDs in this collection.
keys: function () {
return new CollectionIterator(this, ITERATOR_KEYS);
},
// Get an iterator of all [ID, model] tuples in this collection.
entries: function () {
return new CollectionIterator(this, ITERATOR_KEYSVALUES);
},
// Private method to reset all internal state. Called when the collection
// is first initialized or reset.
_reset: function () {
this.length = 0;
this.models = [];
this._byId = {};
},
// Prepare a hash of attributes (or other model) to be added to this
// collection.
_prepareModel: function (attrs, options) {
if (this._isModel(attrs)) {
if (!attrs.collection) attrs.collection = this;
return attrs;
}
options = options ? lodash_es_clone(options) : {};
options.collection = this;
const model = new this.model(attrs, options);
if (!model.validationError) return model;
this.trigger('invalid', this, model.validationError, options);
return false;
},
// Internal method called by both remove and set.
_removeModels: function (models, options) {
const removed = [];
for (let i = 0; i < models.length; i++) {
const model = this.get(models[i]);
if (!model) continue;
const index = this.indexOf(model);
this.models.splice(index, 1);
this.length--;
// Remove references before triggering 'remove' event to prevent an
// infinite loop. #3693
delete this._byId[model.cid];
const id = this.modelId(model.attributes);
if (id != null) delete this._byId[id];
if (!options.silent) {
options.index = index;
model.trigger('remove', model, this, options);
}
removed.push(model);
this._removeReference(model, options);
}
return removed;
},
// Method for checking whether an object should be considered a model for
// the purposes of adding to the collection.
_isModel: function (model) {
return model instanceof Model;
},
// Internal method to create a model's ties to a collection.
_addReference: function (model, options) {
this._byId[model.cid] = model;
const id = this.modelId(model.attributes);
if (id != null) this._byId[id] = model;
model.on('all', this._onModelEvent, this);
},
// Internal method to sever a model's ties to a collection.
_removeReference: function (model, options) {
delete this._byId[model.cid];
const id = this.modelId(model.attributes);
if (id != null) delete this._byId[id];
if (this === model.collection) delete model.collection;
model.off('all', this._onModelEvent, this);
},
// Internal method called every time a model in the set fires an event.
// Sets need to update their indexes when models change ids. All other
// events simply proxy through. "add" and "remove" events that originate
// in other collections are ignored.
_onModelEvent: function (event, model, collection, options) {
if (model) {
if ((event === 'add' || event === 'remove') && collection !== this) return;
if (event === 'destroy') this.remove(model, options);
if (event === 'change') {
const prevId = this.modelId(model.previousAttributes());
const id = this.modelId(model.attributes);
if (prevId !== id) {
if (prevId != null) delete this._byId[prevId];
if (id != null) this._byId[id] = model;
}
}
}
this.trigger.apply(this, arguments);
}
});
// Defining an @@iterator method implements JavaScript's Iterable protocol.
// In modern ES2015 browsers, this value is found at Symbol.iterator.
/* global Symbol */
const $$iterator = typeof Symbol === 'function' && Symbol.iterator;
if ($$iterator) {
Collection.prototype[$$iterator] = Collection.prototype.values;
}
// CollectionIterator
// ------------------
// A CollectionIterator implements JavaScript's Iterator protocol, allowing the
// use of `for of` loops in modern browsers and interoperation between
// Collection and other JavaScript functions and third-party libraries
// which can operate on Iterables.
const CollectionIterator = function (collection, kind) {
this._collection = collection;
this._kind = kind;
this._index = 0;
};
// This "enum" defines the three possible kinds of values which can be emitted
// by a CollectionIterator that correspond to the values(), keys() and entries()
// methods on Collection, respectively.
const ITERATOR_VALUES = 1;
const ITERATOR_KEYS = 2;
const ITERATOR_KEYSVALUES = 3;
// All Iterators should themselves be Iterable.
if ($$iterator) {
CollectionIterator.prototype[$$iterator] = function () {
return this;
};
}
CollectionIterator.prototype.next = function () {
if (this._collection) {
// Only continue iterating if the iterated collection is long enough.
if (this._index < this._collection.length) {
const model = this._collection.at(this._index);
this._index++;
// Construct a value depending on what kind of values should be iterated.
let value;
if (this._kind === ITERATOR_VALUES) {
value = model;
} else {
const id = this._collection.modelId(model.attributes);
if (this._kind === ITERATOR_KEYS) {
value = id;
} else {
// ITERATOR_KEYSVALUES
value = [id, model];
}
}
return {
value: value,
done: false
};
}
// Once exhausted, remove the reference to the collection so future
// calls to the next method always return done.
this._collection = undefined;
}
return {
value: undefined,
done: true
};
};
;// CONCATENATED MODULE: ./node_modules/filesize/dist/filesize.esm.js
/**
* filesize
*
* @copyright 2023 Jason Mulligan <jason.mulligan@avoidwork.com>
* @license BSD-3-Clause
* @version 10.0.7
*/
const ARRAY = "array";
const BIT = "bit";
const BITS = "bits";
const BYTE = "byte";
const BYTES = "bytes";
const EMPTY = "";
const EXPONENT = "exponent";
const FUNCTION = "function";
const IEC = "iec";
const INVALID_NUMBER = "Invalid number";
const INVALID_ROUND = "Invalid rounding method";
const JEDEC = "jedec";
const OBJECT = "object";
const PERIOD = ".";
const ROUND = "round";
const S = "s";
const SI_KBIT = "kbit";
const SI_KBYTE = "kB";
const SPACE = " ";
const STRING = "string";
const ZERO = "0";
const STRINGS = {
symbol: {
iec: {
bits: ["bit", "Kibit", "Mibit", "Gibit", "Tibit", "Pibit", "Eibit", "Zibit", "Yibit"],
bytes: ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
},
jedec: {
bits: ["bit", "Kbit", "Mbit", "Gbit", "Tbit", "Pbit", "Ebit", "Zbit", "Ybit"],
bytes: ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
}
},
fullform: {
iec: ["", "kibi", "mebi", "gibi", "tebi", "pebi", "exbi", "zebi", "yobi"],
jedec: ["", "kilo", "mega", "giga", "tera", "peta", "exa", "zetta", "yotta"]
}
};function filesize (arg, {
bits = false,
pad = false,
base = -1,
round = 2,
locale = EMPTY,
localeOptions = {},
separator = EMPTY,
spacer = SPACE,
symbols = {},
standard = EMPTY,
output = STRING,
fullform = false,
fullforms = [],
exponent = -1,
roundingMethod = ROUND,
precision = 0
} = {}) {
let e = exponent,
num = Number(arg),
result = [],
val = 0,
u = EMPTY;
// Sync base & standard
if (base === -1 && standard.length === 0) {
base = 10;
standard = JEDEC;
} else if (base === -1 && standard.length > 0) {
standard = standard === IEC ? IEC : JEDEC;
base = standard === IEC ? 2 : 10;
} else {
base = base === 2 ? 2 : 10;
standard = base === 10 ? JEDEC : standard === JEDEC ? JEDEC : IEC;
}
const ceil = base === 10 ? 1000 : 1024,
full = fullform === true,
neg = num < 0,
roundingFunc = Math[roundingMethod];
if (typeof arg !== "bigint" && isNaN(arg)) {
throw new TypeError(INVALID_NUMBER);
}
if (typeof roundingFunc !== FUNCTION) {
throw new TypeError(INVALID_ROUND);
}
// Flipping a negative number to determine the size
if (neg) {
num = -num;
}
// Determining the exponent
if (e === -1 || isNaN(e)) {
e = Math.floor(Math.log(num) / Math.log(ceil));
if (e < 0) {
e = 0;
}
}
// Exceeding supported length, time to reduce & multiply
if (e > 8) {
if (precision > 0) {
precision += 8 - e;
}
e = 8;
}
if (output === EXPONENT) {
return e;
}
// Zero is now a special case because bytes divide by 1
if (num === 0) {
result[0] = 0;
u = result[1] = STRINGS.symbol[standard][bits ? BITS : BYTES][e];
} else {
val = num / (base === 2 ? Math.pow(2, e * 10) : Math.pow(1000, e));
if (bits) {
val = val * 8;
if (val >= ceil && e < 8) {
val = val / ceil;
e++;
}
}
const p = Math.pow(10, e > 0 ? round : 0);
result[0] = roundingFunc(val * p) / p;
if (result[0] === ceil && e < 8 && exponent === -1) {
result[0] = 1;
e++;
}
u = result[1] = base === 10 && e === 1 ? bits ? SI_KBIT : SI_KBYTE : STRINGS.symbol[standard][bits ? BITS : BYTES][e];
}
// Decorating a 'diff'
if (neg) {
result[0] = -result[0];
}
// Setting optional precision
if (precision > 0) {
result[0] = result[0].toPrecision(precision);
}
// Applying custom symbol
result[1] = symbols[result[1]] || result[1];
if (locale === true) {
result[0] = result[0].toLocaleString();
} else if (locale.length > 0) {
result[0] = result[0].toLocaleString(locale, localeOptions);
} else if (separator.length > 0) {
result[0] = result[0].toString().replace(PERIOD, separator);
}
if (pad && Number.isInteger(result[0]) === false && round > 0) {
const x = separator || PERIOD,
tmp = result[0].toString().split(x),
s = tmp[1] || EMPTY,
l = s.length,
n = round - l;
result[0] = `${tmp[0]}${x}${s.padEnd(l + n, ZERO)}`;
}
if (full) {
result[1] = fullforms[e] ? fullforms[e] : STRINGS.fullform[standard][e] + (bits ? BIT : BYTE) + (result[0] === 1 ? EMPTY : S);
}
// Returning Array, Object, or String (default)
return output === ARRAY ? result : output === OBJECT ? {
value: result[0],
symbol: result[1],
exponent: e,
unit: u
} : result.join(spacer);
}
// Partial application for functional programming
function partial ({
bits = false,
pad = false,
base = -1,
round = 2,
locale = EMPTY,
localeOptions = {},
separator = EMPTY,
spacer = SPACE,
symbols = {},
standard = EMPTY,
output = STRING,
fullform = false,
fullforms = [],
exponent = -1,
roundingMethod = ROUND,
precision = 0
} = {}) {
return arg => filesize(arg, {
bits,
pad,
base,
round,
locale,
localeOptions,
separator,
spacer,
symbols,
standard,
output,
fullform,
fullforms,
exponent,
roundingMethod,
precision
});
}
;// CONCATENATED MODULE: ./node_modules/@lit/reactive-element/css-tag.js
/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
const css_tag_t=window,e=css_tag_t.ShadowRoot&&(void 0===css_tag_t.ShadyCSS||css_tag_t.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,s=Symbol(),n=new WeakMap;class o{constructor(t,e,n){if(this._$cssResult$=!0,n!==s)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const s=this.t;if(e&&void 0===t){const e=void 0!==s&&1===s.length;e&&(t=n.get(s)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),e&&n.set(s,t))}return t}toString(){return this.cssText}}const r=t=>new o("string"==typeof t?t:t+"",void 0,s),css_tag_i=(t,...e)=>{const n=1===t.length?t[0]:e.reduce(((e,s,n)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+t[n+1]),t[0]);return new o(n,t,s)},css_tag_S=(s,n)=>{e?s.adoptedStyleSheets=n.map((t=>t instanceof CSSStyleSheet?t:t.styleSheet)):n.forEach((e=>{const n=document.createElement("style"),o=css_tag_t.litNonce;void 0!==o&&n.setAttribute("nonce",o),n.textContent=e.cssText,s.appendChild(n)}))},c=e?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const s of t.cssRules)e+=s.cssText;return r(e)})(t):t;
//# sourceMappingURL=css-tag.js.map
;// CONCATENATED MODULE: ./node_modules/@lit/reactive-element/reactive-element.js
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/var reactive_element_s;const reactive_element_e=window,reactive_element_r=reactive_element_e.trustedTypes,h=reactive_element_r?reactive_element_r.emptyScript:"",reactive_element_o=reactive_element_e.reactiveElementPolyfillSupport,reactive_element_n={toAttribute(t,i){switch(i){case Boolean:t=t?h:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,i){let s=t;switch(i){case Boolean:s=null!==t;break;case Number:s=null===t?null:Number(t);break;case Object:case Array:try{s=JSON.parse(t)}catch(t){s=null}}return s}},a=(t,i)=>i!==t&&(i==i||t==t),l={attribute:!0,type:String,converter:reactive_element_n,reflect:!1,hasChanged:a},d="finalized";class reactive_element_u extends HTMLElement{constructor(){super(),this._$Ei=new Map,this.isUpdatePending=!1,this.hasUpdated=!1,this._$El=null,this.u()}static addInitializer(t){var i;this.finalize(),(null!==(i=this.h)&&void 0!==i?i:this.h=[]).push(t)}static get observedAttributes(){this.finalize();const t=[];return this.elementProperties.forEach(((i,s)=>{const e=this._$Ep(s,i);void 0!==e&&(this._$Ev.set(e,s),t.push(e))})),t}static createProperty(t,i=l){if(i.state&&(i.attribute=!1),this.finalize(),this.elementProperties.set(t,i),!i.noAccessor&&!this.prototype.hasOwnProperty(t)){const s="symbol"==typeof t?Symbol():"__"+t,e=this.getPropertyDescriptor(t,s,i);void 0!==e&&Object.defineProperty(this.prototype,t,e)}}static getPropertyDescriptor(t,i,s){return{get(){return this[i]},set(e){const r=this[t];this[i]=e,this.requestUpdate(t,r,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)||l}static finalize(){if(this.hasOwnProperty(d))return!1;this[d]=!0;const t=Object.getPrototypeOf(this);if(t.finalize(),void 0!==t.h&&(this.h=[...t.h]),this.elementProperties=new Map(t.elementProperties),this._$Ev=new Map,this.hasOwnProperty("properties")){const t=this.properties,i=[...Object.getOwnPropertyNames(t),...Object.getOwnPropertySymbols(t)];for(const s of i)this.createProperty(s,t[s])}return this.elementStyles=this.finalizeStyles(this.styles),!0}static finalizeStyles(i){const s=[];if(Array.isArray(i)){const e=new Set(i.flat(1/0).reverse());for(const i of e)s.unshift(c(i))}else void 0!==i&&s.push(c(i));return s}static _$Ep(t,i){const s=i.attribute;return!1===s?void 0:"string"==typeof s?s:"string"==typeof t?t.toLowerCase():void 0}u(){var t;this._$E_=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$Eg(),this.requestUpdate(),null===(t=this.constructor.h)||void 0===t||t.forEach((t=>t(this)))}addController(t){var i,s;(null!==(i=this._$ES)&&void 0!==i?i:this._$ES=[]).push(t),void 0!==this.renderRoot&&this.isConnected&&(null===(s=t.hostConnected)||void 0===s||s.call(t))}removeController(t){var i;null===(i=this._$ES)||void 0===i||i.splice(this._$ES.indexOf(t)>>>0,1)}_$Eg(){this.constructor.elementProperties.forEach(((t,i)=>{this.hasOwnProperty(i)&&(this._$Ei.set(i,this[i]),delete this[i])}))}createRenderRoot(){var t;const s=null!==(t=this.shadowRoot)&&void 0!==t?t:this.attachShadow(this.constructor.shadowRootOptions);return css_tag_S(s,this.constructor.elementStyles),s}connectedCallback(){var t;void 0===this.renderRoot&&(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),null===(t=this._$ES)||void 0===t||t.forEach((t=>{var i;return null===(i=t.hostConnected)||void 0===i?void 0:i.call(t)}))}enableUpdating(t){}disconnectedCallback(){var t;null===(t=this._$ES)||void 0===t||t.forEach((t=>{var i;return null===(i=t.hostDisconnected)||void 0===i?void 0:i.call(t)}))}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$EO(t,i,s=l){var e;const r=this.constructor._$Ep(t,s);if(void 0!==r&&!0===s.reflect){const h=(void 0!==(null===(e=s.converter)||void 0===e?void 0:e.toAttribute)?s.converter:reactive_element_n).toAttribute(i,s.type);this._$El=t,null==h?this.removeAttribute(r):this.setAttribute(r,h),this._$El=null}}_$AK(t,i){var s;const e=this.constructor,r=e._$Ev.get(t);if(void 0!==r&&this._$El!==r){const t=e.getPropertyOptions(r),h="function"==typeof t.converter?{fromAttribute:t.converter}:void 0!==(null===(s=t.converter)||void 0===s?void 0:s.fromAttribute)?t.converter:reactive_element_n;this._$El=r,this[r]=h.fromAttribute(i,t.type),this._$El=null}}requestUpdate(t,i,s){let e=!0;void 0!==t&&(((s=s||this.constructor.getPropertyOptions(t)).hasChanged||a)(this[t],i)?(this._$AL.has(t)||this._$AL.set(t,i),!0===s.reflect&&this._$El!==t&&(void 0===this._$EC&&(this._$EC=new Map),this._$EC.set(t,s))):e=!1),!this.isUpdatePending&&e&&(this._$E_=this._$Ej())}async _$Ej(){this.isUpdatePending=!0;try{await this._$E_}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var t;if(!this.isUpdatePending)return;this.hasUpdated,this._$Ei&&(this._$Ei.forEach(((t,i)=>this[i]=t)),this._$Ei=void 0);let i=!1;const s=this._$AL;try{i=this.shouldUpdate(s),i?(this.willUpdate(s),null===(t=this._$ES)||void 0===t||t.forEach((t=>{var i;return null===(i=t.hostUpdate)||void 0===i?void 0:i.call(t)})),this.update(s)):this._$Ek()}catch(t){throw i=!1,this._$Ek(),t}i&&this._$AE(s)}willUpdate(t){}_$AE(t){var i;null===(i=this._$ES)||void 0===i||i.forEach((t=>{var i;return null===(i=t.hostUpdated)||void 0===i?void 0:i.call(t)})),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$Ek(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$E_}shouldUpdate(t){return!0}update(t){void 0!==this._$EC&&(this._$EC.forEach(((t,i)=>this._$EO(i,this[i],t))),this._$EC=void 0),this._$Ek()}updated(t){}firstUpdated(t){}}reactive_element_u[d]=!0,reactive_element_u.elementProperties=new Map,reactive_element_u.elementStyles=[],reactive_element_u.shadowRootOptions={mode:"open"},null==reactive_element_o||reactive_element_o({ReactiveElement:reactive_element_u}),(null!==(reactive_element_s=reactive_element_e.reactiveElementVersions)&&void 0!==reactive_element_s?reactive_element_s:reactive_element_e.reactiveElementVersions=[]).push("1.6.2");
//# sourceMappingURL=reactive-element.js.map
;// CONCATENATED MODULE: ./node_modules/lit-html/lit-html.js
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
var lit_html_t;
const lit_html_i = window,
lit_html_s = lit_html_i.trustedTypes,
lit_html_e = lit_html_s ? lit_html_s.createPolicy("lit-html", {
createHTML: t => t
}) : void 0,
lit_html_o = "$lit$",
lit_html_n = `lit$${(Math.random() + "").slice(9)}$`,
lit_html_l = "?" + lit_html_n,
lit_html_h = `<${lit_html_l}>`,
lit_html_r = document,
lit_html_d = () => lit_html_r.createComment(""),
lit_html_u = t => null === t || "object" != typeof t && "function" != typeof t,
lit_html_c = Array.isArray,
v = t => lit_html_c(t) || "function" == typeof (null == t ? void 0 : t[Symbol.iterator]),
lit_html_a = "[ \t\n\f\r]",
f = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,
_ = /-->/g,
m = />/g,
p = RegExp(`>|${lit_html_a}(?:([^\\s"'>=/]+)(${lit_html_a}*=${lit_html_a}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`, "g"),
g = /'/g,
$ = /"/g,
y = /^(?:script|style|textarea|title)$/i,
w = t => function (i) {
for (var _len = arguments.length, s = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
s[_key - 1] = arguments[_key];
}
return {
_$litType$: t,
strings: i,
values: s
};
},
x = w(1),
b = w(2),
T = Symbol.for("lit-noChange"),
A = Symbol.for("lit-nothing"),
E = new WeakMap(),
C = lit_html_r.createTreeWalker(lit_html_r, 129, null, !1),
P = (t, i) => {
const s = t.length - 1,
l = [];
let r,
d = 2 === i ? "<svg>" : "",
u = f;
for (let i = 0; i < s; i++) {
const s = t[i];
let e,
c,
v = -1,
a = 0;
for (; a < s.length && (u.lastIndex = a, c = u.exec(s), null !== c);) a = u.lastIndex, u === f ? "!--" === c[1] ? u = _ : void 0 !== c[1] ? u = m : void 0 !== c[2] ? (y.test(c[2]) && (r = RegExp("</" + c[2], "g")), u = p) : void 0 !== c[3] && (u = p) : u === p ? ">" === c[0] ? (u = null != r ? r : f, v = -1) : void 0 === c[1] ? v = -2 : (v = u.lastIndex - c[2].length, e = c[1], u = void 0 === c[3] ? p : '"' === c[3] ? $ : g) : u === $ || u === g ? u = p : u === _ || u === m ? u = f : (u = p, r = void 0);
const w = u === p && t[i + 1].startsWith("/>") ? " " : "";
d += u === f ? s + lit_html_h : v >= 0 ? (l.push(e), s.slice(0, v) + lit_html_o + s.slice(v) + lit_html_n + w) : s + lit_html_n + (-2 === v ? (l.push(void 0), i) : w);
}
const c = d + (t[s] || "<?>") + (2 === i ? "</svg>" : "");
if (!Array.isArray(t) || !t.hasOwnProperty("raw")) throw Error("invalid template strings array");
return [void 0 !== lit_html_e ? lit_html_e.createHTML(c) : c, l];
};
class V {
constructor(_ref, e) {
let {
strings: t,
_$litType$: i
} = _ref;
let h;
this.parts = [];
let r = 0,
u = 0;
const c = t.length - 1,
v = this.parts,
[a, f] = P(t, i);
if (this.el = V.createElement(a, e), C.currentNode = this.el.content, 2 === i) {
const t = this.el.content,
i = t.firstChild;
i.remove(), t.append(...i.childNodes);
}
for (; null !== (h = C.nextNode()) && v.length < c;) {
if (1 === h.nodeType) {
if (h.hasAttributes()) {
const t = [];
for (const i of h.getAttributeNames()) if (i.endsWith(lit_html_o) || i.startsWith(lit_html_n)) {
const s = f[u++];
if (t.push(i), void 0 !== s) {
const t = h.getAttribute(s.toLowerCase() + lit_html_o).split(lit_html_n),
i = /([.?@])?(.*)/.exec(s);
v.push({
type: 1,
index: r,
name: i[2],
strings: t,
ctor: "." === i[1] ? k : "?" === i[1] ? I : "@" === i[1] ? L : R
});
} else v.push({
type: 6,
index: r
});
}
for (const i of t) h.removeAttribute(i);
}
if (y.test(h.tagName)) {
const t = h.textContent.split(lit_html_n),
i = t.length - 1;
if (i > 0) {
h.textContent = lit_html_s ? lit_html_s.emptyScript : "";
for (let s = 0; s < i; s++) h.append(t[s], lit_html_d()), C.nextNode(), v.push({
type: 2,
index: ++r
});
h.append(t[i], lit_html_d());
}
}
} else if (8 === h.nodeType) if (h.data === lit_html_l) v.push({
type: 2,
index: r
});else {
let t = -1;
for (; -1 !== (t = h.data.indexOf(lit_html_n, t + 1));) v.push({
type: 7,
index: r
}), t += lit_html_n.length - 1;
}
r++;
}
}
static createElement(t, i) {
const s = lit_html_r.createElement("template");
return s.innerHTML = t, s;
}
}
function N(t, i) {
let s = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : t;
let e = arguments.length > 3 ? arguments[3] : undefined;
var o, n, l, h;
if (i === T) return i;
let r = void 0 !== e ? null === (o = s._$Co) || void 0 === o ? void 0 : o[e] : s._$Cl;
const d = lit_html_u(i) ? void 0 : i._$litDirective$;
return (null == r ? void 0 : r.constructor) !== d && (null === (n = null == r ? void 0 : r._$AO) || void 0 === n || n.call(r, !1), void 0 === d ? r = void 0 : (r = new d(t), r._$AT(t, s, e)), void 0 !== e ? (null !== (l = (h = s)._$Co) && void 0 !== l ? l : h._$Co = [])[e] = r : s._$Cl = r), void 0 !== r && (i = N(t, r._$AS(t, i.values), r, e)), i;
}
class lit_html_S {
constructor(t, i) {
this._$AV = [], this._$AN = void 0, this._$AD = t, this._$AM = i;
}
get parentNode() {
return this._$AM.parentNode;
}
get _$AU() {
return this._$AM._$AU;
}
u(t) {
var i;
const {
el: {
content: s
},
parts: e
} = this._$AD,
o = (null !== (i = null == t ? void 0 : t.creationScope) && void 0 !== i ? i : lit_html_r).importNode(s, !0);
C.currentNode = o;
let n = C.nextNode(),
l = 0,
h = 0,
d = e[0];
for (; void 0 !== d;) {
if (l === d.index) {
let i;
2 === d.type ? i = new M(n, n.nextSibling, this, t) : 1 === d.type ? i = new d.ctor(n, d.name, d.strings, this, t) : 6 === d.type && (i = new z(n, this, t)), this._$AV.push(i), d = e[++h];
}
l !== (null == d ? void 0 : d.index) && (n = C.nextNode(), l++);
}
return C.currentNode = lit_html_r, o;
}
v(t) {
let i = 0;
for (const s of this._$AV) void 0 !== s && (void 0 !== s.strings ? (s._$AI(t, s, i), i += s.strings.length - 2) : s._$AI(t[i])), i++;
}
}
class M {
constructor(t, i, s, e) {
var o;
this.type = 2, this._$AH = A, this._$AN = void 0, this._$AA = t, this._$AB = i, this._$AM = s, this.options = e, this._$Cp = null === (o = null == e ? void 0 : e.isConnected) || void 0 === o || o;
}
get _$AU() {
var t, i;
return null !== (i = null === (t = this._$AM) || void 0 === t ? void 0 : t._$AU) && void 0 !== i ? i : this._$Cp;
}
get parentNode() {
let t = this._$AA.parentNode;
const i = this._$AM;
return void 0 !== i && 11 === (null == t ? void 0 : t.nodeType) && (t = i.parentNode), t;
}
get startNode() {
return this._$AA;
}
get endNode() {
return this._$AB;
}
_$AI(t) {
let i = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this;
t = N(this, t, i), lit_html_u(t) ? t === A || null == t || "" === t ? (this._$AH !== A && this._$AR(), this._$AH = A) : t !== this._$AH && t !== T && this._(t) : void 0 !== t._$litType$ ? this.g(t) : void 0 !== t.nodeType ? this.$(t) : v(t) ? this.T(t) : this._(t);
}
k(t) {
return this._$AA.parentNode.insertBefore(t, this._$AB);
}
$(t) {
this._$AH !== t && (this._$AR(), this._$AH = this.k(t));
}
_(t) {
this._$AH !== A && lit_html_u(this._$AH) ? this._$AA.nextSibling.data = t : this.$(lit_html_r.createTextNode(t)), this._$AH = t;
}
g(t) {
var i;
const {
values: s,
_$litType$: e
} = t,
o = "number" == typeof e ? this._$AC(t) : (void 0 === e.el && (e.el = V.createElement(e.h, this.options)), e);
if ((null === (i = this._$AH) || void 0 === i ? void 0 : i._$AD) === o) this._$AH.v(s);else {
const t = new lit_html_S(o, this),
i = t.u(this.options);
t.v(s), this.$(i), this._$AH = t;
}
}
_$AC(t) {
let i = E.get(t.strings);
return void 0 === i && E.set(t.strings, i = new V(t)), i;
}
T(t) {
lit_html_c(this._$AH) || (this._$AH = [], this._$AR());
const i = this._$AH;
let s,
e = 0;
for (const o of t) e === i.length ? i.push(s = new M(this.k(lit_html_d()), this.k(lit_html_d()), this, this.options)) : s = i[e], s._$AI(o), e++;
e < i.length && (this._$AR(s && s._$AB.nextSibling, e), i.length = e);
}
_$AR() {
let t = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this._$AA.nextSibling;
let i = arguments.length > 1 ? arguments[1] : undefined;
var s;
for (null === (s = this._$AP) || void 0 === s || s.call(this, !1, !0, i); t && t !== this._$AB;) {
const i = t.nextSibling;
t.remove(), t = i;
}
}
setConnected(t) {
var i;
void 0 === this._$AM && (this._$Cp = t, null === (i = this._$AP) || void 0 === i || i.call(this, t));
}
}
class R {
constructor(t, i, s, e, o) {
this.type = 1, this._$AH = A, this._$AN = void 0, this.element = t, this.name = i, this._$AM = e, this.options = o, s.length > 2 || "" !== s[0] || "" !== s[1] ? (this._$AH = Array(s.length - 1).fill(new String()), this.strings = s) : this._$AH = A;
}
get tagName() {
return this.element.tagName;
}
get _$AU() {
return this._$AM._$AU;
}
_$AI(t) {
let i = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this;
let s = arguments.length > 2 ? arguments[2] : undefined;
let e = arguments.length > 3 ? arguments[3] : undefined;
const o = this.strings;
let n = !1;
if (void 0 === o) t = N(this, t, i, 0), n = !lit_html_u(t) || t !== this._$AH && t !== T, n && (this._$AH = t);else {
const e = t;
let l, h;
for (t = o[0], l = 0; l < o.length - 1; l++) h = N(this, e[s + l], i, l), h === T && (h = this._$AH[l]), n || (n = !lit_html_u(h) || h !== this._$AH[l]), h === A ? t = A : t !== A && (t += (null != h ? h : "") + o[l + 1]), this._$AH[l] = h;
}
n && !e && this.j(t);
}
j(t) {
t === A ? this.element.removeAttribute(this.name) : this.element.setAttribute(this.name, null != t ? t : "");
}
}
class k extends R {
constructor() {
super(...arguments), this.type = 3;
}
j(t) {
this.element[this.name] = t === A ? void 0 : t;
}
}
const H = lit_html_s ? lit_html_s.emptyScript : "";
class I extends R {
constructor() {
super(...arguments), this.type = 4;
}
j(t) {
t && t !== A ? this.element.setAttribute(this.name, H) : this.element.removeAttribute(this.name);
}
}
class L extends R {
constructor(t, i, s, e, o) {
super(t, i, s, e, o), this.type = 5;
}
_$AI(t) {
let i = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this;
var s;
if ((t = null !== (s = N(this, t, i, 0)) && void 0 !== s ? s : A) === T) return;
const e = this._$AH,
o = t === A && e !== A || t.capture !== e.capture || t.once !== e.once || t.passive !== e.passive,
n = t !== A && (e === A || o);
o && this.element.removeEventListener(this.name, this, e), n && this.element.addEventListener(this.name, this, t), this._$AH = t;
}
handleEvent(t) {
var i, s;
"function" == typeof this._$AH ? this._$AH.call(null !== (s = null === (i = this.options) || void 0 === i ? void 0 : i.host) && void 0 !== s ? s : this.element, t) : this._$AH.handleEvent(t);
}
}
class z {
constructor(t, i, s) {
this.element = t, this.type = 6, this._$AN = void 0, this._$AM = i, this.options = s;
}
get _$AU() {
return this._$AM._$AU;
}
_$AI(t) {
N(this, t);
}
}
const Z = {
O: lit_html_o,
P: lit_html_n,
A: lit_html_l,
C: 1,
M: P,
L: lit_html_S,
D: v,
R: N,
I: M,
V: R,
H: I,
N: L,
U: k,
F: z
},
j = lit_html_i.litHtmlPolyfillSupport;
null == j || j(V, M), (null !== (lit_html_t = lit_html_i.litHtmlVersions) && void 0 !== lit_html_t ? lit_html_t : lit_html_i.litHtmlVersions = []).push("2.7.4");
const B = (t, i, s) => {
var e, o;
const n = null !== (e = null == s ? void 0 : s.renderBefore) && void 0 !== e ? e : i;
let l = n._$litPart$;
if (void 0 === l) {
const t = null !== (o = null == s ? void 0 : s.renderBefore) && void 0 !== o ? o : null;
n._$litPart$ = l = new M(i.insertBefore(lit_html_d(), t), t, void 0, null != s ? s : {});
}
return l._$AI(t), l;
};
;// CONCATENATED MODULE: ./node_modules/lit-element/lit-element.js
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/var lit_element_l,lit_element_o;const lit_element_r=(/* unused pure expression or super */ null && (t));class lit_element_s extends reactive_element_u{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var t,e;const i=super.createRenderRoot();return null!==(t=(e=this.renderOptions).renderBefore)&&void 0!==t||(e.renderBefore=i.firstChild),i}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=B(i,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),null===(t=this._$Do)||void 0===t||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),null===(t=this._$Do)||void 0===t||t.setConnected(!1)}render(){return T}}lit_element_s.finalized=!0,lit_element_s._$litElement$=!0,null===(lit_element_l=globalThis.litElementHydrateSupport)||void 0===lit_element_l||lit_element_l.call(globalThis,{LitElement:lit_element_s});const lit_element_n=globalThis.litElementPolyfillSupport;null==lit_element_n||lit_element_n({LitElement:lit_element_s});const lit_element_h={_$AK:(t,e,i)=>{t._$AK(e,i)},_$AL:t=>t._$AL};(null!==(lit_element_o=globalThis.litElementVersions)&&void 0!==lit_element_o?lit_element_o:globalThis.litElementVersions=[]).push("3.3.2");
//# sourceMappingURL=lit-element.js.map
;// CONCATENATED MODULE: ./node_modules/lit/index.js
//# sourceMappingURL=index.js.map
;// CONCATENATED MODULE: ./src/headless/shared/api/public.js
/**
* ### The Public API
*
* This namespace contains public API methods which are are
* accessible on the global `converse` object.
* They are public, because any JavaScript in the
* page can call them. Public methods therefore don’t expose any sensitive
* or closured data. To do that, you’ll need to create a plugin, which has
* access to the private API method.
*
* @global
* @namespace converse
*/
const converse = Object.assign(window.converse || {}, {
CHAT_STATES: CHAT_STATES,
keycodes: KEYCODES,
/**
* Public API method which initializes Converse.
* This method must always be called when using Converse.
* @async
* @memberOf converse
* @method initialize
* @param { object } config A map of [configuration-settings](https://conversejs.org/docs/html/configuration.html#configuration-settings).
* @example
* converse.initialize({
* auto_list_rooms: false,
* auto_subscribe: false,
* bosh_service_url: 'https://bind.example.com',
* hide_muc_server: false,
* i18n: 'en',
* play_sounds: true,
* show_controlbox_by_default: true,
* debug: false,
* roster_groups: true
* });
*/
async initialize(settings) {
const {
api
} = shared_converse;
await cleanup(shared_converse);
setUnloadEvent();
initAppSettings(settings);
shared_converse.strict_plugin_dependencies = settings.strict_plugin_dependencies; // Needed by pluggable.js
log.setLogLevel(api.settings.get("loglevel"));
if (api.settings.get("authentication") === ANONYMOUS) {
if (api.settings.get("auto_login") && !api.settings.get('jid')) {
throw new Error("Config Error: you need to provide the server's " + "domain via the 'jid' option when using anonymous " + "authentication with auto_login.");
}
}
shared_converse.router.route(/^converse\?loglevel=(debug|info|warn|error|fatal)$/, 'loglevel', l => log.setLogLevel(l));
shared_converse.connfeedback = new feedback();
/* When reloading the page:
* For new sessions, we need to send out a presence stanza to notify
* the server/network that we're online.
* When re-attaching to an existing session we don't need to again send out a presence stanza,
* because it's as if "we never left" (see onConnectStatusChanged).
* https://github.com/conversejs/converse.js/issues/521
*/
shared_converse.send_initial_presence = true;
await initSessionStorage(shared_converse);
await initClientConfig(shared_converse);
await i18n.initialize();
initPlugins(shared_converse);
// Register all custom elements
// XXX: api.elements is defined in the UI part of Converse, outside of @converse/headless.
// This line should probably be moved to the UI code as part of a larger refactoring.
api.elements?.register();
registerGlobalEventHandlers(shared_converse);
try {
!History.started && shared_converse.router.history.start();
} catch (e) {
log.error(e);
}
const plugins = shared_converse.pluggable.plugins;
if (api.settings.get("auto_login") || api.settings.get("keepalive") && plugins['converse-bosh']?.enabled()) {
await api.user.login(null, null, true);
}
/**
* Triggered once converse.initialize has finished.
* @event _converse#initialized
*/
api.trigger('initialized');
if (shared_converse.isTestEnv()) {
return shared_converse;
}
},
/**
* Exposes methods for adding and removing plugins. You'll need to write a plugin
* if you want to have access to the private API methods defined further down below.
*
* For more information on plugins, read the documentation on [writing a plugin](/docs/html/plugin_development.html).
* @namespace plugins
* @memberOf converse
*/
plugins: {
/**
* Registers a new plugin.
* @method converse.plugins.add
* @param { string } name The name of the plugin
* @param { object } plugin The plugin object
* @example
* const plugin = {
* initialize: function () {
* // Gets called as soon as the plugin has been loaded.
*
* // Inside this method, you have access to the private
* // API via `_covnerse.api`.
*
* // The private _converse object contains the core logic
* // and data-structures of Converse.
* }
* }
* converse.plugins.add('myplugin', plugin);
*/
add(name, plugin) {
plugin.__name__ = name;
if (shared_converse.pluggable.plugins[name] !== undefined) {
throw new TypeError(`Error: plugin with name "${name}" has already been ` + 'registered!');
} else {
shared_converse.pluggable.plugins[name] = plugin;
}
}
},
/**
* Utility methods and globals from bundled 3rd party libraries.
* @typedef ConverseEnv
* @property { Error } converse.env.TimeoutError
* @property { function } converse.env.$build - Creates a Strophe.Builder, for creating stanza objects.
* @property { function } converse.env.$iq - Creates a Strophe.Builder with an <iq/> element as the root.
* @property { function } converse.env.$msg - Creates a Strophe.Builder with an <message/> element as the root.
* @property { function } converse.env.$pres - Creates a Strophe.Builder with an <presence/> element as the root.
* @property { function } converse.env.Promise - The Promise implementation used by Converse.
* @property { function } converse.env.Strophe - The [Strophe](http://strophe.im/strophejs) XMPP library used by Converse.
* @property { function } converse.env.f - And instance of Lodash with its methods wrapped to produce immutable auto-curried iteratee-first data-last methods.
* @property { function } converse.env.sizzle - [Sizzle](https://sizzlejs.com) CSS selector engine.
* @property { function } converse.env.sprintf
* @property { object } converse.env._ - The instance of [lodash-es](http://lodash.com) used by Converse.
* @property { object } converse.env.dayjs - [DayJS](https://github.com/iamkun/dayjs) date manipulation library.
* @property { object } converse.env.utils - Module containing common utility methods used by Converse.
* @memberOf converse
*/
'env': {
$build: $build,
$iq: $iq,
$msg: $msg,
$pres: $pres,
'utils': utils_core,
Collection: Collection,
Model: Model,
Promise,
Strophe: core,
TimeoutError: TimeoutError,
URI: (URI_default()),
VERSION_NAME: VERSION_NAME,
dayjs: (dayjs_min_default()),
filesize: filesize,
html: x,
log: log,
sizzle: (sizzle_default()),
sprintf: sprintf.sprintf,
stx: stanza_stx,
u: utils_core
}
});
;// CONCATENATED MODULE: ./src/headless/core.js
/**
* @copyright The Converse.js contributors
* @license Mozilla Public License (MPLv2)
*/
dayjs_min_default().extend((advancedFormat_default()));
;// CONCATENATED MODULE: ./src/headless/plugins/chat/model-with-contact.js
const ModelWithContact = Model.extend({
initialize() {
this.rosterContactAdded = getOpenPromise();
},
async setRosterContact(jid) {
const contact = await shared_api.contacts.get(jid);
if (contact) {
this.contact = contact;
this.set('nickname', contact.get('nickname'));
this.rosterContactAdded.resolve();
}
}
});
/* harmony default export */ const model_with_contact = (ModelWithContact);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isMatch.js
/**
* Performs a partial deep comparison between `object` and `source` to
* determine if `object` contains equivalent property values.
*
* **Note:** This method is equivalent to `_.matches` when `source` is
* partially applied.
*
* Partial comparisons will match empty array and empty object `source`
* values against any array or object value, respectively. See `_.isEqual`
* for a list of supported value comparisons.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2 };
*
* _.isMatch(object, { 'b': 2 });
* // => true
*
* _.isMatch(object, { 'b': 1 });
* // => false
*/
function isMatch(object, source) {
return object === source || _baseIsMatch(object, source, _getMatchData(source));
}
/* harmony default export */ const lodash_es_isMatch = (isMatch);
;// CONCATENATED MODULE: ./src/headless/shared/chat/utils.js
const {
u: utils_u
} = converse.env;
function pruneHistory(model) {
const max_history = shared_api.settings.get('prune_messages_above');
if (max_history && typeof max_history === 'number') {
if (model.messages.length > max_history) {
const non_empty_messages = model.messages.filter(m => !utils_u.isEmptyMessage(m));
if (non_empty_messages.length > max_history) {
while (non_empty_messages.length > max_history) {
non_empty_messages.shift().destroy();
}
/**
* Triggered once the message history has been pruned, i.e.
* once older messages have been removed to keep the
* number of messages below the value set in `prune_messages_above`.
* @event _converse#historyPruned
* @type { _converse.ChatBox | _converse.ChatRoom }
* @example _converse.api.listen.on('historyPruned', this => { ... });
*/
shared_api.trigger('historyPruned', model);
}
}
}
}
/**
* Given an array of {@link MediaURLMetadata} objects and text, return an
* array of {@link MediaURL} objects.
* @param { Array<MediaURLMetadata> } arr
* @param { String } text
* @returns{ Array<MediaURL> }
*/
function getMediaURLs(arr, text) {
let offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
/**
* @typedef { Object } MediaURLData
* An object representing a URL found in a chat message
* @property { Boolean } is_audio
* @property { Boolean } is_image
* @property { Boolean } is_video
* @property { String } end
* @property { String } start
* @property { String } url
*/
return arr.map(o => {
const start = o.start - offset;
const end = o.end - offset;
if (start < 0 || start >= text.length) {
return null;
}
return Object.assign({}, o, {
start,
end,
'url': text.substring(o.start - offset, o.end - offset)
});
}).filter(o => o);
}
/**
* Determines whether the given attributes of an incoming message
* represent a XEP-0308 correction and, if so, handles it appropriately.
* @private
* @method _converse.ChatBox#handleCorrection
* @param { _converse.ChatBox | _converse.ChatRoom }
* @param { object } attrs - Attributes representing a received
* message, as returned by {@link parseMessage}
* @returns { _converse.Message|undefined } Returns the corrected
* message or `undefined` if not applicable.
*/
async function handleCorrection(model, attrs) {
if (!attrs.replace_id || !attrs.from) {
return;
}
const query = attrs.type === 'groupchat' && attrs.occupant_id ? _ref => {
let {
attributes: m
} = _ref;
return m.msgid === attrs.replace_id && m.occupant_id == attrs.occupant_id;
}
// eslint-disable-next-line no-eq-null
: _ref2 => {
let {
attributes: m
} = _ref2;
return m.msgid === attrs.replace_id && m.from === attrs.from && m.occupant_id == null;
};
const message = model.messages.models.find(query);
if (!message) {
attrs['older_versions'] = {};
return await model.createMessage(attrs); // eslint-disable-line no-return-await
}
const older_versions = message.get('older_versions') || {};
if (attrs.time < message.get('time') && message.get('edited')) {
// This is an older message which has been corrected afterwards
older_versions[attrs.time] = attrs['message'];
message.save({
'older_versions': older_versions
});
} else {
// This is a correction of an earlier message we already received
if (Object.keys(older_versions).length) {
older_versions[message.get('edited')] = message.getMessageText();
} else {
older_versions[message.get('time')] = message.getMessageText();
}
attrs = Object.assign(attrs, {
older_versions
});
delete attrs['msgid']; // We want to keep the msgid of the original message
delete attrs['id']; // Delete id, otherwise a new cache entry gets created
attrs['time'] = message.get('time');
message.save(attrs);
}
return message;
}
const debouncedPruneHistory = lodash_es_debounce(pruneHistory, 500);
;// CONCATENATED MODULE: ./src/headless/shared/actions.js
const actions_u = converse.env.utils;
function rejectMessage(stanza, text) {
// Reject an incoming message by replying with an error message of type "cancel".
shared_api.send($msg({
'to': stanza.getAttribute('from'),
'type': 'error',
'id': stanza.getAttribute('id')
}).c('error', {
'type': 'cancel'
}).c('not-allowed', {
xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'
}).up().c('text', {
xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'
}).t(text));
log.warn(`Rejecting message stanza with the following reason: ${text}`);
log.warn(stanza);
}
/**
* Send out a XEP-0333 chat marker
* @param { String } to_jid
* @param { String } id - The id of the message being marked
* @param { String } type - The marker type
* @param { String } msg_type
*/
function sendMarker(to_jid, id, type, msg_type) {
const stanza = $msg({
'from': shared_converse.connection.jid,
'id': actions_u.getUniqueId(),
'to': to_jid,
'type': msg_type ? msg_type : 'chat'
}).c(type, {
'xmlns': core.NS.MARKERS,
'id': id
});
shared_api.send(stanza);
}
;// CONCATENATED MODULE: ./src/headless/utils/url.js
const {
u: url_u
} = converse.env;
/**
* Given a url, check whether the protocol being used is allowed for rendering
* the media in the chat (as opposed to just rendering a URL hyperlink).
* @param { String } url
* @returns { Boolean }
*/
function isAllowedProtocolForMedia(url) {
const uri = getURI(url);
const {
protocol
} = window.location;
if (['chrome-extension:', 'file:'].includes(protocol)) {
return true;
}
return protocol === 'http:' || protocol === 'https:' && ['https', 'aesgcm'].includes(uri.protocol().toLowerCase());
}
function getURI(url) {
try {
return url instanceof (URI_default()) ? url : new (URI_default())(url);
} catch (error) {
log.debug(error);
return null;
}
}
/**
* Given the an array of file extensions, check whether a URL points to a file
* ending in one of them.
* @param { String[] } types - An array of file extensions
* @param { String } url
* @returns { Boolean }
* @example
* checkFileTypes(['.gif'], 'https://conversejs.org/cat.gif?foo=bar');
*/
function checkFileTypes(types, url) {
const uri = getURI(url);
if (uri === null) {
throw new Error(`checkFileTypes: could not parse url ${url}`);
}
const filename = uri.filename().toLowerCase();
return !!types.filter(ext => filename.endsWith(ext)).length;
}
function isDomainWhitelisted(whitelist, url) {
const uri = getURI(url);
const subdomain = uri.subdomain();
const domain = uri.domain();
const fulldomain = `${subdomain ? `${subdomain}.` : ''}${domain}`;
return whitelist.includes(domain) || whitelist.includes(fulldomain);
}
function shouldRenderMediaFromURL(url_text, type) {
if (!isAllowedProtocolForMedia(url_text)) {
return false;
}
const may_render = shared_api.settings.get('render_media');
const is_domain_allowed = isDomainAllowed(url_text, `allowed_${type}_domains`);
if (Array.isArray(may_render)) {
return is_domain_allowed && isDomainWhitelisted(may_render, url_text);
} else {
return is_domain_allowed && may_render;
}
}
function filterQueryParamsFromURL(url) {
const paramsArray = api.settings.get('filter_url_query_params');
if (!paramsArray) return url;
const parsed_uri = getURI(url);
return parsed_uri.removeQuery(paramsArray).toString();
}
function isDomainAllowed(url, setting) {
const allowed_domains = shared_api.settings.get(setting);
if (!Array.isArray(allowed_domains)) {
return true;
}
try {
return isDomainWhitelisted(allowed_domains, url);
} catch (error) {
log.debug(error);
return false;
}
}
/**
* Accepts a {@link MediaURL} object and then checks whether its domain is
* allowed for rendering in the chat.
* @param { MediaURL } o
* @returns { Bool }
*/
function isMediaURLDomainAllowed(o) {
return o.is_audio && isDomainAllowed(o.url, 'allowed_audio_domains') || o.is_video && isDomainAllowed(o.url, 'allowed_video_domains') || o.is_image && isDomainAllowed(o.url, 'allowed_image_domains');
}
function isURLWithImageExtension(url) {
return checkFileTypes(['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.svg'], url);
}
function isGIFURL(url) {
return checkFileTypes(['.gif'], url);
}
function isAudioURL(url) {
return checkFileTypes(['.ogg', '.mp3', '.m4a'], url);
}
function isVideoURL(url) {
return checkFileTypes(['.mp4', '.webm'], url);
}
function isImageURL(url) {
const regex = shared_api.settings.get('image_urls_regex');
return regex?.test(url) || isURLWithImageExtension(url);
}
function isEncryptedFileURL(url) {
return url.startsWith('aesgcm://');
}
Object.assign(url_u, {
isAudioURL,
isGIFURL,
isVideoURL,
isImageURL,
isURLWithImageExtension,
checkFileTypes,
getURI,
shouldRenderMediaFromURL,
isAllowedProtocolForMedia
});
;// CONCATENATED MODULE: ./src/headless/shared/parsers.js
const {
NS: parsers_NS
} = core;
class StanzaParseError extends Error {
constructor(message, stanza) {
super(message, stanza);
this.name = 'StanzaParseError';
this.stanza = stanza;
}
}
/**
* Extract the XEP-0359 stanza IDs from the passed in stanza
* and return a map containing them.
* @private
* @param { Element } stanza - The message stanza
* @returns { Object }
*/
function getStanzaIDs(stanza, original_stanza) {
const attrs = {};
// Store generic stanza ids
const sids = sizzle_default()(`stanza-id[xmlns="${core.NS.SID}"]`, stanza);
const sid_attrs = sids.reduce((acc, s) => {
acc[`stanza_id ${s.getAttribute('by')}`] = s.getAttribute('id');
return acc;
}, {});
Object.assign(attrs, sid_attrs);
// Store the archive id
const result = sizzle_default()(`message > result[xmlns="${core.NS.MAM}"]`, original_stanza).pop();
if (result) {
const by_jid = original_stanza.getAttribute('from') || shared_converse.bare_jid;
attrs[`stanza_id ${by_jid}`] = result.getAttribute('id');
}
// Store the origin id
const origin_id = sizzle_default()(`origin-id[xmlns="${core.NS.SID}"]`, stanza).pop();
if (origin_id) {
attrs['origin_id'] = origin_id.getAttribute('id');
}
return attrs;
}
function getEncryptionAttributes(stanza) {
const eme_tag = sizzle_default()(`encryption[xmlns="${core.NS.EME}"]`, stanza).pop();
const namespace = eme_tag?.getAttribute('namespace');
const attrs = {};
if (namespace) {
attrs.is_encrypted = true;
attrs.encryption_namespace = namespace;
} else if (sizzle_default()(`encrypted[xmlns="${core.NS.OMEMO}"]`, stanza).pop()) {
attrs.is_encrypted = true;
attrs.encryption_namespace = core.NS.OMEMO;
}
return attrs;
}
/**
* @private
* @param { Element } stanza - The message stanza
* @param { Element } original_stanza - The original stanza, that contains the
* message stanza, if it was contained, otherwise it's the message stanza itself.
* @returns { Object }
*/
function getRetractionAttributes(stanza, original_stanza) {
const fastening = sizzle_default()(`> apply-to[xmlns="${core.NS.FASTEN}"]`, stanza).pop();
if (fastening) {
const applies_to_id = fastening.getAttribute('id');
const retracted = sizzle_default()(`> retract[xmlns="${core.NS.RETRACT}"]`, fastening).pop();
if (retracted) {
const delay = sizzle_default()(`delay[xmlns="${core.NS.DELAY}"]`, original_stanza).pop();
const time = delay ? dayjs_min_default()(delay.getAttribute('stamp')).toISOString() : new Date().toISOString();
return {
'editable': false,
'retracted': time,
'retracted_id': applies_to_id
};
}
} else {
const tombstone = sizzle_default()(`> retracted[xmlns="${core.NS.RETRACT}"]`, stanza).pop();
if (tombstone) {
return {
'editable': false,
'is_tombstone': true,
'retracted': tombstone.getAttribute('stamp')
};
}
}
return {};
}
function getCorrectionAttributes(stanza, original_stanza) {
const el = sizzle_default()(`replace[xmlns="${core.NS.MESSAGE_CORRECT}"]`, stanza).pop();
if (el) {
const replace_id = el.getAttribute('id');
if (replace_id) {
const delay = sizzle_default()(`delay[xmlns="${core.NS.DELAY}"]`, original_stanza).pop();
const time = delay ? dayjs_min_default()(delay.getAttribute('stamp')).toISOString() : new Date().toISOString();
return {
replace_id,
'edited': time
};
}
}
return {};
}
function getOpenGraphMetadata(stanza) {
const fastening = sizzle_default()(`> apply-to[xmlns="${core.NS.FASTEN}"]`, stanza).pop();
if (fastening) {
const applies_to_id = fastening.getAttribute('id');
const meta = sizzle_default()(`> meta[xmlns="${core.NS.XHTML}"]`, fastening);
if (meta.length) {
const msg_limit = shared_api.settings.get('message_limit');
const data = meta.reduce((acc, el) => {
const property = el.getAttribute('property');
if (property) {
let value = decodeHTMLEntities(el.getAttribute('content') || '');
if (msg_limit && property === 'og:description' && value.length >= msg_limit) {
value = `${value.slice(0, msg_limit)}${decodeHTMLEntities('…')}`;
}
acc[property] = value;
}
return acc;
}, {
'ogp_for_id': applies_to_id
});
if ("og:description" in data || "og:title" in data || "og:image" in data) {
return data;
}
}
}
return {};
}
function getMediaURLsMetadata(text) {
let offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
const objs = [];
if (!text) {
return {};
}
try {
URI_default().withinString(text, (url, start, end) => {
if (url.startsWith('_')) {
url = url.slice(1);
start += 1;
}
if (url.endsWith('_')) {
url = url.slice(0, url.length - 1);
end -= 1;
}
objs.push({
url,
'start': start + offset,
'end': end + offset
});
return url;
}, URL_PARSE_OPTIONS);
} catch (error) {
log.debug(error);
}
/**
* @typedef { Object } MediaURLMetadata
* An object representing the metadata of a URL found in a chat message
* The actual URL is not saved, it can be extracted via the `start` and `end` indexes.
* @property { Boolean } is_audio
* @property { Boolean } is_image
* @property { Boolean } is_video
* @property { String } end
* @property { String } start
*/
const media_urls = objs.map(o => ({
'end': o.end,
'is_audio': isAudioURL(o.url),
'is_image': isImageURL(o.url),
'is_video': isVideoURL(o.url),
'is_encrypted': isEncryptedFileURL(o.url),
'start': o.start
}));
return media_urls.length ? {
media_urls
} : {};
}
function getSpoilerAttributes(stanza) {
const spoiler = sizzle_default()(`spoiler[xmlns="${core.NS.SPOILER}"]`, stanza).pop();
return {
'is_spoiler': !!spoiler,
'spoiler_hint': spoiler?.textContent
};
}
function getOutOfBandAttributes(stanza) {
const xform = sizzle_default()(`x[xmlns="${core.NS.OUTOFBAND}"]`, stanza).pop();
if (xform) {
return {
'oob_url': xform.querySelector('url')?.textContent,
'oob_desc': xform.querySelector('desc')?.textContent
};
}
return {};
}
/**
* Returns the human readable error message contained in a `groupchat` message stanza of type `error`.
* @private
* @param { Element } stanza - The message stanza
*/
function getErrorAttributes(stanza) {
if (stanza.getAttribute('type') === 'error') {
const error = stanza.querySelector('error');
const text = sizzle_default()(`text[xmlns="${core.NS.STANZAS}"]`, error).pop();
return {
'is_error': true,
'error_text': text?.textContent,
'error_type': error.getAttribute('type'),
'error_condition': error.firstElementChild.nodeName
};
}
return {};
}
/**
* Given a message stanza, find and return any XEP-0372 references
* @param { Element } stana - The message stanza
* @returns { Reference }
*/
function getReferences(stanza) {
return sizzle_default()(`reference[xmlns="${core.NS.REFERENCE}"]`, stanza).map(ref => {
const anchor = ref.getAttribute('anchor');
const text = stanza.querySelector(anchor ? `#${anchor}` : 'body')?.textContent;
if (!text) {
log.warn(`Could not find referenced text for ${ref}`);
return null;
}
const begin = ref.getAttribute('begin');
const end = ref.getAttribute('end');
/**
* @typedef { Object } Reference
* An object representing XEP-0372 reference data
* @property { string } begin
* @property { string } end
* @property { string } type
* @property { String } value
* @property { String } uri
*/
return {
begin,
end,
'type': ref.getAttribute('type'),
'value': text.slice(begin, end),
'uri': ref.getAttribute('uri')
};
}).filter(r => r);
}
function getReceiptId(stanza) {
const receipt = sizzle_default()(`received[xmlns="${core.NS.RECEIPTS}"]`, stanza).pop();
return receipt?.getAttribute('id');
}
/**
* Determines whether the passed in stanza is a XEP-0280 Carbon
* @private
* @param { Element } stanza - The message stanza
* @returns { Boolean }
*/
function isCarbon(stanza) {
const xmlns = core.NS.CARBONS;
return sizzle_default()(`message > received[xmlns="${xmlns}"]`, stanza).length > 0 || sizzle_default()(`message > sent[xmlns="${xmlns}"]`, stanza).length > 0;
}
/**
* Returns the XEP-0085 chat state contained in a message stanza
* @private
* @param { Element } stanza - The message stanza
*/
function getChatState(stanza) {
return sizzle_default()(`
composing[xmlns="${parsers_NS.CHATSTATES}"],
paused[xmlns="${parsers_NS.CHATSTATES}"],
inactive[xmlns="${parsers_NS.CHATSTATES}"],
active[xmlns="${parsers_NS.CHATSTATES}"],
gone[xmlns="${parsers_NS.CHATSTATES}"]`, stanza).pop()?.nodeName;
}
function isValidReceiptRequest(stanza, attrs) {
return attrs.sender !== 'me' && !attrs.is_carbon && !attrs.is_archived && sizzle_default()(`request[xmlns="${core.NS.RECEIPTS}"]`, stanza).length;
}
/**
* Check whether the passed-in stanza is a forwarded message that is "bare",
* i.e. it's not forwarded as part of a larger protocol, like MAM.
* @param { Element } stanza
*/
function throwErrorIfInvalidForward(stanza) {
const bare_forward = sizzle_default()(`message > forwarded[xmlns="${core.NS.FORWARD}"]`, stanza).length;
if (bare_forward) {
rejectMessage(stanza, 'Forwarded messages not part of an encapsulating protocol are not supported');
const from_jid = stanza.getAttribute('from');
throw new StanzaParseError(`Ignoring unencapsulated forwarded message from ${from_jid}`, stanza);
}
}
/**
* Determines whether the passed in stanza is a XEP-0333 Chat Marker
* @private
* @method getChatMarker
* @param { Element } stanza - The message stanza
* @returns { Boolean }
*/
function getChatMarker(stanza) {
// If we receive more than one marker (which shouldn't happen), we take
// the highest level of acknowledgement.
return sizzle_default()(`
acknowledged[xmlns="${core.NS.MARKERS}"],
displayed[xmlns="${core.NS.MARKERS}"],
received[xmlns="${core.NS.MARKERS}"]`, stanza).pop();
}
function isHeadline(stanza) {
return stanza.getAttribute('type') === 'headline';
}
function isServerMessage(stanza) {
if (sizzle_default()(`mentions[xmlns="${core.NS.MENTIONS}"]`, stanza).pop()) {
return false;
}
const from_jid = stanza.getAttribute('from');
if (stanza.getAttribute('type') !== 'error' && from_jid && !from_jid.includes('@')) {
// Some servers (e.g. Prosody) don't set the stanza
// type to "headline" when sending server messages.
// For now we check if an @ signal is included, and if not,
// we assume it's a headline stanza.
return true;
}
return false;
}
/**
* Determines whether the passed in stanza is a XEP-0313 MAM stanza
* @private
* @method isArchived
* @param { Element } stanza - The message stanza
* @returns { Boolean }
*/
function isArchived(original_stanza) {
return !!sizzle_default()(`message > result[xmlns="${core.NS.MAM}"]`, original_stanza).pop();
}
/**
* Returns an object containing all attribute names and values for a particular element.
* @method getAttributes
* @param { Element } stanza
* @returns { Object }
*/
function getAttributes(stanza) {
return stanza.getAttributeNames().reduce((acc, name) => {
acc[name] = core.xmlunescape(stanza.getAttribute(name));
return acc;
}, {});
}
;// CONCATENATED MODULE: ./src/headless/plugins/chat/parsers.js
const {
Strophe: parsers_Strophe,
sizzle: parsers_sizzle
} = converse.env;
/**
* Parses a passed in message stanza and returns an object of attributes.
* @method st#parseMessage
* @param { Element } stanza - The message stanza
* @param { _converse } _converse
* @returns { (MessageAttributes|Error) }
*/
async function parseMessage(stanza) {
throwErrorIfInvalidForward(stanza);
let to_jid = stanza.getAttribute('to');
const to_resource = parsers_Strophe.getResourceFromJid(to_jid);
if (shared_api.settings.get('filter_by_resource') && to_resource && to_resource !== shared_converse.resource) {
return new StanzaParseError(`Ignoring incoming message intended for a different resource: ${to_jid}`, stanza);
}
const original_stanza = stanza;
let from_jid = stanza.getAttribute('from') || shared_converse.bare_jid;
if (isCarbon(stanza)) {
if (from_jid === shared_converse.bare_jid) {
const selector = `[xmlns="${parsers_Strophe.NS.CARBONS}"] > forwarded[xmlns="${parsers_Strophe.NS.FORWARD}"] > message`;
stanza = parsers_sizzle(selector, stanza).pop();
to_jid = stanza.getAttribute('to');
from_jid = stanza.getAttribute('from');
} else {
// Prevent message forging via carbons: https://xmpp.org/extensions/xep-0280.html#security
rejectMessage(stanza, 'Rejecting carbon from invalid JID');
return new StanzaParseError(`Rejecting carbon from invalid JID ${to_jid}`, stanza);
}
}
const is_archived = isArchived(stanza);
if (is_archived) {
if (from_jid === shared_converse.bare_jid) {
const selector = `[xmlns="${parsers_Strophe.NS.MAM}"] > forwarded[xmlns="${parsers_Strophe.NS.FORWARD}"] > message`;
stanza = parsers_sizzle(selector, stanza).pop();
to_jid = stanza.getAttribute('to');
from_jid = stanza.getAttribute('from');
} else {
return new StanzaParseError(`Invalid Stanza: alleged MAM message from ${stanza.getAttribute('from')}`, stanza);
}
}
const from_bare_jid = parsers_Strophe.getBareJidFromJid(from_jid);
const is_me = from_bare_jid === shared_converse.bare_jid;
if (is_me && to_jid === null) {
return new StanzaParseError(`Don't know how to handle message stanza without 'to' attribute. ${stanza.outerHTML}`, stanza);
}
const is_headline = isHeadline(stanza);
const is_server_message = isServerMessage(stanza);
let contact, contact_jid;
if (!is_headline && !is_server_message) {
contact_jid = is_me ? parsers_Strophe.getBareJidFromJid(to_jid) : from_bare_jid;
contact = await shared_api.contacts.get(contact_jid);
if (contact === undefined && !shared_api.settings.get('allow_non_roster_messaging')) {
log.error(stanza);
return new StanzaParseError(`Blocking messaging with a JID not in our roster because allow_non_roster_messaging is false.`, stanza);
}
}
/**
* @typedef { Object } MessageAttributes
* The object which {@link parseMessage} returns
* @property { ('me'|'them') } sender - Whether the message was sent by the current user or someone else
* @property { Array<Object> } references - A list of objects representing XEP-0372 references
* @property { Boolean } editable - Is this message editable via XEP-0308?
* @property { Boolean } is_archived - Is this message from a XEP-0313 MAM archive?
* @property { Boolean } is_carbon - Is this message a XEP-0280 Carbon?
* @property { Boolean } is_delayed - Was delivery of this message was delayed as per XEP-0203?
* @property { Boolean } is_encrypted - Is this message XEP-0384 encrypted?
* @property { Boolean } is_error - Whether an error was received for this message
* @property { Boolean } is_headline - Is this a "headline" message?
* @property { Boolean } is_markable - Can this message be marked with a XEP-0333 chat marker?
* @property { Boolean } is_marker - Is this message a XEP-0333 Chat Marker?
* @property { Boolean } is_only_emojis - Does the message body contain only emojis?
* @property { Boolean } is_spoiler - Is this a XEP-0382 spoiler message?
* @property { Boolean } is_tombstone - Is this a XEP-0424 tombstone?
* @property { Boolean } is_unstyled - Whether XEP-0393 styling hints should be ignored
* @property { Boolean } is_valid_receipt_request - Does this message request a XEP-0184 receipt (and is not from us or a carbon or archived message)
* @property { Object } encrypted - XEP-0384 encryption payload attributes
* @property { String } body - The contents of the <body> tag of the message stanza
* @property { String } chat_state - The XEP-0085 chat state notification contained in this message
* @property { String } contact_jid - The JID of the other person or entity
* @property { String } edited - An ISO8601 string recording the time that the message was edited per XEP-0308
* @property { String } error_condition - The defined error condition
* @property { String } error_text - The error text received from the server
* @property { String } error_type - The type of error received from the server
* @property { String } from - The sender JID
* @property { String } fullname - The full name of the sender
* @property { String } marker - The XEP-0333 Chat Marker value
* @property { String } marker_id - The `id` attribute of a XEP-0333 chat marker
* @property { String } msgid - The root `id` attribute of the stanza
* @property { String } nick - The roster nickname of the sender
* @property { String } oob_desc - The description of the XEP-0066 out of band data
* @property { String } oob_url - The URL of the XEP-0066 out of band data
* @property { String } origin_id - The XEP-0359 Origin ID
* @property { String } receipt_id - The `id` attribute of a XEP-0184 <receipt> element
* @property { String } received - An ISO8601 string recording the time that the message was received
* @property { String } replace_id - The `id` attribute of a XEP-0308 <replace> element
* @property { String } retracted - An ISO8601 string recording the time that the message was retracted
* @property { String } retracted_id - The `id` attribute of a XEP-424 <retracted> element
* @property { String } spoiler_hint The XEP-0382 spoiler hint
* @property { String } stanza_id - The XEP-0359 Stanza ID. Note: the key is actualy `stanza_id ${by_jid}` and there can be multiple.
* @property { String } subject - The <subject> element value
* @property { String } thread - The <thread> element value
* @property { String } time - The time (in ISO8601 format), either given by the XEP-0203 <delay> element, or of receipt.
* @property { String } to - The recipient JID
* @property { String } type - The type of message
*/
const delay = parsers_sizzle(`delay[xmlns="${parsers_Strophe.NS.DELAY}"]`, original_stanza).pop();
const marker = getChatMarker(stanza);
const now = new Date().toISOString();
let attrs = Object.assign({
contact_jid,
is_archived,
is_headline,
is_server_message,
'body': stanza.querySelector('body')?.textContent?.trim(),
'chat_state': getChatState(stanza),
'from': parsers_Strophe.getBareJidFromJid(stanza.getAttribute('from')),
'is_carbon': isCarbon(original_stanza),
'is_delayed': !!delay,
'is_markable': !!parsers_sizzle(`markable[xmlns="${parsers_Strophe.NS.MARKERS}"]`, stanza).length,
'is_marker': !!marker,
'is_unstyled': !!parsers_sizzle(`unstyled[xmlns="${parsers_Strophe.NS.STYLING}"]`, stanza).length,
'marker_id': marker && marker.getAttribute('id'),
'msgid': stanza.getAttribute('id') || original_stanza.getAttribute('id'),
'nick': contact?.attributes?.nickname,
'receipt_id': getReceiptId(stanza),
'received': new Date().toISOString(),
'references': getReferences(stanza),
'sender': is_me ? 'me' : 'them',
'subject': stanza.querySelector('subject')?.textContent,
'thread': stanza.querySelector('thread')?.textContent,
'time': delay ? dayjs_min_default()(delay.getAttribute('stamp')).toISOString() : now,
'to': stanza.getAttribute('to'),
'type': stanza.getAttribute('type') || 'normal'
}, getErrorAttributes(stanza), getOutOfBandAttributes(stanza), getSpoilerAttributes(stanza), getCorrectionAttributes(stanza, original_stanza), getStanzaIDs(stanza, original_stanza), getRetractionAttributes(stanza, original_stanza), getEncryptionAttributes(stanza, shared_converse));
if (attrs.is_archived) {
const from = original_stanza.getAttribute('from');
if (from && from !== shared_converse.bare_jid) {
return new StanzaParseError(`Invalid Stanza: Forged MAM message from ${from}`, stanza);
}
}
await shared_api.emojis.initialize();
attrs = Object.assign({
'message': attrs.body || attrs.error,
// TODO: Remove and use body and error attributes instead
'is_only_emojis': attrs.body ? utils_core.isOnlyEmojis(attrs.body) : false,
'is_valid_receipt_request': isValidReceiptRequest(stanza, attrs)
}, attrs);
// We prefer to use one of the XEP-0359 unique and stable stanza IDs
// as the Model id, to avoid duplicates.
attrs['id'] = attrs['origin_id'] || attrs[`stanza_id ${attrs.from}`] || utils_core.getUniqueId();
/**
* *Hook* which allows plugins to add additional parsing
* @event _converse#parseMessage
*/
attrs = await shared_api.hook('parseMessage', stanza, attrs);
// We call this after the hook, to allow plugins (like omemo) to decrypt encrypted
// messages, since we need to parse the message text to determine whether
// there are media urls.
return Object.assign(attrs, getMediaURLsMetadata(attrs.is_encrypted ? attrs.plaintext : attrs.body));
}
;// CONCATENATED MODULE: ./src/headless/plugins/chat/model.js
const {
Strophe: model_Strophe,
$msg: model_$msg
} = converse.env;
const model_u = converse.env.utils;
/**
* Represents an open/ongoing chat conversation.
*
* @class
* @namespace _converse.ChatBox
* @memberOf _converse
*/
const ChatBox = model_with_contact.extend({
defaults() {
return {
'bookmarked': false,
'chat_state': undefined,
'hidden': isUniView() && !shared_api.settings.get('singleton'),
'message_type': 'chat',
'nickname': undefined,
'num_unread': 0,
'time_opened': this.get('time_opened') || new Date().getTime(),
'time_sent': new Date(0).toISOString(),
'type': shared_converse.PRIVATE_CHAT_TYPE,
'url': ''
};
},
async initialize() {
this.initialized = getOpenPromise();
model_with_contact.prototype.initialize.apply(this, arguments);
const jid = this.get('jid');
if (!jid) {
// XXX: The `validate` method will prevent this model
// from being persisted if there's no jid, but that gets
// called after model instantiation, so we have to deal
// with invalid models here also.
// This happens when the controlbox is in browser storage,
// but we're in embedded mode.
return;
}
this.set({
'box_id': `box-${jid}`
});
this.initNotifications();
this.initUI();
this.initMessages();
if (this.get('type') === shared_converse.PRIVATE_CHAT_TYPE) {
this.presence = shared_converse.presences.get(jid) || shared_converse.presences.create({
jid
});
await this.setRosterContact(jid);
this.presence.on('change:show', item => this.onPresenceChanged(item));
}
this.on('change:chat_state', this.sendChatState, this);
this.ui.on('change:scrolled', this.onScrolledChanged, this);
await this.fetchMessages();
/**
* Triggered once a {@link _converse.ChatBox} has been created and initialized.
* @event _converse#chatBoxInitialized
* @type { _converse.ChatBox}
* @example _converse.api.listen.on('chatBoxInitialized', model => { ... });
*/
await shared_api.trigger('chatBoxInitialized', this, {
'Synchronous': true
});
this.initialized.resolve();
},
getMessagesCollection() {
return new shared_converse.Messages();
},
getMessagesCacheKey() {
return `converse.messages-${this.get('jid')}-${shared_converse.bare_jid}`;
},
initMessages() {
this.messages = this.getMessagesCollection();
this.messages.fetched = getOpenPromise();
this.messages.chatbox = this;
initStorage(this.messages, this.getMessagesCacheKey());
this.listenTo(this.messages, 'change:upload', this.onMessageUploadChanged, this);
this.listenTo(this.messages, 'add', this.onMessageAdded, this);
},
initUI() {
this.ui = new Model();
},
initNotifications() {
this.notifications = new Model();
},
getNotificationsText() {
const {
__
} = shared_converse;
if (this.notifications?.get('chat_state') === shared_converse.COMPOSING) {
return __('%1$s is typing', this.getDisplayName());
} else if (this.notifications?.get('chat_state') === shared_converse.PAUSED) {
return __('%1$s has stopped typing', this.getDisplayName());
} else if (this.notifications?.get('chat_state') === shared_converse.GONE) {
return __('%1$s has gone away', this.getDisplayName());
} else {
return '';
}
},
afterMessagesFetched() {
this.pruneHistoryWhenScrolledDown();
/**
* Triggered whenever a { @link _converse.ChatBox } or ${ @link _converse.ChatRoom }
* has fetched its messages from the local cache.
* @event _converse#afterMessagesFetched
* @type { _converse.ChatBox| _converse.ChatRoom }
* @example _converse.api.listen.on('afterMessagesFetched', (chat) => { ... });
*/
shared_api.trigger('afterMessagesFetched', this);
},
fetchMessages() {
if (this.messages.fetched_flag) {
log.info(`Not re-fetching messages for ${this.get('jid')}`);
return;
}
this.messages.fetched_flag = true;
const resolve = this.messages.fetched.resolve;
this.messages.fetch({
'add': true,
'success': msgs => {
this.afterMessagesFetched(msgs);
resolve();
},
'error': () => {
this.afterMessagesFetched();
resolve();
}
});
return this.messages.fetched;
},
async handleErrorMessageStanza(stanza) {
const {
__
} = shared_converse;
const attrs = await parseMessage(stanza, shared_converse);
if (!(await this.shouldShowErrorMessage(attrs))) {
return;
}
const message = this.getMessageReferencedByError(attrs);
if (message) {
const new_attrs = {
'error': attrs.error,
'error_condition': attrs.error_condition,
'error_text': attrs.error_text,
'error_type': attrs.error_type,
'editable': false
};
if (attrs.msgid === message.get('retraction_id')) {
// The error message refers to a retraction
new_attrs.retraction_id = undefined;
if (!attrs.error) {
if (attrs.error_condition === 'forbidden') {
new_attrs.error = __("You're not allowed to retract your message.");
} else {
new_attrs.error = __('Sorry, an error occurred while trying to retract your message.');
}
}
} else if (!attrs.error) {
if (attrs.error_condition === 'forbidden') {
new_attrs.error = __("You're not allowed to send a message.");
} else {
new_attrs.error = __('Sorry, an error occurred while trying to send your message.');
}
}
message.save(new_attrs);
} else {
this.createMessage(attrs);
}
},
/**
* Queue an incoming `chat` message stanza for processing.
* @async
* @private
* @method _converse.ChatBox#queueMessage
* @param { Promise<MessageAttributes> } attrs - A promise which resolves to the message attributes
*/
queueMessage(attrs) {
this.msg_chain = (this.msg_chain || this.messages.fetched).then(() => this.onMessage(attrs)).catch(e => log.error(e));
return this.msg_chain;
},
/**
* @async
* @private
* @method _converse.ChatBox#onMessage
* @param { MessageAttributes } attrs_promse - A promise which resolves to the message attributes.
*/
async onMessage(attrs) {
attrs = await attrs;
if (model_u.isErrorObject(attrs)) {
attrs.stanza && log.error(attrs.stanza);
return log.error(attrs.message);
}
const message = this.getDuplicateMessage(attrs);
if (message) {
this.updateMessage(message, attrs);
} else if (!this.handleReceipt(attrs) && !this.handleChatMarker(attrs) && !(await this.handleRetraction(attrs))) {
this.setEditable(attrs, attrs.time);
if (attrs['chat_state'] && attrs.sender === 'them') {
this.notifications.set('chat_state', attrs.chat_state);
}
if (model_u.shouldCreateMessage(attrs)) {
const msg = (await handleCorrection(this, attrs)) || (await this.createMessage(attrs));
this.notifications.set({
'chat_state': null
});
this.handleUnreadMessage(msg);
}
}
},
async onMessageUploadChanged(message) {
if (message.get('upload') === shared_converse.SUCCESS) {
const attrs = {
'body': message.get('body'),
'spoiler_hint': message.get('spoiler_hint'),
'oob_url': message.get('oob_url')
};
await this.sendMessage(attrs);
message.destroy();
}
},
onMessageAdded(message) {
if (shared_api.settings.get('prune_messages_above') && (shared_api.settings.get('pruning_behavior') === 'scrolled' || !this.ui.get('scrolled')) && !isEmptyMessage(message)) {
debouncedPruneHistory(this);
}
},
async clearMessages() {
try {
await this.messages.clearStore();
} catch (e) {
this.messages.trigger('reset');
log.error(e);
} finally {
// No point in fetching messages from the cache if it's been cleared.
// Make sure to resolve the fetched promise to avoid freezes.
this.messages.fetched.resolve();
}
},
async close() {
if (shared_api.connection.connected()) {
// Immediately sending the chat state, because the
// model is going to be destroyed afterwards.
this.setChatState(shared_converse.INACTIVE);
this.sendChatState();
}
try {
await new Promise((success, reject) => {
return this.destroy({
success,
'error': (m, e) => reject(e)
});
});
} catch (e) {
log.error(e);
} finally {
if (shared_api.settings.get('clear_messages_on_reconnection')) {
await this.clearMessages();
}
}
/**
* Triggered once a chatbox has been closed.
* @event _converse#chatBoxClosed
* @type {_converse.ChatBox | _converse.ChatRoom}
* @example _converse.api.listen.on('chatBoxClosed', chat => { ... });
*/
shared_api.trigger('chatBoxClosed', this);
},
announceReconnection() {
/**
* Triggered whenever a `_converse.ChatBox` instance has reconnected after an outage
* @event _converse#onChatReconnected
* @type {_converse.ChatBox | _converse.ChatRoom}
* @example _converse.api.listen.on('onChatReconnected', chat => { ... });
*/
shared_api.trigger('chatReconnected', this);
},
async onReconnection() {
if (shared_api.settings.get('clear_messages_on_reconnection')) {
await this.clearMessages();
}
this.announceReconnection();
},
onPresenceChanged(item) {
const {
__
} = shared_converse;
const show = item.get('show');
const fullname = this.getDisplayName();
let text;
if (show === 'offline') {
text = __('%1$s has gone offline', fullname);
} else if (show === 'away') {
text = __('%1$s has gone away', fullname);
} else if (show === 'dnd') {
text = __('%1$s is busy', fullname);
} else if (show === 'online') {
text = __('%1$s is online', fullname);
}
text && this.createMessage({
'message': text,
'type': 'info'
});
},
onScrolledChanged() {
if (!this.ui.get('scrolled')) {
this.clearUnreadMsgCounter();
this.pruneHistoryWhenScrolledDown();
}
},
pruneHistoryWhenScrolledDown() {
if (shared_api.settings.get('prune_messages_above') && shared_api.settings.get('pruning_behavior') === 'unscrolled' && !this.ui.get('scrolled')) {
debouncedPruneHistory(this);
}
},
validate(attrs) {
if (!attrs.jid) {
return 'Ignored ChatBox without JID';
}
const room_jids = shared_api.settings.get('auto_join_rooms').map(s => lodash_es_isObject(s) ? s.jid : s);
const auto_join = shared_api.settings.get('auto_join_private_chats').concat(room_jids);
if (shared_api.settings.get("singleton") && !auto_join.includes(attrs.jid) && !shared_api.settings.get('auto_join_on_invite')) {
const msg = `${attrs.jid} is not allowed because singleton is true and it's not being auto_joined`;
log.warn(msg);
return msg;
}
},
getDisplayName() {
if (this.contact) {
return this.contact.getDisplayName();
} else if (this.vcard) {
return this.vcard.getDisplayName();
} else {
return this.get('jid');
}
},
async createMessageFromError(error) {
if (error instanceof TimeoutError) {
const msg = await this.createMessage({
'type': 'error',
'message': error.message,
'retry_event_id': error.retry_event_id,
'is_ephemeral': 30000
});
msg.error = error;
}
},
editEarlierMessage() {
let message;
let idx = this.messages.findLastIndex('correcting');
if (idx >= 0) {
this.messages.at(idx).save('correcting', false);
while (idx > 0) {
idx -= 1;
const candidate = this.messages.at(idx);
if (candidate.get('editable')) {
message = candidate;
break;
}
}
}
message = message || this.messages.filter({
'sender': 'me'
}).reverse().find(m => m.get('editable'));
if (message) {
message.save('correcting', true);
}
},
editLaterMessage() {
let message;
let idx = this.messages.findLastIndex('correcting');
if (idx >= 0) {
this.messages.at(idx).save('correcting', false);
while (idx < this.messages.length - 1) {
idx += 1;
const candidate = this.messages.at(idx);
if (candidate.get('editable')) {
message = candidate;
message.save('correcting', true);
break;
}
}
}
return message;
},
getOldestMessage() {
for (let i = 0; i < this.messages.length; i++) {
const message = this.messages.at(i);
if (message.get('type') === this.get('message_type')) {
return message;
}
}
},
getMostRecentMessage() {
for (let i = this.messages.length - 1; i >= 0; i--) {
const message = this.messages.at(i);
if (message.get('type') === this.get('message_type')) {
return message;
}
}
},
getUpdatedMessageAttributes(message, attrs) {
if (!attrs.error_type && message.get('error_type') === 'Decryption') {
// Looks like we have a failed decrypted message stored, and now
// we have a properly decrypted version of the same message.
// See issue: https://github.com/conversejs/converse.js/issues/2733#issuecomment-1035493594
return Object.assign({}, attrs, {
error_condition: undefined,
error_message: undefined,
error_text: undefined,
error_type: undefined,
is_archived: attrs.is_archived,
is_ephemeral: false,
is_error: false
});
} else {
return {
is_archived: attrs.is_archived
};
}
},
updateMessage(message, attrs) {
const new_attrs = this.getUpdatedMessageAttributes(message, attrs);
new_attrs && message.save(new_attrs);
},
/**
* Mutator for setting the chat state of this chat session.
* Handles clearing of any chat state notification timeouts and
* setting new ones if necessary.
* Timeouts are set when the state being set is COMPOSING or PAUSED.
* After the timeout, COMPOSING will become PAUSED and PAUSED will become INACTIVE.
* See XEP-0085 Chat State Notifications.
* @private
* @method _converse.ChatBox#setChatState
* @param { string } state - The chat state (consts ACTIVE, COMPOSING, PAUSED, INACTIVE, GONE)
*/
setChatState(state, options) {
if (this.chat_state_timeout !== undefined) {
window.clearTimeout(this.chat_state_timeout);
delete this.chat_state_timeout;
}
if (state === shared_converse.COMPOSING) {
this.chat_state_timeout = window.setTimeout(this.setChatState.bind(this), shared_converse.TIMEOUTS.PAUSED, shared_converse.PAUSED);
} else if (state === shared_converse.PAUSED) {
this.chat_state_timeout = window.setTimeout(this.setChatState.bind(this), shared_converse.TIMEOUTS.INACTIVE, shared_converse.INACTIVE);
}
this.set('chat_state', state, options);
return this;
},
/**
* Given an error `<message>` stanza's attributes, find the saved message model which is
* referenced by that error.
* @param { Object } attrs
*/
getMessageReferencedByError(attrs) {
const id = attrs.msgid;
return id && this.messages.models.find(m => [m.get('msgid'), m.get('retraction_id')].includes(id));
},
/**
* @private
* @method _converse.ChatBox#shouldShowErrorMessage
* @returns {boolean}
*/
shouldShowErrorMessage(attrs) {
const msg = this.getMessageReferencedByError(attrs);
if (!msg && attrs.chat_state) {
// If the error refers to a message not included in our store,
// and it has a chat state tag, we assume that this was a
// CSI message (which we don't store).
// See https://github.com/conversejs/converse.js/issues/1317
return;
}
// Gets overridden in ChatRoom
return true;
},
isSameUser(jid1, jid2) {
return model_u.isSameBareJID(jid1, jid2);
},
/**
* Looks whether we already have a retraction for this
* incoming message. If so, it's considered "dangling" because it
* probably hasn't been applied to anything yet, given that the
* relevant message is only coming in now.
* @private
* @method _converse.ChatBox#findDanglingRetraction
* @param { object } attrs - Attributes representing a received
* message, as returned by {@link parseMessage}
* @returns { _converse.Message }
*/
findDanglingRetraction(attrs) {
if (!attrs.origin_id || !this.messages.length) {
return null;
}
// Only look for dangling retractions if there are newer
// messages than this one, since retractions come after.
if (this.messages.last().get('time') > attrs.time) {
// Search from latest backwards
const messages = Array.from(this.messages.models);
messages.reverse();
return messages.find(_ref => {
let {
attributes
} = _ref;
return attributes.retracted_id === attrs.origin_id && attributes.from === attrs.from && !attributes.moderated_by;
});
}
},
/**
* Handles message retraction based on the passed in attributes.
* @private
* @method _converse.ChatBox#handleRetraction
* @param { object } attrs - Attributes representing a received
* message, as returned by {@link parseMessage}
* @returns { Boolean } Returns `true` or `false` depending on
* whether a message was retracted or not.
*/
async handleRetraction(attrs) {
const RETRACTION_ATTRIBUTES = ['retracted', 'retracted_id', 'editable'];
if (attrs.retracted) {
if (attrs.is_tombstone) {
return false;
}
const message = this.messages.findWhere({
'origin_id': attrs.retracted_id,
'from': attrs.from
});
if (!message) {
attrs['dangling_retraction'] = true;
await this.createMessage(attrs);
return true;
}
message.save(lodash_es_pick(attrs, RETRACTION_ATTRIBUTES));
return true;
} else {
// Check if we have dangling retraction
const message = this.findDanglingRetraction(attrs);
if (message) {
const retraction_attrs = lodash_es_pick(message.attributes, RETRACTION_ATTRIBUTES);
const new_attrs = Object.assign({
'dangling_retraction': false
}, attrs, retraction_attrs);
delete new_attrs['id']; // Delete id, otherwise a new cache entry gets created
message.save(new_attrs);
return true;
}
}
return false;
},
/**
* Returns an already cached message (if it exists) based on the
* passed in attributes map.
* @private
* @method _converse.ChatBox#getDuplicateMessage
* @param { object } attrs - Attributes representing a received
* message, as returned by {@link parseMessage}
* @returns {Promise<_converse.Message>}
*/
getDuplicateMessage(attrs) {
const queries = [...this.getStanzaIdQueryAttrs(attrs), this.getOriginIdQueryAttrs(attrs), this.getMessageBodyQueryAttrs(attrs)].filter(s => s);
const msgs = this.messages.models;
return msgs.find(m => queries.reduce((out, q) => out || lodash_es_isMatch(m.attributes, q), false));
},
getOriginIdQueryAttrs(attrs) {
return attrs.origin_id && {
'origin_id': attrs.origin_id,
'from': attrs.from
};
},
getStanzaIdQueryAttrs(attrs) {
const keys = Object.keys(attrs).filter(k => k.startsWith('stanza_id '));
return keys.map(key => {
const by_jid = key.replace(/^stanza_id /, '');
const query = {};
query[`stanza_id ${by_jid}`] = attrs[key];
return query;
});
},
getMessageBodyQueryAttrs(attrs) {
if (attrs.msgid) {
const query = {
'from': attrs.from,
'msgid': attrs.msgid
};
// XXX: Need to take XEP-428 <fallback> into consideration
if (!attrs.is_encrypted && attrs.body) {
// We can't match the message if it's a reflected
// encrypted message (e.g. via MAM or in a MUC)
query['body'] = attrs.body;
}
return query;
}
},
/**
* Retract one of your messages in this chat
* @private
* @method _converse.ChatBoxView#retractOwnMessage
* @param { _converse.Message } message - The message which we're retracting.
*/
retractOwnMessage(message) {
this.sendRetractionMessage(message);
message.save({
'retracted': new Date().toISOString(),
'retracted_id': message.get('origin_id'),
'retraction_id': message.get('id'),
'is_ephemeral': true,
'editable': false
});
},
/**
* Sends a message stanza to retract a message in this chat
* @private
* @method _converse.ChatBox#sendRetractionMessage
* @param { _converse.Message } message - The message which we're retracting.
*/
sendRetractionMessage(message) {
const origin_id = message.get('origin_id');
if (!origin_id) {
throw new Error("Can't retract message without a XEP-0359 Origin ID");
}
const msg = model_$msg({
'id': model_u.getUniqueId(),
'to': this.get('jid'),
'type': "chat"
}).c('store', {
xmlns: model_Strophe.NS.HINTS
}).up().c("apply-to", {
'id': origin_id,
'xmlns': model_Strophe.NS.FASTEN
}).c('retract', {
xmlns: model_Strophe.NS.RETRACT
});
return shared_converse.connection.send(msg);
},
/**
* Finds the last eligible message and then sends a XEP-0333 chat marker for it.
* @param { ('received'|'displayed'|'acknowledged') } [type='displayed']
* @param { Boolean } force - Whether a marker should be sent for the
* message, even if it didn't include a `markable` element.
*/
sendMarkerForLastMessage() {
let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'displayed';
let force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
const msgs = Array.from(this.messages.models);
msgs.reverse();
const msg = msgs.find(m => m.get('sender') === 'them' && (force || m.get('is_markable')));
msg && this.sendMarkerForMessage(msg, type, force);
},
/**
* Given the passed in message object, send a XEP-0333 chat marker.
* @param { _converse.Message } msg
* @param { ('received'|'displayed'|'acknowledged') } [type='displayed']
* @param { Boolean } force - Whether a marker should be sent for the
* message, even if it didn't include a `markable` element.
*/
sendMarkerForMessage(msg) {
let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'displayed';
let force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!msg || !shared_api.settings.get('send_chat_markers').includes(type)) {
return;
}
if (msg?.get('is_markable') || force) {
const from_jid = model_Strophe.getBareJidFromJid(msg.get('from'));
sendMarker(from_jid, msg.get('msgid'), type, msg.get('type'));
}
},
handleChatMarker(attrs) {
const to_bare_jid = model_Strophe.getBareJidFromJid(attrs.to);
if (to_bare_jid !== shared_converse.bare_jid) {
return false;
}
if (attrs.is_markable) {
if (this.contact && !attrs.is_archived && !attrs.is_carbon) {
sendMarker(attrs.from, attrs.msgid, 'received');
}
return false;
} else if (attrs.marker_id) {
const message = this.messages.findWhere({
'msgid': attrs.marker_id
});
const field_name = `marker_${attrs.marker}`;
if (message && !message.get(field_name)) {
message.save({
field_name: new Date().toISOString()
});
}
return true;
}
},
sendReceiptStanza(to_jid, id) {
const receipt_stanza = model_$msg({
'from': shared_converse.connection.jid,
'id': model_u.getUniqueId(),
'to': to_jid,
'type': 'chat'
}).c('received', {
'xmlns': model_Strophe.NS.RECEIPTS,
'id': id
}).up().c('store', {
'xmlns': model_Strophe.NS.HINTS
}).up();
shared_api.send(receipt_stanza);
},
handleReceipt(attrs) {
if (attrs.sender === 'them') {
if (attrs.is_valid_receipt_request) {
this.sendReceiptStanza(attrs.from, attrs.msgid);
} else if (attrs.receipt_id) {
const message = this.messages.findWhere({
'msgid': attrs.receipt_id
});
if (message && !message.get('received')) {
message.save({
'received': new Date().toISOString()
});
}
return true;
}
}
return false;
},
/**
* Given a {@link _converse.Message} return the XML stanza that represents it.
* @private
* @method _converse.ChatBox#createMessageStanza
* @param { _converse.Message } message - The message object
*/
async createMessageStanza(message) {
const stanza = model_$msg({
'from': shared_converse.connection.jid,
'to': this.get('jid'),
'type': this.get('message_type'),
'id': message.get('edited') && model_u.getUniqueId() || message.get('msgid')
}).c('body').t(message.get('body')).up().c(shared_converse.ACTIVE, {
'xmlns': model_Strophe.NS.CHATSTATES
}).root();
if (message.get('type') === 'chat') {
stanza.c('request', {
'xmlns': model_Strophe.NS.RECEIPTS
}).root();
}
if (!message.get('is_encrypted')) {
if (message.get('is_spoiler')) {
if (message.get('spoiler_hint')) {
stanza.c('spoiler', {
'xmlns': model_Strophe.NS.SPOILER
}, message.get('spoiler_hint')).root();
} else {
stanza.c('spoiler', {
'xmlns': model_Strophe.NS.SPOILER
}).root();
}
}
(message.get('references') || []).forEach(reference => {
const attrs = {
'xmlns': model_Strophe.NS.REFERENCE,
'begin': reference.begin,
'end': reference.end,
'type': reference.type
};
if (reference.uri) {
attrs.uri = reference.uri;
}
stanza.c('reference', attrs).root();
});
if (message.get('oob_url')) {
stanza.c('x', {
'xmlns': model_Strophe.NS.OUTOFBAND
}).c('url').t(message.get('oob_url')).root();
}
}
if (message.get('edited')) {
stanza.c('replace', {
'xmlns': model_Strophe.NS.MESSAGE_CORRECT,
'id': message.get('msgid')
}).root();
}
if (message.get('origin_id')) {
stanza.c('origin-id', {
'xmlns': model_Strophe.NS.SID,
'id': message.get('origin_id')
}).root();
}
stanza.root();
/**
* *Hook* which allows plugins to update an outgoing message stanza
* @event _converse#createMessageStanza
* @param { _converse.ChatBox | _converse.ChatRoom } - The chat from
* which this message stanza is being sent.
* @param { Object } data - Message data
* @param { _converse.Message | _converse.ChatRoomMessage } data.message
* The message object from which the stanza is created and which gets persisted to storage.
* @param { Strophe.Builder } data.stanza
* The stanza that will be sent out, as a Strophe.Builder object.
* You can use the Strophe.Builder functions to extend the stanza.
* See http://strophe.im/strophejs/doc/1.4.3/files/strophe-umd-js.html#Strophe.Builder.Functions
*/
const data = await shared_api.hook('createMessageStanza', this, {
message,
stanza
});
return data.stanza;
},
async getOutgoingMessageAttributes(attrs) {
await shared_api.emojis.initialize();
const is_spoiler = !!this.get('composing_spoiler');
const origin_id = model_u.getUniqueId();
const text = attrs?.body;
const body = text ? model_u.shortnamesToUnicode(text) : undefined;
attrs = Object.assign({}, attrs, {
'from': shared_converse.bare_jid,
'fullname': shared_converse.xmppstatus.get('fullname'),
'id': origin_id,
'is_only_emojis': text ? model_u.isOnlyEmojis(text) : false,
'jid': this.get('jid'),
'message': body,
'msgid': origin_id,
'nickname': this.get('nickname'),
'sender': 'me',
'time': new Date().toISOString(),
'type': this.get('message_type'),
body,
is_spoiler,
origin_id
}, getMediaURLsMetadata(text));
/**
* *Hook* which allows plugins to update the attributes of an outgoing message.
* These attributes get set on the { @link _converse.Message } or
* { @link _converse.ChatRoomMessage } and persisted to storage.
* @event _converse#getOutgoingMessageAttributes
* @param { _converse.ChatBox | _converse.ChatRoom } chat
* The chat from which this message will be sent.
* @param { MessageAttributes } attrs
* The message attributes, from which the stanza will be created.
*/
attrs = await shared_api.hook('getOutgoingMessageAttributes', this, attrs);
return attrs;
},
/**
* Responsible for setting the editable attribute of messages.
* If api.settings.get('allow_message_corrections') is "last", then only the last
* message sent from me will be editable. If set to "all" all messages
* will be editable. Otherwise no messages will be editable.
* @method _converse.ChatBox#setEditable
* @memberOf _converse.ChatBox
* @param { Object } attrs An object containing message attributes.
* @param { String } send_time - time when the message was sent
*/
setEditable(attrs, send_time) {
if (attrs.is_headline || isEmptyMessage(attrs) || attrs.sender !== 'me') {
return;
}
if (shared_api.settings.get('allow_message_corrections') === 'all') {
attrs.editable = !(attrs.file || attrs.retracted || 'oob_url' in attrs);
} else if (shared_api.settings.get('allow_message_corrections') === 'last' && send_time > this.get('time_sent')) {
this.set({
'time_sent': send_time
});
this.messages.findWhere({
'editable': true
})?.save({
'editable': false
});
attrs.editable = !(attrs.file || attrs.retracted || 'oob_url' in attrs);
}
},
/**
* Queue the creation of a message, to make sure that we don't run
* into a race condition whereby we're creating a new message
* before the collection has been fetched.
* @async
* @private
* @method _converse.ChatBox#createMessage
* @param { Object } attrs
*/
async createMessage(attrs, options) {
attrs.time = attrs.time || new Date().toISOString();
await this.messages.fetched;
return this.messages.create(attrs, options);
},
/**
* Responsible for sending off a text message inside an ongoing chat conversation.
* @private
* @method _converse.ChatBox#sendMessage
* @memberOf _converse.ChatBox
* @param { Object } [attrs] - A map of attributes to be saved on the message
* @returns { _converse.Message }
* @example
* const chat = api.chats.get('buddy1@example.org');
* chat.sendMessage({'body': 'hello world'});
*/
async sendMessage(attrs) {
attrs = await this.getOutgoingMessageAttributes(attrs);
let message = this.messages.findWhere('correcting');
if (message) {
const older_versions = message.get('older_versions') || {};
const edited_time = message.get('edited') || message.get('time');
older_versions[edited_time] = message.getMessageText();
message.save({
...lodash_es_pick(attrs, ['body', 'is_only_emojis', 'media_urls', 'references', 'is_encrypted']),
...{
'correcting': false,
'edited': new Date().toISOString(),
'message': attrs.body,
'ogp_metadata': [],
'origin_id': model_u.getUniqueId(),
'received': undefined,
older_versions,
plaintext: attrs.is_encrypted ? attrs.message : undefined
}
});
} else {
this.setEditable(attrs, new Date().toISOString());
message = await this.createMessage(attrs);
}
try {
const stanza = await this.createMessageStanza(message);
shared_api.send(stanza);
} catch (e) {
message.destroy();
log.error(e);
return;
}
/**
* Triggered when a message is being sent out
* @event _converse#sendMessage
* @type { Object }
* @param { Object } data
* @property { (_converse.ChatBox | _converse.ChatRoom) } data.chatbox
* @property { (_converse.Message | _converse.ChatRoomMessage) } data.message
*/
shared_api.trigger('sendMessage', {
'chatbox': this,
message
});
return message;
},
/**
* Sends a message with the current XEP-0085 chat state of the user
* as taken from the `chat_state` attribute of the {@link _converse.ChatBox}.
* @private
* @method _converse.ChatBox#sendChatState
*/
sendChatState() {
if (shared_api.settings.get('send_chat_state_notifications') && this.get('chat_state')) {
const allowed = shared_api.settings.get('send_chat_state_notifications');
if (Array.isArray(allowed) && !allowed.includes(this.get('chat_state'))) {
return;
}
shared_api.send(model_$msg({
'id': model_u.getUniqueId(),
'to': this.get('jid'),
'type': 'chat'
}).c(this.get('chat_state'), {
'xmlns': model_Strophe.NS.CHATSTATES
}).up().c('no-store', {
'xmlns': model_Strophe.NS.HINTS
}).up().c('no-permanent-store', {
'xmlns': model_Strophe.NS.HINTS
}));
}
},
async sendFiles(files) {
const {
__
} = shared_converse;
const result = await shared_api.disco.features.get(model_Strophe.NS.HTTPUPLOAD, shared_converse.domain);
const item = result.pop();
if (!item) {
this.createMessage({
'message': __("Sorry, looks like file upload is not supported by your server."),
'type': 'error',
'is_ephemeral': true
});
return;
}
const data = item.dataforms.where({
'FORM_TYPE': {
'value': model_Strophe.NS.HTTPUPLOAD,
'type': "hidden"
}
}).pop();
const max_file_size = window.parseInt((data?.attributes || {})['max-file-size']?.value);
const slot_request_url = item?.id;
if (!slot_request_url) {
this.createMessage({
'message': __("Sorry, looks like file upload is not supported by your server."),
'type': 'error',
'is_ephemeral': true
});
return;
}
Array.from(files).forEach(async file => {
/**
* *Hook* which allows plugins to transform files before they'll be
* uploaded. The main use-case is to encrypt the files.
* @event _converse#beforeFileUpload
* @param { _converse.ChatBox | _converse.ChatRoom } chat
* The chat from which this file will be uploaded.
* @param { File } file
* The file that will be uploaded
*/
file = await shared_api.hook('beforeFileUpload', this, file);
if (!window.isNaN(max_file_size) && window.parseInt(file.size) > max_file_size) {
return this.createMessage({
'message': __('The size of your file, %1$s, exceeds the maximum allowed by your server, which is %2$s.', file.name, filesize(max_file_size)),
'type': 'error',
'is_ephemeral': true
});
} else {
const initial_attrs = await this.getOutgoingMessageAttributes();
const attrs = Object.assign(initial_attrs, {
'file': true,
'progress': 0,
'slot_request_url': slot_request_url
});
this.setEditable(attrs, new Date().toISOString());
const message = await this.createMessage(attrs, {
'silent': true
});
message.file = file;
this.messages.trigger('add', message);
message.getRequestSlotURL();
}
});
},
maybeShow(force) {
if (isUniView()) {
const filter = c => !c.get('hidden') && c.get('jid') !== this.get('jid') && c.get('id') !== 'controlbox';
const other_chats = shared_converse.chatboxes.filter(filter);
if (force || other_chats.length === 0) {
// We only have one chat visible at any one time.
// So before opening a chat, we make sure all other chats are hidden.
other_chats.forEach(c => model_u.safeSave(c, {
'hidden': true
}));
model_u.safeSave(this, {
'hidden': false
});
}
return;
}
model_u.safeSave(this, {
'hidden': false
});
this.trigger('show');
return this;
},
/**
* Indicates whether the chat is hidden and therefore
* whether a newly received message will be visible
* to the user or not.
* @returns {boolean}
*/
isHidden() {
// Note: This methods gets overridden by converse-minimize
return this.get('hidden') || this.isScrolledUp() || shared_converse.windowState === 'hidden';
},
/**
* Given a newly received {@link _converse.Message} instance,
* update the unread counter if necessary.
* @private
* @method _converse.ChatBox#handleUnreadMessage
* @param {_converse.Message} message
*/
handleUnreadMessage(message) {
if (!message?.get('body')) {
return;
}
if (model_u.isNewMessage(message)) {
if (message.get('sender') === 'me') {
// We remove the "scrolled" flag so that the chat area
// gets scrolled down. We always want to scroll down
// when the user writes a message as opposed to when a
// message is received.
this.ui.set('scrolled', false);
} else if (this.isHidden()) {
this.incrementUnreadMsgsCounter(message);
} else {
this.sendMarkerForMessage(message);
}
}
},
incrementUnreadMsgsCounter(message) {
const settings = {
'num_unread': this.get('num_unread') + 1
};
if (this.get('num_unread') === 0) {
settings['first_unread_id'] = message.get('id');
}
this.save(settings);
},
clearUnreadMsgCounter() {
if (this.get('num_unread') > 0) {
this.sendMarkerForMessage(this.messages.last());
}
model_u.safeSave(this, {
'num_unread': 0
});
},
isScrolledUp() {
return this.ui.get('scrolled');
}
});
/* harmony default export */ const model = (ChatBox);
;// CONCATENATED MODULE: ./src/headless/plugins/chat/message.js
const {
Strophe: message_Strophe,
sizzle: message_sizzle,
u: message_u
} = converse.env;
/**
* Mixin which turns a `ModelWithContact` model into a non-MUC message.
* These can be either `chat`, `normal` or `headline` messages.
* @mixin
* @namespace _converse.Message
* @memberOf _converse
* @example const msg = new _converse.Message({'message': 'hello world!'});
*/
const MessageMixin = {
defaults() {
return {
'msgid': message_u.getUniqueId(),
'time': new Date().toISOString(),
'is_ephemeral': false
};
},
async initialize() {
if (!this.checkValidity()) {
return;
}
this.initialized = getOpenPromise();
if (this.get('file')) {
this.on('change:put', () => this.uploadFile());
}
// If `type` changes from `error` to `chat`, we want to set the contact. See #2733
this.on('change:type', () => this.setContact());
this.on('change:is_ephemeral', () => this.setTimerForEphemeralMessage());
await this.setContact();
this.setTimerForEphemeralMessage();
/**
* Triggered once a {@link _converse.Message} has been created and initialized.
* @event _converse#messageInitialized
* @type { _converse.Message}
* @example _converse.api.listen.on('messageInitialized', model => { ... });
*/
await shared_api.trigger('messageInitialized', this, {
'Synchronous': true
});
this.initialized.resolve();
},
setContact() {
if (['chat', 'normal'].includes(this.get('type'))) {
model_with_contact.prototype.initialize.apply(this, arguments);
this.setRosterContact(message_Strophe.getBareJidFromJid(this.get('from')));
}
},
/**
* Sets an auto-destruct timer for this message, if it's is_ephemeral.
* @private
* @method _converse.Message#setTimerForEphemeralMessage
*/
setTimerForEphemeralMessage() {
if (this.ephemeral_timer) {
clearTimeout(this.ephemeral_timer);
}
const is_ephemeral = this.isEphemeral();
if (is_ephemeral) {
const timeout = typeof is_ephemeral === "number" ? is_ephemeral : 10000;
this.ephemeral_timer = window.setTimeout(() => this.safeDestroy(), timeout);
}
},
checkValidity() {
if (Object.keys(this.attributes).length === 3) {
// XXX: This is an empty message with only the 3 default values.
// This seems to happen when saving a newly created message
// fails for some reason.
// TODO: This is likely fixable by setting `wait` when
// creating messages. See the wait-for-messages branch.
this.validationError = 'Empty message';
this.safeDestroy();
return false;
}
return true;
},
/**
* Determines whether this messsage may be retracted by the current user.
* @private
* @method _converse.Messages#mayBeRetracted
* @returns { Boolean }
*/
mayBeRetracted() {
const is_own_message = this.get('sender') === 'me';
const not_canceled = this.get('error_type') !== 'cancel';
return is_own_message && not_canceled && ['all', 'own'].includes(shared_api.settings.get('allow_message_retraction'));
},
safeDestroy() {
try {
this.destroy();
} catch (e) {
log.warn(`safeDestroy: ${e}`);
}
},
/**
* Returns a boolean indicating whether this message is ephemeral,
* meaning it will get automatically removed after ten seconds.
* @returns { boolean }
*/
isEphemeral() {
return this.get('is_ephemeral');
},
/**
* Returns a boolean indicating whether this message is a XEP-0245 /me command.
* @returns { boolean }
*/
isMeCommand() {
const text = this.getMessageText();
if (!text) {
return false;
}
return text.startsWith('/me ');
},
/**
* Returns a boolean indicating whether this message is considered a followup
* message from the previous one. Followup messages are shown grouped together
* under one author heading.
* A message is considered a followup of it's predecessor when it's a chat
* message from the same author, within 10 minutes.
* @returns { boolean }
*/
isFollowup() {
const messages = this.collection.models;
const idx = messages.indexOf(this);
const prev_model = idx ? messages[idx - 1] : null;
if (prev_model === null) {
return false;
}
const date = dayjs_min_default()(this.get('time'));
return this.get('from') === prev_model.get('from') && !this.isMeCommand() && !prev_model.isMeCommand() && !!this.get('is_encrypted') === !!prev_model.get('is_encrypted') && this.get('type') === prev_model.get('type') && this.get('type') !== 'info' && date.isBefore(dayjs_min_default()(prev_model.get('time')).add(10, 'minutes')) && (this.get('type') === 'groupchat' ? this.get('occupant_id') === prev_model.get('occupant_id') : true);
},
getDisplayName() {
if (this.contact) {
return this.contact.getDisplayName();
} else if (this.vcard) {
return this.vcard.getDisplayName();
} else {
return this.get('from');
}
},
getMessageText() {
if (this.get('is_encrypted')) {
const {
__
} = shared_converse;
return this.get('plaintext') || this.get('body') || __('Undecryptable OMEMO message');
} else if (['groupchat', 'chat', 'normal'].includes(this.get('type'))) {
return this.get('body');
} else {
return this.get('message');
}
},
/**
* Send out an IQ stanza to request a file upload slot.
* https://xmpp.org/extensions/xep-0363.html#request
* @private
* @method _converse.Message#sendSlotRequestStanza
*/
sendSlotRequestStanza() {
if (!this.file) {
return Promise.reject(new Error('file is undefined'));
}
const iq = converse.env.$iq({
'from': shared_converse.jid,
'to': this.get('slot_request_url'),
'type': 'get'
}).c('request', {
'xmlns': message_Strophe.NS.HTTPUPLOAD,
'filename': this.file.name,
'size': this.file.size,
'content-type': this.file.type
});
return shared_api.sendIQ(iq);
},
getUploadRequestMetadata(stanza) {
const headers = message_sizzle(`slot[xmlns="${message_Strophe.NS.HTTPUPLOAD}"] put header`, stanza);
// https://xmpp.org/extensions/xep-0363.html#request
// TODO: Can't set the Cookie header in JavaScipt, instead cookies need
// to be manually set via document.cookie, so we're leaving it out here.
return {
'headers': headers.map(h => ({
'name': h.getAttribute('name'),
'value': h.textContent
})).filter(h => ['Authorization', 'Expires'].includes(h.name))
};
},
async getRequestSlotURL() {
const {
__
} = shared_converse;
let stanza;
try {
stanza = await this.sendSlotRequestStanza();
} catch (e) {
log.error(e);
return this.save({
'type': 'error',
'message': __('Sorry, could not determine upload URL.'),
'is_ephemeral': true
});
}
const slot = message_sizzle(`slot[xmlns="${message_Strophe.NS.HTTPUPLOAD}"]`, stanza).pop();
if (slot) {
this.upload_metadata = this.getUploadRequestMetadata(stanza);
this.save({
'get': slot.querySelector('get').getAttribute('url'),
'put': slot.querySelector('put').getAttribute('url')
});
} else {
return this.save({
'type': 'error',
'message': __('Sorry, could not determine file upload URL.'),
'is_ephemeral': true
});
}
},
uploadFile() {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = async () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
log.info('Status: ' + xhr.status);
if (xhr.status === 200 || xhr.status === 201) {
let attrs = {
'upload': shared_converse.SUCCESS,
'oob_url': this.get('get'),
'message': this.get('get'),
'body': this.get('get')
};
/**
* *Hook* which allows plugins to change the attributes
* saved on the message once a file has been uploaded.
* @event _converse#afterFileUploaded
*/
attrs = await shared_api.hook('afterFileUploaded', this, attrs);
this.save(attrs);
} else {
xhr.onerror();
}
}
};
xhr.upload.addEventListener('progress', evt => {
if (evt.lengthComputable) {
this.set('progress', evt.loaded / evt.total);
}
}, false);
xhr.onerror = () => {
const {
__
} = shared_converse;
let message;
if (xhr.responseText) {
message = __('Sorry, could not succesfully upload your file. Your server’s response: "%1$s"', xhr.responseText);
} else {
message = __('Sorry, could not succesfully upload your file.');
}
this.save({
'type': 'error',
'upload': shared_converse.FAILURE,
'message': message,
'is_ephemeral': true
});
};
xhr.open('PUT', this.get('put'), true);
xhr.setRequestHeader('Content-type', this.file.type);
this.upload_metadata.headers?.forEach(h => xhr.setRequestHeader(h.name, h.value));
xhr.send(this.file);
}
};
/* harmony default export */ const message = (MessageMixin);
;// CONCATENATED MODULE: ./src/headless/plugins/chat/api.js
/* harmony default export */ const chat_api = ({
/**
* The "chats" namespace (used for one-on-one chats)
*
* @namespace api.chats
* @memberOf api
*/
chats: {
/**
* @method api.chats.create
* @param {string|string[]} jid|jids An jid or array of jids
* @param { object } [attrs] An object containing configuration attributes.
*/
async create(jids, attrs) {
if (typeof jids === 'string') {
if (attrs && !attrs?.fullname) {
const contact = await shared_api.contacts.get(jids);
attrs.fullname = contact?.attributes?.fullname;
}
const chatbox = shared_api.chats.get(jids, attrs, true);
if (!chatbox) {
log.error("Could not open chatbox for JID: " + jids);
return;
}
return chatbox;
}
if (Array.isArray(jids)) {
return Promise.all(jids.forEach(async jid => {
const contact = await shared_api.contacts.get(jids);
attrs.fullname = contact?.attributes?.fullname;
return shared_api.chats.get(jid, attrs, true).maybeShow();
}));
}
log.error("chats.create: You need to provide at least one JID");
return null;
},
/**
* Opens a new one-on-one chat.
*
* @method api.chats.open
* @param {String|string[]} name - e.g. 'buddy@example.com' or ['buddy1@example.com', 'buddy2@example.com']
* @param { Object } [attrs] - Attributes to be set on the _converse.ChatBox model.
* @param { Boolean } [attrs.minimized] - Should the chat be created in minimized state.
* @param { Boolean } [force=false] - By default, a minimized
* chat won't be maximized (in `overlayed` view mode) and in
* `fullscreen` view mode a newly opened chat won't replace
* another chat already in the foreground.
* Set `force` to `true` if you want to force the chat to be
* maximized or shown.
* @returns {Promise} Promise which resolves with the
* _converse.ChatBox representing the chat.
*
* @example
* // To open a single chat, provide the JID of the contact you're chatting with in that chat:
* converse.plugins.add('myplugin', {
* initialize: function() {
* const _converse = this._converse;
* // Note, buddy@example.org must be in your contacts roster!
* api.chats.open('buddy@example.com').then(chat => {
* // Now you can do something with the chat model
* });
* }
* });
*
* @example
* // To open an array of chats, provide an array of JIDs:
* converse.plugins.add('myplugin', {
* initialize: function () {
* const _converse = this._converse;
* // Note, these users must first be in your contacts roster!
* api.chats.open(['buddy1@example.com', 'buddy2@example.com']).then(chats => {
* // Now you can do something with the chat models
* });
* }
* });
*/
async open(jids, attrs, force) {
if (typeof jids === 'string') {
const chat = await shared_api.chats.get(jids, attrs, true);
if (chat) {
return chat.maybeShow(force);
}
return chat;
} else if (Array.isArray(jids)) {
return Promise.all(jids.map(j => shared_api.chats.get(j, attrs, true).then(c => c && c.maybeShow(force))).filter(c => c));
}
const err_msg = "chats.open: You need to provide at least one JID";
log.error(err_msg);
throw new Error(err_msg);
},
/**
* Retrieves a chat or all chats.
*
* @method api.chats.get
* @param {String|string[]} jids - e.g. 'buddy@example.com' or ['buddy1@example.com', 'buddy2@example.com']
* @param { Object } [attrs] - Attributes to be set on the _converse.ChatBox model.
* @param { Boolean } [create=false] - Whether the chat should be created if it's not found.
* @returns { Promise<_converse.ChatBox> }
*
* @example
* // To return a single chat, provide the JID of the contact you're chatting with in that chat:
* const model = await api.chats.get('buddy@example.com');
*
* @example
* // To return an array of chats, provide an array of JIDs:
* const models = await api.chats.get(['buddy1@example.com', 'buddy2@example.com']);
*
* @example
* // To return all open chats, call the method without any parameters::
* const models = await api.chats.get();
*
*/
async get(jids) {
let attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let create = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
await shared_api.waitUntil('chatBoxesFetched');
async function _get(jid) {
let model = await shared_api.chatboxes.get(jid);
if (!model && create) {
model = await shared_api.chatboxes.create(jid, attrs, shared_converse.ChatBox);
} else {
model = model && model.get('type') === shared_converse.PRIVATE_CHAT_TYPE ? model : null;
if (model && Object.keys(attrs).length) {
model.save(attrs);
}
}
return model;
}
if (jids === undefined) {
const chats = await shared_api.chatboxes.get();
return chats.filter(c => c.get('type') === shared_converse.PRIVATE_CHAT_TYPE);
} else if (typeof jids === 'string') {
return _get(jids);
}
return Promise.all(jids.map(jid => _get(jid)));
}
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/chat/utils.js
const {
Strophe: utils_Strophe,
u: chat_utils_u
} = converse.env;
function openChat(jid) {
if (!chat_utils_u.isValidJID(jid)) {
return log.warn(`Invalid JID "${jid}" provided in URL fragment`);
}
shared_api.chats.open(jid);
}
async function onClearSession() {
if (shouldClearCache()) {
await Promise.all(shared_converse.chatboxes.map(c => c.messages && c.messages.clearStore({
'silent': true
})));
const filter = o => o.get('type') !== shared_converse.CONTROLBOX_TYPE;
shared_converse.chatboxes.clearStore({
'silent': true
}, filter);
}
}
async function handleErrorMessage(stanza) {
const from_jid = utils_Strophe.getBareJidFromJid(stanza.getAttribute('from'));
if (chat_utils_u.isSameBareJID(from_jid, shared_converse.bare_jid)) {
return;
}
const chatbox = await shared_api.chatboxes.get(from_jid);
if (chatbox?.get('type') === shared_converse.PRIVATE_CHAT_TYPE) {
chatbox?.handleErrorMessageStanza(stanza);
}
}
function autoJoinChats() {
// Automatically join private chats, based on the
// "auto_join_private_chats" configuration setting.
shared_api.settings.get('auto_join_private_chats').forEach(jid => {
if (shared_converse.chatboxes.where({
'jid': jid
}).length) {
return;
}
if (typeof jid === 'string') {
shared_api.chats.open(jid);
} else {
log.error('Invalid jid criteria specified for "auto_join_private_chats"');
}
});
/**
* Triggered once any private chats have been automatically joined as
* specified by the `auto_join_private_chats` setting.
* See: https://conversejs.org/docs/html/configuration.html#auto-join-private-chats
* @event _converse#privateChatsAutoJoined
* @example _converse.api.listen.on('privateChatsAutoJoined', () => { ... });
* @example _converse.api.waitUntil('privateChatsAutoJoined').then(() => { ... });
*/
shared_api.trigger('privateChatsAutoJoined');
}
function registerMessageHandlers() {
shared_converse.connection.addHandler(stanza => {
if (['groupchat', 'error'].includes(stanza.getAttribute('type')) || isHeadline(stanza) || isServerMessage(stanza) || isArchived(stanza)) {
return true;
}
return shared_converse.handleMessageStanza(stanza) || true;
}, null, 'message');
shared_converse.connection.addHandler(stanza => handleErrorMessage(stanza) || true, null, 'message', 'error');
}
/**
* Handler method for all incoming single-user chat "message" stanzas.
* @param { MessageAttributes } attrs - The message attributes
*/
async function handleMessageStanza(stanza) {
stanza = stanza.tree?.() ?? stanza;
if (isServerMessage(stanza)) {
// Prosody sends headline messages with type `chat`, so we need to filter them out here.
const from = stanza.getAttribute('from');
return log.info(`handleMessageStanza: Ignoring incoming server message from JID: ${from}`);
}
let attrs;
try {
attrs = await parseMessage(stanza);
} catch (e) {
return log.error(e);
}
if (chat_utils_u.isErrorObject(attrs)) {
attrs.stanza && log.error(attrs.stanza);
return log.error(attrs.message);
}
// XXX: Need to take XEP-428 <fallback> into consideration
const has_body = !!(attrs.body || attrs.plaintext);
const chatbox = await shared_api.chats.get(attrs.contact_jid, {
'nickname': attrs.nick
}, has_body);
await chatbox?.queueMessage(attrs);
/**
* @typedef { Object } MessageData
* An object containing the original message stanza, as well as the
* parsed attributes.
* @property { Element } stanza
* @property { MessageAttributes } stanza
* @property { ChatBox } chatbox
*/
const data = {
stanza,
attrs,
chatbox
};
/**
* Triggered when a message stanza is been received and processed.
* @event _converse#message
* @type { object }
* @property { module:converse-chat~MessageData } data
*/
shared_api.trigger('message', data);
}
/**
* Ask the XMPP server to enable Message Carbons
* See [XEP-0280](https://xmpp.org/extensions/xep-0280.html#enabling)
* @param { Boolean } reconnecting
*/
async function enableCarbons() {
const domain = utils_Strophe.getDomainFromJid(shared_converse.bare_jid);
const supported = await shared_api.disco.supports(utils_Strophe.NS.CARBONS, domain);
if (!supported) {
log.warn("Not enabling carbons because it's not supported!");
return;
}
const iq = new utils_Strophe.Builder('iq', {
'from': shared_converse.connection.jid,
'type': 'set'
}).c('enable', {
xmlns: utils_Strophe.NS.CARBONS
});
const result = await shared_api.sendIQ(iq, null, false);
if (result === null) {
log.warn(`A timeout occurred while trying to enable carbons`);
} else if (chat_utils_u.isErrorStanza(result)) {
log.warn('An error occurred while trying to enable message carbons.');
log.error(result);
} else {
log.debug('Message carbons have been enabled.');
}
}
;// CONCATENATED MODULE: ./src/headless/plugins/chat/index.js
/**
* @copyright 2022, the Converse.js contributors
* @license Mozilla Public License (MPLv2)
*/
converse.plugins.add('converse-chat', {
dependencies: ['converse-chatboxes', 'converse-disco'],
initialize() {
// Configuration values for this plugin
// ====================================
// Refer to docs/source/configuration.rst for explanations of these
// configuration settings.
shared_api.settings.extend({
'allow_message_corrections': 'all',
'allow_message_retraction': 'all',
'allow_message_styling': true,
'auto_join_private_chats': [],
'clear_messages_on_reconnection': false,
'filter_by_resource': false,
'prune_messages_above': undefined,
'pruning_behavior': 'unscrolled',
'send_chat_markers': ['received', 'displayed', 'acknowledged'],
'send_chat_state_notifications': true
});
shared_converse.Message = model_with_contact.extend(message);
shared_converse.Messages = Collection.extend({
model: shared_converse.Message,
comparator: 'time'
});
Object.assign(shared_converse, {
ChatBox: model,
handleMessageStanza: handleMessageStanza
});
Object.assign(shared_api, chat_api);
shared_converse.router.route('converse/chat?jid=:jid', openChat);
shared_api.listen.on('chatBoxesFetched', autoJoinChats);
shared_api.listen.on('presencesInitialized', registerMessageHandlers);
shared_api.listen.on('clearSession', onClearSession);
shared_api.listen.on('connected', () => enableCarbons());
shared_api.listen.on('reconnected', () => enableCarbons());
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/disco/entity.js
const {
Strophe: entity_Strophe
} = converse.env;
/**
* @class
* @namespace _converse.DiscoEntity
* @memberOf _converse
*
* A Disco Entity is a JID addressable entity that can be queried for features.
*
* See XEP-0030: https://xmpp.org/extensions/xep-0030.html
*/
const DiscoEntity = Model.extend({
idAttribute: 'jid',
initialize(_, options) {
this.waitUntilFeaturesDiscovered = getOpenPromise();
this.dataforms = new Collection();
let id = `converse.dataforms-${this.get('jid')}`;
this.dataforms.browserStorage = shared_converse.createStore(id, 'session');
this.features = new Collection();
id = `converse.features-${this.get('jid')}`;
this.features.browserStorage = shared_converse.createStore(id, 'session');
this.listenTo(this.features, 'add', this.onFeatureAdded);
this.fields = new Collection();
id = `converse.fields-${this.get('jid')}`;
this.fields.browserStorage = shared_converse.createStore(id, 'session');
this.listenTo(this.fields, 'add', this.onFieldAdded);
this.identities = new Collection();
id = `converse.identities-${this.get('jid')}`;
this.identities.browserStorage = shared_converse.createStore(id, 'session');
this.fetchFeatures(options);
},
/**
* Returns a Promise which resolves with a map indicating
* whether a given identity is provided by this entity.
* @private
* @method _converse.DiscoEntity#getIdentity
* @param { String } category - The identity category
* @param { String } type - The identity type
*/
async getIdentity(category, type) {
await this.waitUntilFeaturesDiscovered;
return this.identities.findWhere({
'category': category,
'type': type
});
},
/**
* Returns a Promise which resolves with a map indicating
* whether a given feature is supported.
* @private
* @method _converse.DiscoEntity#getFeature
* @param { String } feature - The feature that might be supported.
*/
async getFeature(feature) {
await this.waitUntilFeaturesDiscovered;
if (this.features.findWhere({
'var': feature
})) {
return this;
}
},
onFeatureAdded(feature) {
feature.entity = this;
/**
* Triggered when Converse has learned of a service provided by the XMPP server.
* See XEP-0030.
* @event _converse#serviceDiscovered
* @type { Model }
* @example _converse.api.listen.on('featuresDiscovered', feature => { ... });
*/
shared_api.trigger('serviceDiscovered', feature);
},
onFieldAdded(field) {
field.entity = this;
/**
* Triggered when Converse has learned of a disco extension field.
* See XEP-0030.
* @event _converse#discoExtensionFieldDiscovered
* @example _converse.api.listen.on('discoExtensionFieldDiscovered', () => { ... });
*/
shared_api.trigger('discoExtensionFieldDiscovered', field);
},
async fetchFeatures(options) {
if (options.ignore_cache) {
this.queryInfo();
} else {
const store_id = this.features.browserStorage.name;
const result = await this.features.browserStorage.store.getItem(store_id);
if (result && result.length === 0 || result === null) {
this.queryInfo();
} else {
this.features.fetch({
add: true,
success: () => {
this.waitUntilFeaturesDiscovered.resolve(this);
this.trigger('featuresDiscovered');
}
});
this.identities.fetch({
add: true
});
}
}
},
async queryInfo() {
let stanza;
try {
stanza = await shared_api.disco.info(this.get('jid'), null);
} catch (iq) {
iq === null ? log.error(`Timeout for disco#info query for ${this.get('jid')}`) : log.error(iq);
this.waitUntilFeaturesDiscovered.resolve(this);
return;
}
this.onInfo(stanza);
},
onDiscoItems(stanza) {
sizzle_default()(`query[xmlns="${entity_Strophe.NS.DISCO_ITEMS}"] item`, stanza).forEach(item => {
if (item.getAttribute('node')) {
// XXX: Ignore nodes for now.
// See: https://xmpp.org/extensions/xep-0030.html#items-nodes
return;
}
const jid = item.getAttribute('jid');
const entity = shared_converse.disco_entities.get(jid);
if (entity) {
entity.set({
parent_jids: [this.get('jid')]
});
} else {
shared_api.disco.entities.create({
jid,
'parent_jids': [this.get('jid')],
'name': item.getAttribute('name')
});
}
});
},
async queryForItems() {
if (this.identities.where({
'category': 'server'
}).length === 0) {
// Don't fetch features and items if this is not a
// server or a conference component.
return;
}
const stanza = await shared_api.disco.items(this.get('jid'));
this.onDiscoItems(stanza);
},
async onInfo(stanza) {
Array.from(stanza.querySelectorAll('identity')).forEach(identity => {
this.identities.create({
'category': identity.getAttribute('category'),
'type': identity.getAttribute('type'),
'name': identity.getAttribute('name')
});
});
sizzle_default()(`x[type="result"][xmlns="${entity_Strophe.NS.XFORM}"]`, stanza).forEach(form => {
const data = {};
sizzle_default()('field', form).forEach(field => {
data[field.getAttribute('var')] = {
'value': field.querySelector('value')?.textContent,
'type': field.getAttribute('type')
};
});
this.dataforms.create(data);
});
if (stanza.querySelector(`feature[var="${entity_Strophe.NS.DISCO_ITEMS}"]`)) {
await this.queryForItems();
}
Array.from(stanza.querySelectorAll('feature')).forEach(feature => {
this.features.create({
'var': feature.getAttribute('var'),
'from': stanza.getAttribute('from')
});
});
// XEP-0128 Service Discovery Extensions
sizzle_default()('x[type="result"][xmlns="jabber:x:data"] field', stanza).forEach(field => {
this.fields.create({
'var': field.getAttribute('var'),
'value': field.querySelector('value')?.textContent,
'from': stanza.getAttribute('from')
});
});
this.waitUntilFeaturesDiscovered.resolve(this);
this.trigger('featuresDiscovered');
}
});
/* harmony default export */ const entity = (DiscoEntity);
;// CONCATENATED MODULE: ./src/headless/plugins/disco/entities.js
const DiscoEntities = Collection.extend({
model: entity,
fetchEntities() {
return new Promise((resolve, reject) => {
this.fetch({
add: true,
success: resolve,
error(_m, e) {
log.error(e);
reject(new Error("Could not fetch disco entities"));
}
});
});
}
});
/* harmony default export */ const entities = (DiscoEntities);
;// CONCATENATED MODULE: ./src/headless/plugins/disco/utils.js
const {
Strophe: disco_utils_Strophe,
$iq: utils_$iq
} = converse.env;
function onDiscoInfoRequest(stanza) {
const node = stanza.getElementsByTagName('query')[0].getAttribute('node');
const attrs = {
xmlns: disco_utils_Strophe.NS.DISCO_INFO
};
if (node) {
attrs.node = node;
}
const iqresult = utils_$iq({
'type': 'result',
'id': stanza.getAttribute('id')
});
const from = stanza.getAttribute('from');
if (from !== null) {
iqresult.attrs({
'to': from
});
}
iqresult.c('query', attrs);
shared_converse.disco._identities.forEach(identity => {
const attrs = {
'category': identity.category,
'type': identity.type
};
if (identity.name) {
attrs.name = identity.name;
}
if (identity.lang) {
attrs['xml:lang'] = identity.lang;
}
iqresult.c('identity', attrs).up();
});
shared_converse.disco._features.forEach(f => iqresult.c('feature', {
'var': f
}).up());
shared_api.send(iqresult.tree());
return true;
}
function addClientFeatures() {
// See https://xmpp.org/registrar/disco-categories.html
shared_api.disco.own.identities.add('client', 'web', 'Converse');
shared_api.disco.own.features.add(disco_utils_Strophe.NS.CHATSTATES);
shared_api.disco.own.features.add(disco_utils_Strophe.NS.DISCO_INFO);
shared_api.disco.own.features.add(disco_utils_Strophe.NS.ROSTERX); // Limited support
shared_api.disco.own.features.add(disco_utils_Strophe.NS.CARBONS);
/**
* Triggered in converse-disco once the core disco features of
* Converse have been added.
* @event _converse#addClientFeatures
* @example _converse.api.listen.on('addClientFeatures', () => { ... });
*/
shared_api.trigger('addClientFeatures');
return this;
}
async function initializeDisco() {
addClientFeatures();
shared_converse.connection.addHandler(stanza => onDiscoInfoRequest(stanza), disco_utils_Strophe.NS.DISCO_INFO, 'iq', 'get', null, null);
shared_converse.disco_entities = new shared_converse.DiscoEntities();
const id = `converse.disco-entities-${shared_converse.bare_jid}`;
shared_converse.disco_entities.browserStorage = shared_converse.createStore(id, 'session');
const collection = await shared_converse.disco_entities.fetchEntities();
if (collection.length === 0 || !collection.get(shared_converse.domain)) {
// If we don't have an entity for our own XMPP server, create one.
shared_api.disco.entities.create({
'jid': shared_converse.domain
}, {
'ignore_cache': true
});
}
/**
* Triggered once the `converse-disco` plugin has been initialized and the
* `_converse.disco_entities` collection will be available and populated with at
* least the service discovery features of the user's own server.
* @event _converse#discoInitialized
* @example _converse.api.listen.on('discoInitialized', () => { ... });
*/
shared_api.trigger('discoInitialized');
}
function initStreamFeatures() {
// Initialize the stream_features collection, and if we're
// re-attaching to a pre-existing BOSH session, we restore the
// features from cache.
// Otherwise the features will be created once we've received them
// from the server (see populateStreamFeatures).
if (!shared_converse.stream_features) {
const bare_jid = disco_utils_Strophe.getBareJidFromJid(shared_converse.jid);
const id = `converse.stream-features-${bare_jid}`;
shared_api.promises.add('streamFeaturesAdded');
shared_converse.stream_features = new Collection();
shared_converse.stream_features.browserStorage = shared_converse.createStore(id, "session");
}
}
function notifyStreamFeaturesAdded() {
/**
* Triggered as soon as the stream features are known.
* If you want to check whether a stream feature is supported before proceeding,
* then you'll first want to wait for this event.
* @event _converse#streamFeaturesAdded
* @example _converse.api.listen.on('streamFeaturesAdded', () => { ... });
*/
shared_api.trigger('streamFeaturesAdded');
}
function populateStreamFeatures() {
// Strophe.js sets the <stream:features> element on the
// Strophe.Connection instance (_converse.connection).
//
// Once this is we populate the _converse.stream_features collection
// and trigger streamFeaturesAdded.
initStreamFeatures();
Array.from(shared_converse.connection.features.childNodes).forEach(feature => {
shared_converse.stream_features.create({
'name': feature.nodeName,
'xmlns': feature.getAttribute('xmlns')
});
});
notifyStreamFeaturesAdded();
}
function utils_clearSession() {
shared_converse.disco_entities?.forEach(e => e.features.clearStore());
shared_converse.disco_entities?.forEach(e => e.identities.clearStore());
shared_converse.disco_entities?.forEach(e => e.dataforms.clearStore());
shared_converse.disco_entities?.forEach(e => e.fields.clearStore());
shared_converse.disco_entities?.clearStore();
delete shared_converse.disco_entities;
}
;// CONCATENATED MODULE: ./src/headless/plugins/disco/api.js
const {
Strophe: api_Strophe,
$iq: api_$iq
} = converse.env;
/* harmony default export */ const disco_api = ({
/**
* The XEP-0030 service discovery API
*
* This API lets you discover information about entities on the
* XMPP network.
*
* @namespace api.disco
* @memberOf api
*/
disco: {
/**
* @namespace api.disco.stream
* @memberOf api.disco
*/
stream: {
/**
* @method api.disco.stream.getFeature
* @param { String } name The feature name
* @param { String } xmlns The XML namespace
* @example _converse.api.disco.stream.getFeature('ver', 'urn:xmpp:features:rosterver')
*/
async getFeature(name, xmlns) {
await shared_api.waitUntil('streamFeaturesAdded');
if (!name || !xmlns) {
throw new Error("name and xmlns need to be provided when calling disco.stream.getFeature");
}
if (shared_converse.stream_features === undefined && !shared_api.connection.connected()) {
// Happens during tests when disco lookups happen asynchronously after teardown.
const msg = `Tried to get feature ${name} ${xmlns} but _converse.stream_features has been torn down`;
log.warn(msg);
return;
}
return shared_converse.stream_features.findWhere({
'name': name,
'xmlns': xmlns
});
}
},
/**
* @namespace api.disco.own
* @memberOf api.disco
*/
own: {
/**
* @namespace api.disco.own.identities
* @memberOf api.disco.own
*/
identities: {
/**
* Lets you add new identities for this client (i.e. instance of Converse)
* @method api.disco.own.identities.add
*
* @param { String } category - server, client, gateway, directory, etc.
* @param { String } type - phone, pc, web, etc.
* @param { String } name - "Converse"
* @param { String } lang - en, el, de, etc.
*
* @example _converse.api.disco.own.identities.clear();
*/
add(category, type, name, lang) {
for (var i = 0; i < shared_converse.disco._identities.length; i++) {
if (shared_converse.disco._identities[i].category == category && shared_converse.disco._identities[i].type == type && shared_converse.disco._identities[i].name == name && shared_converse.disco._identities[i].lang == lang) {
return false;
}
}
shared_converse.disco._identities.push({
category: category,
type: type,
name: name,
lang: lang
});
},
/**
* Clears all previously registered identities.
* @method api.disco.own.identities.clear
* @example _converse.api.disco.own.identities.clear();
*/
clear() {
shared_converse.disco._identities = [];
},
/**
* Returns all of the identities registered for this client
* (i.e. instance of Converse).
* @method api.disco.identities.get
* @example const identities = api.disco.own.identities.get();
*/
get() {
return shared_converse.disco._identities;
}
},
/**
* @namespace api.disco.own.features
* @memberOf api.disco.own
*/
features: {
/**
* Lets you register new disco features for this client (i.e. instance of Converse)
* @method api.disco.own.features.add
* @param { String } name - e.g. http://jabber.org/protocol/caps
* @example _converse.api.disco.own.features.add("http://jabber.org/protocol/caps");
*/
add(name) {
for (var i = 0; i < shared_converse.disco._features.length; i++) {
if (shared_converse.disco._features[i] == name) {
return false;
}
}
shared_converse.disco._features.push(name);
},
/**
* Clears all previously registered features.
* @method api.disco.own.features.clear
* @example _converse.api.disco.own.features.clear();
*/
clear() {
shared_converse.disco._features = [];
},
/**
* Returns all of the features registered for this client (i.e. instance of Converse).
* @method api.disco.own.features.get
* @example const features = api.disco.own.features.get();
*/
get() {
return shared_converse.disco._features;
}
}
},
/**
* Query for information about an XMPP entity
*
* @method api.disco.info
* @param { string } jid The Jabber ID of the entity to query
* @param { string } [node] A specific node identifier associated with the JID
* @returns {promise} Promise which resolves once we have a result from the server.
*/
info(jid, node) {
const attrs = {
xmlns: api_Strophe.NS.DISCO_INFO
};
if (node) {
attrs.node = node;
}
const info = api_$iq({
'from': shared_converse.connection.jid,
'to': jid,
'type': 'get'
}).c('query', attrs);
return shared_api.sendIQ(info);
},
/**
* Query for items associated with an XMPP entity
*
* @method api.disco.items
* @param { string } jid The Jabber ID of the entity to query for items
* @param { string } [node] A specific node identifier associated with the JID
* @returns {promise} Promise which resolves once we have a result from the server.
*/
items(jid, node) {
const attrs = {
'xmlns': api_Strophe.NS.DISCO_ITEMS
};
if (node) {
attrs.node = node;
}
return shared_api.sendIQ(api_$iq({
'from': shared_converse.connection.jid,
'to': jid,
'type': 'get'
}).c('query', attrs));
},
/**
* Namespace for methods associated with disco entities
*
* @namespace api.disco.entities
* @memberOf api.disco
*/
entities: {
/**
* Get the corresponding `DiscoEntity` instance.
*
* @method api.disco.entities.get
* @param { string } jid The Jabber ID of the entity
* @param { boolean } [create] Whether the entity should be created if it doesn't exist.
* @example _converse.api.disco.entities.get(jid);
*/
async get(jid) {
let create = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
await shared_api.waitUntil('discoInitialized');
if (!jid) {
return shared_converse.disco_entities;
}
if (shared_converse.disco_entities === undefined) {
// Happens during tests when disco lookups happen asynchronously after teardown.
log.warn(`Tried to look up entity ${jid} but _converse.disco_entities has been torn down`);
return;
}
const entity = shared_converse.disco_entities.get(jid);
if (entity || !create) {
return entity;
}
return shared_api.disco.entities.create({
jid
});
},
/**
* Return any disco items advertised on this entity
*
* @method api.disco.entities.items
* @param { string } jid The Jabber ID of the entity for which we want to fetch items
* @example api.disco.entities.items(jid);
*/
items(jid) {
return shared_converse.disco_entities.filter(e => e.get('parent_jids')?.includes(jid));
},
/**
* Create a new disco entity. It's identity and features
* will automatically be fetched from cache or from the
* XMPP server.
*
* Fetching from cache can be disabled by passing in
* `ignore_cache: true` in the options parameter.
*
* @method api.disco.entities.create
* @param { object } data
* @param { string } data.jid - The Jabber ID of the entity
* @param { string } data.parent_jid - The Jabber ID of the parent entity
* @param { string } data.name
* @param { object } [options] - Additional options
* @param { boolean } [options.ignore_cache]
* If true, fetch all features from the XMPP server instead of restoring them from cache
* @example _converse.api.disco.entities.create({ jid }, {'ignore_cache': true});
*/
create(data, options) {
return shared_converse.disco_entities.create(data, options);
}
},
/**
* @namespace api.disco.features
* @memberOf api.disco
*/
features: {
/**
* Return a given feature of a disco entity
*
* @method api.disco.features.get
* @param { string } feature The feature that might be
* supported. In the XML stanza, this is the `var`
* attribute of the `<feature>` element. For
* example: `http://jabber.org/protocol/muc`
* @param { string } jid The JID of the entity
* (and its associated items) which should be queried
* @returns {promise} A promise which resolves with a list containing
* _converse.Entity instances representing the entity
* itself or those items associated with the entity if
* they support the given feature.
* @example
* api.disco.features.get(Strophe.NS.MAM, _converse.bare_jid);
*/
async get(feature, jid) {
if (!jid) throw new TypeError('You need to provide an entity JID');
const entity = await shared_api.disco.entities.get(jid, true);
if (shared_converse.disco_entities === undefined && !shared_api.connection.connected()) {
// Happens during tests when disco lookups happen asynchronously after teardown.
log.warn(`Tried to get feature ${feature} for ${jid} but _converse.disco_entities has been torn down`);
return [];
}
const promises = [entity.getFeature(feature), ...shared_api.disco.entities.items(jid).map(i => i.getFeature(feature))];
const result = await Promise.all(promises);
return result.filter(lodash_es_isObject);
},
/**
* Returns true if an entity with the given JID, or if one of its
* associated items, supports a given feature.
*
* @method api.disco.features.has
* @param { string } feature The feature that might be
* supported. In the XML stanza, this is the `var`
* attribute of the `<feature>` element. For
* example: `http://jabber.org/protocol/muc`
* @param { string } jid The JID of the entity
* (and its associated items) which should be queried
* @returns {Promise} A promise which resolves with a boolean
* @example
* api.disco.features.has(Strophe.NS.MAM, _converse.bare_jid);
*/
async has(feature, jid) {
if (!jid) throw new TypeError('You need to provide an entity JID');
const entity = await shared_api.disco.entities.get(jid, true);
if (shared_converse.disco_entities === undefined && !shared_api.connection.connected()) {
// Happens during tests when disco lookups happen asynchronously after teardown.
log.warn(`Tried to check if ${jid} supports feature ${feature}`);
return false;
}
if (await entity.getFeature(feature)) {
return true;
}
const result = await Promise.all(shared_api.disco.entities.items(jid).map(i => i.getFeature(feature)));
return result.map(lodash_es_isObject).includes(true);
}
},
/**
* Used to determine whether an entity supports a given feature.
*
* @method api.disco.supports
* @param { string } feature The feature that might be
* supported. In the XML stanza, this is the `var`
* attribute of the `<feature>` element. For
* example: `http://jabber.org/protocol/muc`
* @param { string } jid The JID of the entity
* (and its associated items) which should be queried
* @returns {promise} A promise which resolves with `true` or `false`.
* @example
* if (await api.disco.supports(Strophe.NS.MAM, _converse.bare_jid)) {
* // The feature is supported
* } else {
* // The feature is not supported
* }
*/
supports(feature, jid) {
return shared_api.disco.features.has(feature, jid);
},
/**
* Refresh the features, fields and identities associated with a
* disco entity by refetching them from the server
* @method api.disco.refresh
* @param { string } jid The JID of the entity whose features are refreshed.
* @returns {promise} A promise which resolves once the features have been refreshed
* @example
* await api.disco.refresh('room@conference.example.org');
*/
async refresh(jid) {
if (!jid) {
throw new TypeError('api.disco.refresh: You need to provide an entity JID');
}
await shared_api.waitUntil('discoInitialized');
let entity = await shared_api.disco.entities.get(jid);
if (entity) {
entity.features.reset();
entity.fields.reset();
entity.identities.reset();
if (!entity.waitUntilFeaturesDiscovered.isPending) {
entity.waitUntilFeaturesDiscovered = getOpenPromise();
}
entity.queryInfo();
} else {
// Create it if it doesn't exist
entity = await shared_api.disco.entities.create({
jid
}, {
'ignore_cache': true
});
}
return entity.waitUntilFeaturesDiscovered;
},
/**
* @deprecated Use {@link api.disco.refresh} instead.
* @method api.disco.refreshFeatures
*/
refreshFeatures(jid) {
return shared_api.refresh(jid);
},
/**
* Return all the features associated with a disco entity
*
* @method api.disco.getFeatures
* @param { string } jid The JID of the entity whose features are returned.
* @returns {promise} A promise which resolves with the returned features
* @example
* const features = await api.disco.getFeatures('room@conference.example.org');
*/
async getFeatures(jid) {
if (!jid) {
throw new TypeError('api.disco.getFeatures: You need to provide an entity JID');
}
await shared_api.waitUntil('discoInitialized');
let entity = await shared_api.disco.entities.get(jid, true);
entity = await entity.waitUntilFeaturesDiscovered;
return entity.features;
},
/**
* Return all the service discovery extensions fields
* associated with an entity.
*
* See [XEP-0129: Service Discovery Extensions](https://xmpp.org/extensions/xep-0128.html)
*
* @method api.disco.getFields
* @param { string } jid The JID of the entity whose fields are returned.
* @example
* const fields = await api.disco.getFields('room@conference.example.org');
*/
async getFields(jid) {
if (!jid) {
throw new TypeError('api.disco.getFields: You need to provide an entity JID');
}
await shared_api.waitUntil('discoInitialized');
let entity = await shared_api.disco.entities.get(jid, true);
entity = await entity.waitUntilFeaturesDiscovered;
return entity.fields;
},
/**
* Get the identity (with the given category and type) for a given disco entity.
*
* For example, when determining support for PEP (personal eventing protocol), you
* want to know whether the user's own JID has an identity with
* `category='pubsub'` and `type='pep'` as explained in this section of
* XEP-0163: https://xmpp.org/extensions/xep-0163.html#support
*
* @method api.disco.getIdentity
* @param { string } The identity category.
* In the XML stanza, this is the `category`
* attribute of the `<identity>` element.
* For example: 'pubsub'
* @param { string } type The identity type.
* In the XML stanza, this is the `type`
* attribute of the `<identity>` element.
* For example: 'pep'
* @param { string } jid The JID of the entity which might have the identity
* @returns {promise} A promise which resolves with a map indicating
* whether an identity with a given type is provided by the entity.
* @example
* api.disco.getIdentity('pubsub', 'pep', _converse.bare_jid).then(
* function (identity) {
* if (identity) {
* // The entity DOES have this identity
* } else {
* // The entity DOES NOT have this identity
* }
* }
* ).catch(e => log.error(e));
*/
async getIdentity(category, type, jid) {
const e = await shared_api.disco.entities.get(jid, true);
if (e === undefined && !shared_api.connection.connected()) {
// Happens during tests when disco lookups happen asynchronously after teardown.
const msg = `Tried to look up category ${category} for ${jid} but _converse.disco_entities has been torn down`;
log.warn(msg);
return;
}
return e.getIdentity(category, type);
}
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/disco/index.js
/**
* @copyright The Converse.js contributors
* @license Mozilla Public License (MPLv2)
* @description Converse plugin which add support for XEP-0030: Service Discovery
*/
const {
Strophe: disco_Strophe
} = converse.env;
converse.plugins.add('converse-disco', {
initialize() {
Object.assign(shared_api, disco_api);
shared_api.promises.add('discoInitialized');
shared_api.promises.add('streamFeaturesAdded');
shared_converse.DiscoEntity = entity;
shared_converse.DiscoEntities = entities;
shared_converse.disco = {
_identities: [],
_features: []
};
shared_api.listen.on('userSessionInitialized', async () => {
initStreamFeatures();
if (shared_converse.connfeedback.get('connection_status') === disco_Strophe.Status.ATTACHED) {
// When re-attaching to a BOSH session, we fetch the stream features from the cache.
await new Promise((success, error) => shared_converse.stream_features.fetch({
success,
error
}));
notifyStreamFeaturesAdded();
}
});
shared_api.listen.on('beforeResourceBinding', populateStreamFeatures);
shared_api.listen.on('reconnected', initializeDisco);
shared_api.listen.on('connected', initializeDisco);
shared_api.listen.on('beforeTearDown', async () => {
shared_api.promises.add('streamFeaturesAdded');
if (shared_converse.stream_features) {
await shared_converse.stream_features.clearStore();
delete shared_converse.stream_features;
}
});
// All disco entities stored in sessionStorage and are refetched
// upon login or reconnection and then stored with new ids, so to
// avoid sessionStorage filling up, we remove them.
shared_api.listen.on('will-reconnect', utils_clearSession);
shared_api.listen.on('clearSession', utils_clearSession);
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/emoji/regexes.js
const ASCII_REGEX = '(\\*\\\\0\\/\\*|\\*\\\\O\\/\\*|\\-___\\-|\\:\'\\-\\)|\'\\:\\-\\)|\'\\:\\-D|\\>\\:\\-\\)|>\\:\\-\\)|\'\\:\\-\\(|\\>\\:\\-\\(|>\\:\\-\\(|\\:\'\\-\\(|O\\:\\-\\)|0\\:\\-3|0\\:\\-\\)|0;\\^\\)|O;\\-\\)|0;\\-\\)|O\\:\\-3|\\-__\\-|\\:\\-Þ|\\:\\-Þ|\\<\\/3|<\\/3|\\:\'\\)|\\:\\-D|\'\\:\\)|\'\\=\\)|\'\\:D|\'\\=D|\\>\\:\\)|>\\:\\)|\\>;\\)|>;\\)|\\>\\=\\)|>\\=\\)|;\\-\\)|\\*\\-\\)|;\\-\\]|;\\^\\)|\'\\:\\(|\'\\=\\(|\\:\\-\\*|\\:\\^\\*|\\>\\:P|>\\:P|X\\-P|\\>\\:\\[|>\\:\\[|\\:\\-\\(|\\:\\-\\[|\\>\\:\\(|>\\:\\(|\\:\'\\(|;\\-\\(|\\>\\.\\<|>\\.<|#\\-\\)|%\\-\\)|X\\-\\)|\\\\0\\/|\\\\O\\/|0\\:3|0\\:\\)|O\\:\\)|O\\=\\)|O\\:3|B\\-\\)|8\\-\\)|B\\-D|8\\-D|\\-_\\-|\\>\\:\\\\|>\\:\\\\|\\>\\:\\/|>\\:\\/|\\:\\-\\/|\\:\\-\\.|\\:\\-P|\\:Þ|\\:Þ|\\:\\-b|\\:\\-O|O_O|\\>\\:O|>\\:O|\\:\\-X|\\:\\-#|\\:\\-\\)|\\(y\\)|\\<3|<3|\\:D|\\=D|;\\)|\\*\\)|;\\]|;D|\\:\\*|\\=\\*|\\:\\(|\\:\\[|\\=\\(|\\:@|;\\(|D\\:|\\:\\$|\\=\\$|#\\)|%\\)|X\\)|B\\)|8\\)|\\:\\/|\\:\\\\|\\=\\/|\\=\\\\|\\:L|\\=L|\\:P|\\=P|\\:b|\\:O|\\:X|\\:#|\\=X|\\=#|\\:\\)|\\=\\]|\\=\\)|\\:\\])';
const ASCII_REPLACE_REGEX = new RegExp("<object[^>]*>.*?<\/object>|<span[^>]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|((\\s|^)" + ASCII_REGEX + "(?=\\s|$|[!,.?]))", "gi");
const CODEPOINTS_REGEX = /(?:\ud83d\udc68\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc68\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc68\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\u200d\ud83e\udd1d\u200d\ud83e\uddd1|\ud83d\udc6b\ud83c[\udffb-\udfff]|\ud83d\udc6c\ud83c[\udffb-\udfff]|\ud83d\udc6d\ud83c[\udffb-\udfff]|\ud83d[\udc6b-\udc6d])|(?:\ud83d[\udc68\udc69]|\ud83e\uddd1)(?:\ud83c[\udffb-\udfff])?\u200d(?:\u2695\ufe0f|\u2696\ufe0f|\u2708\ufe0f|\ud83c[\udf3e\udf73\udf93\udfa4\udfa8\udfeb\udfed]|\ud83d[\udcbb\udcbc\udd27\udd2c\ude80\ude92]|\ud83e[\uddaf-\uddb3\uddbc\uddbd])|(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75]|\u26f9)((?:\ud83c[\udffb-\udfff]|\ufe0f)\u200d[\u2640\u2642]\ufe0f)|(?:\ud83c[\udfc3\udfc4\udfca]|\ud83d[\udc6e\udc71\udc73\udc77\udc81\udc82\udc86\udc87\ude45-\ude47\ude4b\ude4d\ude4e\udea3\udeb4-\udeb6]|\ud83e[\udd26\udd35\udd37-\udd39\udd3d\udd3e\uddb8\uddb9\uddcd-\uddcf\uddd6-\udddd])(?:\ud83c[\udffb-\udfff])?\u200d[\u2640\u2642]\ufe0f|(?:\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f|\ud83c\udff3\ufe0f\u200d\ud83c\udf08|\ud83c\udff4\u200d\u2620\ufe0f|\ud83d\udc15\u200d\ud83e\uddba|\ud83d\udc41\u200d\ud83d\udde8|\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc6f\u200d\u2640\ufe0f|\ud83d\udc6f\u200d\u2642\ufe0f|\ud83e\udd3c\u200d\u2640\ufe0f|\ud83e\udd3c\u200d\u2642\ufe0f|\ud83e\uddde\u200d\u2640\ufe0f|\ud83e\uddde\u200d\u2642\ufe0f|\ud83e\udddf\u200d\u2640\ufe0f|\ud83e\udddf\u200d\u2642\ufe0f)|[#*0-9]\ufe0f?\u20e3|(?:[©®\u2122\u265f]\ufe0f)|(?:\ud83c[\udc04\udd70\udd71\udd7e\udd7f\ude02\ude1a\ude2f\ude37\udf21\udf24-\udf2c\udf36\udf7d\udf96\udf97\udf99-\udf9b\udf9e\udf9f\udfcd\udfce\udfd4-\udfdf\udff3\udff5\udff7]|\ud83d[\udc3f\udc41\udcfd\udd49\udd4a\udd6f\udd70\udd73\udd76-\udd79\udd87\udd8a-\udd8d\udda5\udda8\uddb1\uddb2\uddbc\uddc2-\uddc4\uddd1-\uddd3\udddc-\uddde\udde1\udde3\udde8\uddef\uddf3\uddfa\udecb\udecd-\udecf\udee0-\udee5\udee9\udef0\udef3]|[\u203c\u2049\u2139\u2194-\u2199\u21a9\u21aa\u231a\u231b\u2328\u23cf\u23ed-\u23ef\u23f1\u23f2\u23f8-\u23fa\u24c2\u25aa\u25ab\u25b6\u25c0\u25fb-\u25fe\u2600-\u2604\u260e\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262a\u262e\u262f\u2638-\u263a\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267b\u267f\u2692-\u2697\u2699\u269b\u269c\u26a0\u26a1\u26a7\u26aa\u26ab\u26b0\u26b1\u26bd\u26be\u26c4\u26c5\u26c8\u26cf\u26d1\u26d3\u26d4\u26e9\u26ea\u26f0-\u26f5\u26f8\u26fa\u26fd\u2702\u2708\u2709\u270f\u2712\u2714\u2716\u271d\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u2764\u27a1\u2934\u2935\u2b05-\u2b07\u2b1b\u2b1c\u2b50\u2b55\u3030\u303d\u3297\u3299])(?:\ufe0f|(?!\ufe0e))|(?:(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75\udd90]|[\u261d\u26f7\u26f9\u270c\u270d])(?:\ufe0f|(?!\ufe0e))|(?:\ud83c[\udf85\udfc2-\udfc4\udfc7\udfca]|\ud83d[\udc42\udc43\udc46-\udc50\udc66-\udc69\udc6e\udc70-\udc78\udc7c\udc81-\udc83\udc85-\udc87\udcaa\udd7a\udd95\udd96\ude45-\ude47\ude4b-\ude4f\udea3\udeb4-\udeb6\udec0\udecc]|\ud83e[\udd0f\udd18-\udd1c\udd1e\udd1f\udd26\udd30-\udd39\udd3d\udd3e\uddb5\uddb6\uddb8\uddb9\uddbb\uddcd-\uddcf\uddd1-\udddd]|[\u270a\u270b]))(?:\ud83c[\udffb-\udfff])?|(?:\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc73\udb40\udc63\udb40\udc74\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc77\udb40\udc6c\udb40\udc73\udb40\udc7f|\ud83c\udde6\ud83c[\udde8-\uddec\uddee\uddf1\uddf2\uddf4\uddf6-\uddfa\uddfc\uddfd\uddff]|\ud83c\udde7\ud83c[\udde6\udde7\udde9-\uddef\uddf1-\uddf4\uddf6-\uddf9\uddfb\uddfc\uddfe\uddff]|\ud83c\udde8\ud83c[\udde6\udde8\udde9\uddeb-\uddee\uddf0-\uddf5\uddf7\uddfa-\uddff]|\ud83c\udde9\ud83c[\uddea\uddec\uddef\uddf0\uddf2\uddf4\uddff]|\ud83c\uddea\ud83c[\udde6\udde8\uddea\uddec\udded\uddf7-\uddfa]|\ud83c\uddeb\ud83c[\uddee-\uddf0\uddf2\uddf4\uddf7]|\ud83c\uddec\ud83c[\udde6\udde7\udde9-\uddee\uddf1-\uddf3\uddf5-\uddfa\uddfc\uddfe]|\ud83c\udded\ud83c[\uddf0\uddf2\uddf3\uddf7\uddf9\uddfa]|\ud83c\uddee\ud83c[\udde8-\uddea\uddf1-\uddf4\uddf6-\uddf9]|\ud83c\uddef\ud83c[\uddea\uddf2\uddf4\uddf5]|\ud83c\uddf0\ud83c[\uddea\uddec-\uddee\uddf2\uddf3\uddf5\uddf7\uddfc\uddfe\uddff]|\ud83c\uddf1\ud83c[\udde6-\udde8\uddee\uddf0\uddf7-\uddfb\uddfe]|\ud83c\uddf2\ud83c[\udde6\udde8-\udded\uddf0-\uddff]|\ud83c\uddf3\ud83c[\udde6\udde8\uddea-\uddec\uddee\uddf1\uddf4\uddf5\uddf7\uddfa\uddff]|\ud83c\uddf4\ud83c\uddf2|\ud83c\uddf5\ud83c[\udde6\uddea-\udded\uddf0-\uddf3\uddf7-\uddf9\uddfc\uddfe]|\ud83c\uddf6\ud83c\udde6|\ud83c\uddf7\ud83c[\uddea\uddf4\uddf8\uddfa\uddfc]|\ud83c\uddf8\ud83c[\udde6-\uddea\uddec-\uddf4\uddf7-\uddf9\uddfb\uddfd-\uddff]|\ud83c\uddf9\ud83c[\udde6\udde8\udde9\uddeb-\udded\uddef-\uddf4\uddf7\uddf9\uddfb\uddfc\uddff]|\ud83c\uddfa\ud83c[\udde6\uddec\uddf2\uddf3\uddf8\uddfe\uddff]|\ud83c\uddfb\ud83c[\udde6\udde8\uddea\uddec\uddee\uddf3\uddfa]|\ud83c\uddfc\ud83c[\uddeb\uddf8]|\ud83c\uddfd\ud83c\uddf0|\ud83c\uddfe\ud83c[\uddea\uddf9]|\ud83c\uddff\ud83c[\udde6\uddf2\uddfc]|\ud83c[\udccf\udd8e\udd91-\udd9a\udde6-\uddff\ude01\ude32-\ude36\ude38-\ude3a\ude50\ude51\udf00-\udf20\udf2d-\udf35\udf37-\udf7c\udf7e-\udf84\udf86-\udf93\udfa0-\udfc1\udfc5\udfc6\udfc8\udfc9\udfcf-\udfd3\udfe0-\udff0\udff4\udff8-\udfff]|\ud83d[\udc00-\udc3e\udc40\udc44\udc45\udc51-\udc65\udc6a\udc6f\udc79-\udc7b\udc7d-\udc80\udc84\udc88-\udca9\udcab-\udcfc\udcff-\udd3d\udd4b-\udd4e\udd50-\udd67\udda4\uddfb-\ude44\ude48-\ude4a\ude80-\udea2\udea4-\udeb3\udeb7-\udebf\udec1-\udec5\uded0-\uded2\uded5\udeeb\udeec\udef4-\udefa\udfe0-\udfeb]|\ud83e[\udd0d\udd0e\udd10-\udd17\udd1d\udd20-\udd25\udd27-\udd2f\udd3a\udd3c\udd3f-\udd45\udd47-\udd71\udd73-\udd76\udd7a-\udda2\udda5-\uddaa\uddae-\uddb4\uddb7\uddba\uddbc-\uddca\uddd0\uddde-\uddff\ude70-\ude73\ude78-\ude7a\ude80-\ude82\ude90-\ude95]|[\u23e9-\u23ec\u23f0\u23f3\u267e\u26ce\u2705\u2728\u274c\u274e\u2753-\u2755\u2795-\u2797\u27b0\u27bf\ue50a])|\ufe0f/g;
;// CONCATENATED MODULE: ./src/headless/plugins/emoji/utils.js
const {
u: emoji_utils_u
} = converse.env;
// Closured cache
const emojis_by_attribute = {};
const ASCII_LIST = {
'*\\0/*': '1f646',
'*\\O/*': '1f646',
'-___-': '1f611',
':\'-)': '1f602',
'\':-)': '1f605',
'\':-D': '1f605',
'>:-)': '1f606',
'\':-(': '1f613',
'>:-(': '1f620',
':\'-(': '1f622',
'O:-)': '1f607',
'0:-3': '1f607',
'0:-)': '1f607',
'0;^)': '1f607',
'O;-)': '1f607',
'0;-)': '1f607',
'O:-3': '1f607',
'-__-': '1f611',
':-Þ': '1f61b',
'</3': '1f494',
':\')': '1f602',
':-D': '1f603',
'\':)': '1f605',
'\'=)': '1f605',
'\':D': '1f605',
'\'=D': '1f605',
'>:)': '1f606',
'>;)': '1f606',
'>=)': '1f606',
';-)': '1f609',
'*-)': '1f609',
';-]': '1f609',
';^)': '1f609',
'\':(': '1f613',
'\'=(': '1f613',
':-*': '1f618',
':^*': '1f618',
'>:P': '1f61c',
'X-P': '1f61c',
'>:[': '1f61e',
':-(': '1f61e',
':-[': '1f61e',
'>:(': '1f620',
':\'(': '1f622',
';-(': '1f622',
'>.<': '1f623',
'#-)': '1f635',
'%-)': '1f635',
'X-)': '1f635',
'\\0/': '1f646',
'\\O/': '1f646',
'0:3': '1f607',
'0:)': '1f607',
'O:)': '1f607',
'O=)': '1f607',
'O:3': '1f607',
'B-)': '1f60e',
'8-)': '1f60e',
'B-D': '1f60e',
'8-D': '1f60e',
'-_-': '1f611',
'>:\\': '1f615',
'>:/': '1f615',
':-/': '1f615',
':-.': '1f615',
':-P': '1f61b',
':Þ': '1f61b',
':-b': '1f61b',
':-O': '1f62e',
'O_O': '1f62e',
'>:O': '1f62e',
':-X': '1f636',
':-#': '1f636',
':-)': '1f642',
'(y)': '1f44d',
'<3': '2764',
':D': '1f603',
'=D': '1f603',
';)': '1f609',
'*)': '1f609',
';]': '1f609',
';D': '1f609',
':*': '1f618',
'=*': '1f618',
':(': '1f61e',
':[': '1f61e',
'=(': '1f61e',
':@': '1f620',
';(': '1f622',
'D:': '1f628',
':$': '1f633',
'=$': '1f633',
'#)': '1f635',
'%)': '1f635',
'X)': '1f635',
'B)': '1f60e',
'8)': '1f60e',
':/': '1f615',
':\\': '1f615',
'=/': '1f615',
'=\\': '1f615',
':L': '1f615',
'=L': '1f615',
':P': '1f61b',
'=P': '1f61b',
':b': '1f61b',
':O': '1f62e',
':X': '1f636',
':#': '1f636',
'=X': '1f636',
'=#': '1f636',
':)': '1f642',
'=]': '1f642',
'=)': '1f642',
':]': '1f642'
};
function toCodePoint(unicode_surrogates) {
const r = [];
let p = 0;
let i = 0;
while (i < unicode_surrogates.length) {
const c = unicode_surrogates.charCodeAt(i++);
if (p) {
r.push((0x10000 + (p - 0xD800 << 10) + (c - 0xDC00)).toString(16));
p = 0;
} else if (0xD800 <= c && c <= 0xDBFF) {
p = c;
} else {
r.push(c.toString(16));
}
}
return r.join('-');
}
function fromCodePoint(codepoint) {
let code = typeof codepoint === 'string' ? parseInt(codepoint, 16) : codepoint;
if (code < 0x10000) {
return String.fromCharCode(code);
}
code -= 0x10000;
return String.fromCharCode(0xD800 + (code >> 10), 0xDC00 + (code & 0x3FF));
}
function convert(unicode) {
// Converts unicode code points and code pairs to their respective characters
if (unicode.indexOf("-") > -1) {
const parts = [],
s = unicode.split('-');
for (let i = 0; i < s.length; i++) {
let part = parseInt(s[i], 16);
if (part >= 0x10000 && part <= 0x10FFFF) {
const hi = Math.floor((part - 0x10000) / 0x400) + 0xD800;
const lo = (part - 0x10000) % 0x400 + 0xDC00;
part = String.fromCharCode(hi) + String.fromCharCode(lo);
} else {
part = String.fromCharCode(part);
}
parts.push(part);
}
return parts.join('');
}
return fromCodePoint(unicode);
}
function convertASCII2Emoji(str) {
// Replace ASCII smileys
return str.replace(ASCII_REPLACE_REGEX, (entire, _, m2, m3) => {
if (typeof m3 === 'undefined' || m3 === '' || !(emoji_utils_u.unescapeHTML(m3) in ASCII_LIST)) {
// if the ascii doesnt exist just return the entire match
return entire;
}
m3 = emoji_utils_u.unescapeHTML(m3);
const unicode = ASCII_LIST[m3].toUpperCase();
return m2 + convert(unicode);
});
}
function getShortnameReferences(text) {
if (!converse.emojis.initialized) {
throw new Error('getShortnameReferences called before emojis are initialized. ' + 'To avoid this problem, first await the converse.emojis.initialized_promise');
}
const references = [...text.matchAll(converse.emojis.shortnames_regex)].filter(ref => ref[0].length > 0);
return references.map(ref => {
const cp = converse.emojis.by_sn[ref[0]].cp;
return {
cp,
'begin': ref.index,
'end': ref.index + ref[0].length,
'shortname': ref[0],
'emoji': cp ? convert(cp) : null
};
});
}
function parseStringForEmojis(str, callback) {
const UFE0Fg = /\uFE0F/g;
const U200D = String.fromCharCode(0x200D);
return String(str).replace(CODEPOINTS_REGEX, (emoji, _, offset) => {
const icon_id = toCodePoint(emoji.indexOf(U200D) < 0 ? emoji.replace(UFE0Fg, '') : emoji);
if (icon_id) callback(icon_id, emoji, offset);
});
}
function getCodePointReferences(text) {
const references = [];
parseStringForEmojis(text, (icon_id, emoji, offset) => {
references.push({
'begin': offset,
'cp': icon_id,
'emoji': emoji,
'end': offset + emoji.length,
'shortname': getEmojisByAtrribute('cp')[icon_id]?.sn || ''
});
});
return references;
}
function addEmojisMarkup(text) {
let list = [text];
[...getShortnameReferences(text), ...getCodePointReferences(text)].sort((a, b) => b.begin - a.begin).forEach(ref => {
const text = list.shift();
const emoji = ref.emoji || ref.shortname;
list = [text.slice(0, ref.begin) + emoji + text.slice(ref.end), ...list];
});
return list;
}
/**
* Replaces all shortnames in the passed in string with their
* unicode (emoji) representation.
* @namespace u
* @method u.shortnamesToUnicode
* @param { String } str - String containing the shortname(s)
* @returns { String }
*/
function shortnamesToUnicode(str) {
return addEmojisMarkup(convertASCII2Emoji(str)).pop();
}
/**
* Determines whether the passed in string is just a single emoji shortname;
* @namespace u
* @method u.isOnlyEmojis
* @param { String } text - A string which migh be just an emoji shortname
* @returns { Boolean }
*/
function isOnlyEmojis(text) {
const words = text.trim().split(/\s+/);
if (words.length === 0 || words.length > 3) {
return false;
}
const emojis = words.filter(text => {
const refs = getCodePointReferences(emoji_utils_u.shortnamesToUnicode(text));
return refs.length === 1 && (text === refs[0]['shortname'] || text === refs[0]['emoji']);
});
return emojis.length === words.length;
}
/**
* @namespace u
* @method u.getEmojisByAtrribute
* @param { 'category'|'cp'|'sn' } attr
* The attribute according to which the returned map should be keyed.
* @returns { Object }
* Map of emojis with the passed in `attr` used as key and a list of emojis as values.
*/
function getEmojisByAtrribute(attr) {
if (emojis_by_attribute[attr]) {
return emojis_by_attribute[attr];
}
if (attr === 'category') {
return converse.emojis.json;
}
const all_variants = converse.emojis.list.map(e => e[attr]).filter((c, i, arr) => arr.indexOf(c) == i);
emojis_by_attribute[attr] = {};
all_variants.forEach(v => emojis_by_attribute[attr][v] = converse.emojis.list.find(i => i[attr] === v));
return emojis_by_attribute[attr];
}
Object.assign(emoji_utils_u, {
getEmojisByAtrribute,
isOnlyEmojis,
shortnamesToUnicode
});
;// CONCATENATED MODULE: ./src/headless/plugins/emoji/index.js
/**
* @module converse-emoji
* @copyright 2022, the Converse.js contributors
* @license Mozilla Public License (MPLv2)
*/
converse.emojis = {
'initialized': false,
'initialized_promise': getOpenPromise()
};
converse.plugins.add('converse-emoji', {
initialize() {
/* The initialize function gets called as soon as the plugin is
* loaded by converse.js's plugin machinery.
*/
const {
___
} = shared_converse;
shared_api.settings.extend({
'emoji_image_path': 'https://twemoji.maxcdn.com/v/12.1.6/',
'emoji_categories': {
"smileys": ":grinning:",
"people": ":thumbsup:",
"activity": ":soccer:",
"travel": ":motorcycle:",
"objects": ":bomb:",
"nature": ":rainbow:",
"food": ":hotdog:",
"symbols": ":musical_note:",
"flags": ":flag_ac:",
"custom": null
},
// We use the triple-underscore method which doesn't actually
// translate but does signify to gettext that these strings should
// go into the POT file. The translation then happens in the
// template. We do this so that users can pass in their own
// strings via converse.initialize, which is before __ is
// available.
'emoji_category_labels': {
"smileys": ___("Smileys and emotions"),
"people": ___("People"),
"activity": ___("Activities"),
"travel": ___("Travel"),
"objects": ___("Objects"),
"nature": ___("Animals and nature"),
"food": ___("Food and drink"),
"symbols": ___("Symbols"),
"flags": ___("Flags"),
"custom": ___("Stickers")
}
});
/**
* Model for storing data related to the Emoji picker widget
* @class
* @namespace _converse.EmojiPicker
* @memberOf _converse
*/
shared_converse.EmojiPicker = Model.extend({
defaults: {
'current_category': 'smileys',
'current_skintone': '',
'scroll_position': 0
}
});
// We extend the default converse.js API to add methods specific to MUC groupchats.
Object.assign(shared_api, {
/**
* @namespace api.emojis
* @memberOf api
*/
emojis: {
/**
* Initializes Emoji support by downloading the emojis JSON (and any applicable images).
* @method api.emojis.initialize
* @returns {Promise}
*/
async initialize() {
if (!converse.emojis.initialized) {
converse.emojis.initialized = true;
const module = await __webpack_require__.e(/* import() | emojis */ 610).then(__webpack_require__.t.bind(__webpack_require__, 175, 19));
const json = converse.emojis.json = module.default;
converse.emojis.by_sn = Object.keys(json).reduce((result, cat) => Object.assign(result, json[cat]), {});
converse.emojis.list = Object.values(converse.emojis.by_sn);
converse.emojis.list.sort((a, b) => a.sn < b.sn ? -1 : a.sn > b.sn ? 1 : 0);
converse.emojis.shortnames = converse.emojis.list.map(m => m.sn);
const getShortNames = () => converse.emojis.shortnames.map(s => s.replace(/[+]/g, "\\$&")).join('|');
converse.emojis.shortnames_regex = new RegExp(getShortNames(), "gi");
converse.emojis.initialized_promise.resolve();
}
return converse.emojis.initialized_promise;
}
}
});
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/muc/message.js
/**
* Mixing that turns a Message model into a ChatRoomMessage model.
* @class
* @namespace _converse.ChatRoomMessage
* @memberOf _converse
*/
const ChatRoomMessageMixin = {
initialize() {
if (!this.checkValidity()) {
return;
}
if (this.get('file')) {
this.on('change:put', () => this.uploadFile());
}
// If `type` changes from `error` to `groupchat`, we want to set the occupant. See #2733
this.on('change:type', () => this.setOccupant());
this.on('change:is_ephemeral', () => this.setTimerForEphemeralMessage());
this.chatbox = this.collection?.chatbox;
this.setTimerForEphemeralMessage();
this.setOccupant();
/**
* Triggered once a { @link _converse.ChatRoomMessage } has been created and initialized.
* @event _converse#chatRoomMessageInitialized
* @type { _converse.ChatRoomMessages}
* @example _converse.api.listen.on('chatRoomMessageInitialized', model => { ... });
*/
shared_api.trigger('chatRoomMessageInitialized', this);
},
getDisplayName() {
return this.occupant?.getDisplayName() || this.get('nick');
},
/**
* Determines whether this messsage may be moderated,
* based on configuration settings and server support.
* @async
* @private
* @method _converse.ChatRoomMessages#mayBeModerated
* @returns { Boolean }
*/
mayBeModerated() {
if (typeof this.get('from_muc') === 'undefined') {
// If from_muc is not defined, then this message hasn't been
// reflected yet, which means we won't have a XEP-0359 stanza id.
return;
}
return ['all', 'moderator'].includes(shared_api.settings.get('allow_message_retraction')) && this.get(`stanza_id ${this.get('from_muc')}`) && this.chatbox.canModerateMessages();
},
checkValidity() {
const result = shared_converse.Message.prototype.checkValidity.call(this);
!result && this.chatbox.debouncedRejoin();
return result;
},
onOccupantRemoved() {
this.stopListening(this.occupant);
delete this.occupant;
this.listenTo(this.chatbox.occupants, 'add', this.onOccupantAdded);
},
onOccupantAdded(occupant) {
if (this.get('occupant_id')) {
if (occupant.get('occupant_id') !== this.get('occupant_id')) {
return;
}
} else if (occupant.get('nick') !== core.getResourceFromJid(this.get('from'))) {
return;
}
this.occupant = occupant;
if (occupant.get('jid')) {
this.save('from_real_jid', occupant.get('jid'));
}
this.trigger('occupantAdded');
this.listenTo(this.occupant, 'destroy', this.onOccupantRemoved);
this.stopListening(this.chatbox.occupants, 'add', this.onOccupantAdded);
},
getOccupant() {
if (this.occupant) return this.occupant;
this.setOccupant();
return this.occupant;
},
setOccupant() {
if (this.get('type') !== 'groupchat' || this.isEphemeral() || this.occupant) {
return;
}
const nick = core.getResourceFromJid(this.get('from'));
const occupant_id = this.get('occupant_id');
this.occupant = this.chatbox.occupants.findOccupant({
nick,
occupant_id
});
if (!this.occupant) {
this.occupant = this.chatbox.occupants.create({
nick,
occupant_id,
jid: this.get('from_real_jid')
});
if (shared_api.settings.get('muc_send_probes')) {
const jid = `${this.chatbox.get('jid')}/${nick}`;
shared_api.user.presence.send('probe', jid);
}
}
this.listenTo(this.occupant, 'destroy', this.onOccupantRemoved);
}
};
/* harmony default export */ const muc_message = (ChatRoomMessageMixin);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isElement.js
/**
* Checks if `value` is likely a DOM element.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*
* _.isElement('<body>');
* // => false
*/
function isElement_isElement(value) {
return lodash_es_isObjectLike(value) && value.nodeType === 1 && !lodash_es_isPlainObject(value);
}
/* harmony default export */ const lodash_es_isElement = (isElement_isElement);
;// CONCATENATED MODULE: ./src/headless/utils/parse-helpers.js
/**
* @copyright 2022, the Converse.js contributors
* @license Mozilla Public License (MPLv2)
* @description Pure functions to help functionally parse messages.
* @todo Other parsing helpers can be made more abstract and placed here.
*/
const helpers = {};
const escapeRegexChars = (string, char) => string.replace(RegExp('\\' + char, 'ig'), '\\' + char);
helpers.escapeCharacters = characters => string => characters.split('').reduce(escapeRegexChars, string);
helpers.escapeRegexString = helpers.escapeCharacters('[\\^$.?*+(){}|');
// `for` is ~25% faster than using `Array.find()`
helpers.findFirstMatchInArray = array => text => {
for (let i = 0; i < array.length; i++) {
if (text.localeCompare(array[i], undefined, {
sensitivity: 'base'
}) === 0) {
return array[i];
}
}
return null;
};
const reduceReferences = (_ref, ref, index) => {
let [text, refs] = _ref;
let updated_text = text;
let {
begin,
end
} = ref;
const {
value
} = ref;
begin = begin - index;
end = end - index - 1; // -1 to compensate for the removed @
updated_text = `${updated_text.slice(0, begin)}${value}${updated_text.slice(end + 1)}`;
return [updated_text, [...refs, {
...ref,
begin,
end
}]];
};
helpers.reduceTextFromReferences = (text, refs) => refs.reduce(reduceReferences, [text, []]);
/* harmony default export */ const parse_helpers = (helpers);
;// CONCATENATED MODULE: ./src/headless/plugins/muc/constants.js
const ROLES = ['moderator', 'participant', 'visitor'];
const AFFILIATIONS = (/* unused pure expression or super */ null && (['owner', 'admin', 'member', 'outcast', 'none']));
const MUC_ROLE_WEIGHTS = {
'moderator': 1,
'participant': 2,
'visitor': 3,
'none': 2
};
const AFFILIATION_CHANGES = {
OWNER: 'owner',
ADMIN: 'admin',
MEMBER: 'member',
EXADMIN: 'exadmin',
EXOWNER: 'exowner',
EXOUTCAST: 'exoutcast',
EXMEMBER: 'exmember'
};
const AFFILIATION_CHANGES_LIST = Object.values(AFFILIATION_CHANGES);
const MUC_TRAFFIC_STATES = {
ENTERED: 'entered',
EXITED: 'exited'
};
const MUC_TRAFFIC_STATES_LIST = Object.values(MUC_TRAFFIC_STATES);
const MUC_ROLE_CHANGES = {
OP: 'op',
DEOP: 'deop',
VOICE: 'voice',
MUTE: 'mute'
};
const MUC_ROLE_CHANGES_LIST = Object.values(MUC_ROLE_CHANGES);
const INFO_CODES = {
'visibility_changes': ['100', '102', '103', '172', '173', '174'],
'self': ['110'],
'non_privacy_changes': ['104', '201'],
'muc_logging_changes': ['170', '171'],
'nickname_changes': ['210', '303'],
'disconnected': ['301', '307', '321', '322', '332', '333'],
'affiliation_changes': [...AFFILIATION_CHANGES_LIST],
'join_leave_events': [...MUC_TRAFFIC_STATES_LIST],
'role_changes': [...MUC_ROLE_CHANGES_LIST]
};
const ROOMSTATUS = {
CONNECTED: 0,
CONNECTING: 1,
NICKNAME_REQUIRED: 2,
PASSWORD_REQUIRED: 3,
DISCONNECTED: 4,
ENTERED: 5,
DESTROYED: 6,
BANNED: 7,
CLOSING: 8
};
const ROOM_FEATURES = ['passwordprotected', 'unsecured', 'hidden', 'publicroom', 'membersonly', 'open', 'persistent', 'temporary', 'nonanonymous', 'semianonymous', 'moderated', 'unmoderated', 'mam_enabled'];
const MUC_NICK_CHANGED_CODE = '303';
// No longer used in code, but useful as reference.
//
// const ROOM_FEATURES_MAP = {
// 'passwordprotected': 'unsecured',
// 'unsecured': 'passwordprotected',
// 'hidden': 'publicroom',
// 'publicroom': 'hidden',
// 'membersonly': 'open',
// 'open': 'membersonly',
// 'persistent': 'temporary',
// 'temporary': 'persistent',
// 'nonanonymous': 'semianonymous',
// 'semianonymous': 'nonanonymous',
// 'moderated': 'unmoderated',
// 'unmoderated': 'moderated'
// };
;// CONCATENATED MODULE: ./src/headless/plugins/muc/parsers.js
const {
Strophe: muc_parsers_Strophe,
sizzle: muc_parsers_sizzle,
u: parsers_u
} = converse.env;
const {
NS: muc_parsers_NS
} = muc_parsers_Strophe;
/**
* Parses a message stanza for XEP-0317 MEP notification data
* @param { Element } stanza - The message stanza
* @returns { Array } Returns an array of objects representing <activity> elements.
*/
function getMEPActivities(stanza) {
const items_el = muc_parsers_sizzle(`items[node="${muc_parsers_Strophe.NS.CONFINFO}"]`, stanza).pop();
if (!items_el) {
return null;
}
const from = stanza.getAttribute('from');
const msgid = stanza.getAttribute('id');
const selector = `item ` + `conference-info[xmlns="${muc_parsers_Strophe.NS.CONFINFO}"] ` + `activity[xmlns="${muc_parsers_Strophe.NS.ACTIVITY}"]`;
return muc_parsers_sizzle(selector, items_el).map(el => {
const message = el.querySelector('text')?.textContent;
if (message) {
const references = getReferences(stanza);
const reason = el.querySelector('reason')?.textContent;
return {
from,
msgid,
message,
reason,
references,
'type': 'mep'
};
}
return {};
});
}
/**
* Given a MUC stanza, check whether it has extended message information that
* includes the sender's real JID, as described here:
* https://xmpp.org/extensions/xep-0313.html#business-storeret-muc-archives
*
* If so, parse and return that data and return the user's JID
*
* Note, this function doesn't check whether this is actually a MAM archived stanza.
*
* @private
* @param { Element } stanza - The message stanza
* @returns { Object }
*/
function getJIDFromMUCUserData(stanza) {
const item = muc_parsers_sizzle(`x[xmlns="${muc_parsers_Strophe.NS.MUC_USER}"] item`, stanza).pop();
return item?.getAttribute('jid');
}
/**
* @private
* @param { Element } stanza - The message stanza
* @param { Element } original_stanza - The original stanza, that contains the
* message stanza, if it was contained, otherwise it's the message stanza itself.
* @returns { Object }
*/
function getModerationAttributes(stanza) {
const fastening = muc_parsers_sizzle(`apply-to[xmlns="${muc_parsers_Strophe.NS.FASTEN}"]`, stanza).pop();
if (fastening) {
const applies_to_id = fastening.getAttribute('id');
const moderated = muc_parsers_sizzle(`moderated[xmlns="${muc_parsers_Strophe.NS.MODERATE}"]`, fastening).pop();
if (moderated) {
const retracted = muc_parsers_sizzle(`retract[xmlns="${muc_parsers_Strophe.NS.RETRACT}"]`, moderated).pop();
if (retracted) {
return {
'editable': false,
'moderated': 'retracted',
'moderated_by': moderated.getAttribute('by'),
'moderated_id': applies_to_id,
'moderation_reason': moderated.querySelector('reason')?.textContent
};
}
}
} else {
const tombstone = muc_parsers_sizzle(`> moderated[xmlns="${muc_parsers_Strophe.NS.MODERATE}"]`, stanza).pop();
if (tombstone) {
const retracted = muc_parsers_sizzle(`retracted[xmlns="${muc_parsers_Strophe.NS.RETRACT}"]`, tombstone).pop();
if (retracted) {
return {
'editable': false,
'is_tombstone': true,
'moderated_by': tombstone.getAttribute('by'),
'retracted': tombstone.getAttribute('stamp'),
'moderation_reason': tombstone.querySelector('reason')?.textContent
};
}
}
}
return {};
}
function getOccupantID(stanza, chatbox) {
if (chatbox.features.get(muc_parsers_Strophe.NS.OCCUPANTID)) {
return muc_parsers_sizzle(`occupant-id[xmlns="${muc_parsers_Strophe.NS.OCCUPANTID}"]`, stanza).pop()?.getAttribute('id');
}
}
/**
* Determines whether the sender of this MUC message is the current user or
* someone else.
* @param { MUCMessageAttributes } attrs
* @param { _converse.ChatRoom } chatbox
* @returns { 'me'|'them' }
*/
function getSender(attrs, chatbox) {
let is_me;
const own_occupant_id = chatbox.get('occupant_id');
if (own_occupant_id) {
is_me = attrs.occupant_id === own_occupant_id;
} else if (attrs.from_real_jid) {
is_me = muc_parsers_Strophe.getBareJidFromJid(attrs.from_real_jid) === shared_converse.bare_jid;
} else {
is_me = attrs.nick === chatbox.get('nick');
}
return is_me ? 'me' : 'them';
}
/**
* Parses a passed in message stanza and returns an object of attributes.
* @param { Element } stanza - The message stanza
* @param { Element } original_stanza - The original stanza, that contains the
* message stanza, if it was contained, otherwise it's the message stanza itself.
* @param { _converse.ChatRoom } chatbox
* @param { _converse } _converse
* @returns { Promise<MUCMessageAttributes|Error> }
*/
async function parseMUCMessage(stanza, chatbox) {
throwErrorIfInvalidForward(stanza);
const selector = `[xmlns="${muc_parsers_NS.MAM}"] > forwarded[xmlns="${muc_parsers_NS.FORWARD}"] > message`;
const original_stanza = stanza;
stanza = muc_parsers_sizzle(selector, stanza).pop() || stanza;
if (muc_parsers_sizzle(`message > forwarded[xmlns="${muc_parsers_Strophe.NS.FORWARD}"]`, stanza).length) {
return new StanzaParseError(`Invalid Stanza: Forged MAM groupchat message from ${stanza.getAttribute('from')}`, stanza);
}
const delay = muc_parsers_sizzle(`delay[xmlns="${muc_parsers_Strophe.NS.DELAY}"]`, original_stanza).pop();
const from = stanza.getAttribute('from');
const marker = getChatMarker(stanza);
/**
* @typedef { Object } MUCMessageAttributes
* The object which {@link parseMUCMessage} returns
* @property { ('me'|'them') } sender - Whether the message was sent by the current user or someone else
* @property { Array<Object> } activities - A list of objects representing XEP-0316 MEP notification data
* @property { Array<Object> } references - A list of objects representing XEP-0372 references
* @property { Boolean } editable - Is this message editable via XEP-0308?
* @property { Boolean } is_archived - Is this message from a XEP-0313 MAM archive?
* @property { Boolean } is_carbon - Is this message a XEP-0280 Carbon?
* @property { Boolean } is_delayed - Was delivery of this message was delayed as per XEP-0203?
* @property { Boolean } is_encrypted - Is this message XEP-0384 encrypted?
* @property { Boolean } is_error - Whether an error was received for this message
* @property { Boolean } is_headline - Is this a "headline" message?
* @property { Boolean } is_markable - Can this message be marked with a XEP-0333 chat marker?
* @property { Boolean } is_marker - Is this message a XEP-0333 Chat Marker?
* @property { Boolean } is_only_emojis - Does the message body contain only emojis?
* @property { Boolean } is_spoiler - Is this a XEP-0382 spoiler message?
* @property { Boolean } is_tombstone - Is this a XEP-0424 tombstone?
* @property { Boolean } is_unstyled - Whether XEP-0393 styling hints should be ignored
* @property { Boolean } is_valid_receipt_request - Does this message request a XEP-0184 receipt (and is not from us or a carbon or archived message)
* @property { Object } encrypted - XEP-0384 encryption payload attributes
* @property { String } body - The contents of the <body> tag of the message stanza
* @property { String } chat_state - The XEP-0085 chat state notification contained in this message
* @property { String } edited - An ISO8601 string recording the time that the message was edited per XEP-0308
* @property { String } error_condition - The defined error condition
* @property { String } error_text - The error text received from the server
* @property { String } error_type - The type of error received from the server
* @property { String } from - The sender JID (${muc_jid}/${nick})
* @property { String } from_muc - The JID of the MUC from which this message was sent
* @property { String } from_real_jid - The real JID of the sender, if available
* @property { String } fullname - The full name of the sender
* @property { String } marker - The XEP-0333 Chat Marker value
* @property { String } marker_id - The `id` attribute of a XEP-0333 chat marker
* @property { String } moderated - The type of XEP-0425 moderation (if any) that was applied
* @property { String } moderated_by - The JID of the user that moderated this message
* @property { String } moderated_id - The XEP-0359 Stanza ID of the message that this one moderates
* @property { String } moderation_reason - The reason provided why this message moderates another
* @property { String } msgid - The root `id` attribute of the stanza
* @property { String } nick - The MUC nickname of the sender
* @property { String } occupant_id - The XEP-0421 occupant ID
* @property { String } oob_desc - The description of the XEP-0066 out of band data
* @property { String } oob_url - The URL of the XEP-0066 out of band data
* @property { String } origin_id - The XEP-0359 Origin ID
* @property { String } receipt_id - The `id` attribute of a XEP-0184 <receipt> element
* @property { String } received - An ISO8601 string recording the time that the message was received
* @property { String } replace_id - The `id` attribute of a XEP-0308 <replace> element
* @property { String } retracted - An ISO8601 string recording the time that the message was retracted
* @property { String } retracted_id - The `id` attribute of a XEP-424 <retracted> element
* @property { String } spoiler_hint The XEP-0382 spoiler hint
* @property { String } stanza_id - The XEP-0359 Stanza ID. Note: the key is actualy `stanza_id ${by_jid}` and there can be multiple.
* @property { String } subject - The <subject> element value
* @property { String } thread - The <thread> element value
* @property { String } time - The time (in ISO8601 format), either given by the XEP-0203 <delay> element, or of receipt.
* @property { String } to - The recipient JID
* @property { String } type - The type of message
*/
let attrs = Object.assign({
from,
'activities': getMEPActivities(stanza),
'body': stanza.querySelector(':scope > body')?.textContent?.trim(),
'chat_state': getChatState(stanza),
'from_muc': muc_parsers_Strophe.getBareJidFromJid(from),
'is_archived': isArchived(original_stanza),
'is_carbon': isCarbon(original_stanza),
'is_delayed': !!delay,
'is_forwarded': !!stanza.querySelector('forwarded'),
'is_headline': isHeadline(stanza),
'is_markable': !!muc_parsers_sizzle(`markable[xmlns="${muc_parsers_Strophe.NS.MARKERS}"]`, stanza).length,
'is_marker': !!marker,
'is_unstyled': !!muc_parsers_sizzle(`unstyled[xmlns="${muc_parsers_Strophe.NS.STYLING}"]`, stanza).length,
'marker_id': marker && marker.getAttribute('id'),
'msgid': stanza.getAttribute('id') || original_stanza.getAttribute('id'),
'nick': muc_parsers_Strophe.unescapeNode(muc_parsers_Strophe.getResourceFromJid(from)),
'occupant_id': getOccupantID(stanza, chatbox),
'receipt_id': getReceiptId(stanza),
'received': new Date().toISOString(),
'references': getReferences(stanza),
'subject': stanza.querySelector('subject')?.textContent,
'thread': stanza.querySelector('thread')?.textContent,
'time': delay ? dayjs_min_default()(delay.getAttribute('stamp')).toISOString() : new Date().toISOString(),
'to': stanza.getAttribute('to'),
'type': stanza.getAttribute('type')
}, getErrorAttributes(stanza), getOutOfBandAttributes(stanza), getSpoilerAttributes(stanza), getCorrectionAttributes(stanza, original_stanza), getStanzaIDs(stanza, original_stanza), getOpenGraphMetadata(stanza), getRetractionAttributes(stanza, original_stanza), getModerationAttributes(stanza), getEncryptionAttributes(stanza, shared_converse));
await shared_api.emojis.initialize();
attrs.from_real_jid = attrs.is_archived && getJIDFromMUCUserData(stanza) || chatbox.occupants.findOccupant(attrs)?.get('jid');
attrs = Object.assign({
'is_only_emojis': attrs.body ? parsers_u.isOnlyEmojis(attrs.body) : false,
'is_valid_receipt_request': isValidReceiptRequest(stanza, attrs),
'message': attrs.body || attrs.error,
// TODO: Should only be used for error and info messages
'sender': getSender(attrs, chatbox)
}, attrs);
if (attrs.is_archived && original_stanza.getAttribute('from') !== attrs.from_muc) {
return new StanzaParseError(`Invalid Stanza: Forged MAM message from ${original_stanza.getAttribute('from')}`, stanza);
} else if (attrs.is_archived && original_stanza.getAttribute('from') !== chatbox.get('jid')) {
return new StanzaParseError(`Invalid Stanza: Forged MAM groupchat message from ${stanza.getAttribute('from')}`, stanza);
} else if (attrs.is_carbon) {
return new StanzaParseError('Invalid Stanza: MUC messages SHOULD NOT be XEP-0280 carbon copied', stanza);
}
// We prefer to use one of the XEP-0359 unique and stable stanza IDs as the Model id, to avoid duplicates.
attrs['id'] = attrs['origin_id'] || attrs[`stanza_id ${attrs.from_muc || attrs.from}`] || parsers_u.getUniqueId();
/**
* *Hook* which allows plugins to add additional parsing
* @event _converse#parseMUCMessage
*/
attrs = await shared_api.hook('parseMUCMessage', stanza, attrs);
// We call this after the hook, to allow plugins to decrypt encrypted
// messages, since we need to parse the message text to determine whether
// there are media urls.
return Object.assign(attrs, getMediaURLsMetadata(attrs.is_encrypted ? attrs.plaintext : attrs.body));
}
/**
* Given an IQ stanza with a member list, create an array of objects containing
* known member data (e.g. jid, nick, role, affiliation).
* @private
* @method muc_utils#parseMemberListIQ
* @returns { MemberListItem[] }
*/
function parseMemberListIQ(iq) {
return muc_parsers_sizzle(`query[xmlns="${muc_parsers_Strophe.NS.MUC_ADMIN}"] item`, iq).map(item => {
/**
* @typedef {Object} MemberListItem
* Either the JID or the nickname (or both) will be available.
* @property {string} affiliation
* @property {string} [role]
* @property {string} [jid]
* @property {string} [nick]
*/
const data = {
'affiliation': item.getAttribute('affiliation')
};
const jid = item.getAttribute('jid');
if (parsers_u.isValidJID(jid)) {
data['jid'] = jid;
} else {
// XXX: Prosody sends nick for the jid attribute value
// Perhaps for anonymous room?
data['nick'] = jid;
}
const nick = item.getAttribute('nick');
if (nick) {
data['nick'] = nick;
}
const role = item.getAttribute('role');
if (role) {
data['role'] = nick;
}
return data;
});
}
/**
* Parses a passed in MUC presence stanza and returns an object of attributes.
* @method parseMUCPresence
* @param { Element } stanza - The presence stanza
* @param { _converse.ChatRoom } chatbox
* @returns { MUCPresenceAttributes }
*/
function parseMUCPresence(stanza, chatbox) {
/**
* @typedef { Object } MUCPresenceAttributes
* The object which {@link parseMUCPresence} returns
* @property { ("offline|online") } show
* @property { Array<MUCHat> } hats - An array of XEP-0317 hats
* @property { Array<string> } states
* @property { String } from - The sender JID (${muc_jid}/${nick})
* @property { String } nick - The nickname of the sender
* @property { String } occupant_id - The XEP-0421 occupant ID
* @property { String } type - The type of presence
*/
const from = stanza.getAttribute('from');
const type = stanza.getAttribute('type');
const data = {
'is_me': !!stanza.querySelector("status[code='110']"),
'from': from,
'occupant_id': getOccupantID(stanza, chatbox),
'nick': muc_parsers_Strophe.getResourceFromJid(from),
'type': type,
'states': [],
'hats': [],
'show': type !== 'unavailable' ? 'online' : 'offline'
};
Array.from(stanza.children).forEach(child => {
if (child.matches('status')) {
data.status = child.textContent || null;
} else if (child.matches('show')) {
data.show = child.textContent || 'online';
} else if (child.matches('x') && child.getAttribute('xmlns') === muc_parsers_Strophe.NS.MUC_USER) {
Array.from(child.children).forEach(item => {
if (item.nodeName === 'item') {
data.affiliation = item.getAttribute('affiliation');
data.role = item.getAttribute('role');
data.jid = item.getAttribute('jid');
data.nick = item.getAttribute('nick') || data.nick;
} else if (item.nodeName == 'status' && item.getAttribute('code')) {
data.states.push(item.getAttribute('code'));
}
});
} else if (child.matches('x') && child.getAttribute('xmlns') === muc_parsers_Strophe.NS.VCARDUPDATE) {
data.image_hash = child.querySelector('photo')?.textContent;
} else if (child.matches('hats') && child.getAttribute('xmlns') === muc_parsers_Strophe.NS.MUC_HATS) {
/**
* @typedef { Object } MUCHat
* Object representing a XEP-0371 Hat
* @property { String } title
* @property { String } uri
*/
data['hats'] = Array.from(child.children).map(c => c.matches('hat') && {
'title': c.getAttribute('title'),
'uri': c.getAttribute('uri')
});
}
});
return data;
}
;// CONCATENATED MODULE: ./src/headless/plugins/muc/affiliations/utils.js
/**
* @copyright The Converse.js contributors
* @license Mozilla Public License (MPLv2)
*/
const {
Strophe: affiliations_utils_Strophe,
$iq: affiliations_utils_$iq,
u: affiliations_utils_u
} = converse.env;
/**
* Sends an IQ stanza to the server, asking it for the relevant affiliation list .
* Returns an array of {@link MemberListItem} objects, representing occupants
* that have the given affiliation.
* See: https://xmpp.org/extensions/xep-0045.html#modifymember
* @param { ("admin"|"owner"|"member") } affiliation
* @param { String } muc_jid - The JID of the MUC for which the affiliation list should be fetched
* @returns { Promise<MemberListItem[]> }
*/
async function getAffiliationList(affiliation, muc_jid) {
const {
__
} = shared_converse;
const iq = affiliations_utils_$iq({
'to': muc_jid,
'type': 'get'
}).c('query', {
xmlns: affiliations_utils_Strophe.NS.MUC_ADMIN
}).c('item', {
'affiliation': affiliation
});
const result = await shared_api.sendIQ(iq, null, false);
if (result === null) {
const err_msg = __('Error: timeout while fetching %1s list for MUC %2s', affiliation, muc_jid);
const err = new Error(err_msg);
log.warn(err_msg);
return err;
}
if (affiliations_utils_u.isErrorStanza(result)) {
const err_msg = __('Error: not allowed to fetch %1s list for MUC %2s', affiliation, muc_jid);
const err = new Error(err_msg);
log.warn(err_msg);
log.warn(result);
return err;
}
return parseMemberListIQ(result).filter(p => p).sort((a, b) => a.nick < b.nick ? -1 : a.nick > b.nick ? 1 : 0);
}
/**
* Given an occupant model, see which affiliations may be assigned by that user
* @param { Model } occupant
* @returns { Array<('owner'|'admin'|'member'|'outcast'|'none')> } - An array of assignable affiliations
*/
function getAssignableAffiliations(occupant) {
let disabled = shared_api.settings.get('modtools_disable_assign');
if (!Array.isArray(disabled)) {
disabled = disabled ? muc_AFFILIATIONS : [];
}
if (occupant?.get('affiliation') === 'owner') {
return muc_AFFILIATIONS.filter(a => !disabled.includes(a));
} else if (occupant?.get('affiliation') === 'admin') {
return muc_AFFILIATIONS.filter(a => !['owner', 'admin', ...disabled].includes(a));
} else {
return [];
}
}
// Necessary for tests
shared_converse.getAssignableAffiliations = getAssignableAffiliations;
/**
* Send IQ stanzas to the server to modify affiliations for users in this groupchat.
* See: https://xmpp.org/extensions/xep-0045.html#modifymember
* @param { Array<Object> } users
* @param { string } users[].jid - The JID of the user whose affiliation will change
* @param { Array } users[].affiliation - The new affiliation for this user
* @param { string } [users[].reason] - An optional reason for the affiliation change
* @returns { Promise }
*/
function setAffiliations(muc_jid, users) {
const affiliations = [...new Set(users.map(u => u.affiliation))];
return Promise.all(affiliations.map(a => setAffiliation(a, muc_jid, users)));
}
/**
* Send IQ stanzas to the server to set an affiliation for
* the provided JIDs.
* See: https://xmpp.org/extensions/xep-0045.html#modifymember
*
* Prosody doesn't accept multiple JIDs' affiliations
* being set in one IQ stanza, so as a workaround we send
* a separate stanza for each JID.
* Related ticket: https://issues.prosody.im/345
*
* @param { ('outcast'|'member'|'admin'|'owner') } affiliation - The affiliation to be set
* @param { String|Array<String> } jids - The JID(s) of the MUCs in which the
* affiliations need to be set.
* @param { object } members - A map of jids, affiliations and
* optionally reasons. Only those entries with the
* same affiliation as being currently set will be considered.
* @returns { Promise } A promise which resolves and fails depending on the XMPP server response.
*/
function setAffiliation(affiliation, muc_jids, members) {
if (!Array.isArray(muc_jids)) {
muc_jids = [muc_jids];
}
members = members.filter(m => [undefined, affiliation].includes(m.affiliation));
return Promise.all(muc_jids.reduce((acc, jid) => [...acc, ...members.map(m => sendAffiliationIQ(affiliation, jid, m))], []));
}
/**
* Send an IQ stanza specifying an affiliation change.
* @private
* @param { String } affiliation: affiliation (could also be stored on the member object).
* @param { String } muc_jid: The JID of the MUC in which the affiliation should be set.
* @param { Object } member: Map containing the member's jid and optionally a reason and affiliation.
*/
function sendAffiliationIQ(affiliation, muc_jid, member) {
const iq = affiliations_utils_$iq({
to: muc_jid,
type: 'set'
}).c('query', {
xmlns: affiliations_utils_Strophe.NS.MUC_ADMIN
}).c('item', {
'affiliation': member.affiliation || affiliation,
'nick': member.nick,
'jid': member.jid
});
if (member.reason !== undefined) {
iq.c('reason', member.reason);
}
return shared_api.sendIQ(iq);
}
/**
* Given two lists of objects with 'jid', 'affiliation' and
* 'reason' properties, return a new list containing
* those objects that are new, changed or removed
* (depending on the 'remove_absentees' boolean).
*
* The affiliations for new and changed members stay the
* same, for removed members, the affiliation is set to 'none'.
*
* The 'reason' property is not taken into account when
* comparing whether affiliations have been changed.
* @param { boolean } exclude_existing - Indicates whether JIDs from
* the new list which are also in the old list
* (regardless of affiliation) should be excluded
* from the delta. One reason to do this
* would be when you want to add a JID only if it
* doesn't have *any* existing affiliation at all.
* @param { boolean } remove_absentees - Indicates whether JIDs
* from the old list which are not in the new list
* should be considered removed and therefore be
* included in the delta with affiliation set
* to 'none'.
* @param { array } new_list - Array containing the new affiliations
* @param { array } old_list - Array containing the old affiliations
* @returns { array }
*/
function computeAffiliationsDelta(exclude_existing, remove_absentees, new_list, old_list) {
const new_jids = new_list.map(o => o.jid);
const old_jids = old_list.map(o => o.jid);
// Get the new affiliations
let delta = lodash_es_difference(new_jids, old_jids).map(jid => new_list[lodash_es_indexOf(new_jids, jid)]);
if (!exclude_existing) {
// Get the changed affiliations
delta = delta.concat(new_list.filter(item => {
const idx = lodash_es_indexOf(old_jids, item.jid);
return idx >= 0 ? item.affiliation !== old_list[idx].affiliation : false;
}));
}
if (remove_absentees) {
// Get the removed affiliations
delta = delta.concat(lodash_es_difference(old_jids, new_jids).map(jid => ({
'jid': jid,
'affiliation': 'none'
})));
}
return delta;
}
;// CONCATENATED MODULE: ./src/headless/plugins/muc/muc.js
const {
u: muc_u
} = converse.env;
const OWNER_COMMANDS = ['owner'];
const ADMIN_COMMANDS = ['admin', 'ban', 'deop', 'destroy', 'member', 'op', 'revoke'];
const MODERATOR_COMMANDS = ['kick', 'mute', 'voice', 'modtools'];
const VISITOR_COMMANDS = ['nick'];
const METADATA_ATTRIBUTES = ["og:article:author", "og:article:published_time", "og:description", "og:image", "og:image:height", "og:image:width", "og:site_name", "og:title", "og:type", "og:url", "og:video:height", "og:video:secure_url", "og:video:tag", "og:video:type", "og:video:url", "og:video:width"];
const ACTION_INFO_CODES = ['301', '303', '333', '307', '321', '322'];
const MUCSession = Model.extend({
defaults() {
return {
'connection_status': ROOMSTATUS.DISCONNECTED
};
}
});
/**
* Represents an open/ongoing groupchat conversation.
* @mixin
* @namespace _converse.ChatRoom
* @memberOf _converse
*/
const ChatRoomMixin = {
defaults() {
return {
'bookmarked': false,
'chat_state': undefined,
'has_activity': false,
// XEP-437
'hidden': isUniView() && !shared_api.settings.get('singleton'),
'hidden_occupants': !!shared_api.settings.get('hide_muc_participants'),
'message_type': 'groupchat',
'name': '',
// For group chats, we distinguish between generally unread
// messages and those ones that specifically mention the
// user.
//
// To keep things simple, we reuse `num_unread` from
// _converse.ChatBox to indicate unread messages which
// mention the user and `num_unread_general` to indicate
// generally unread messages (which *includes* mentions!).
'num_unread_general': 0,
'num_unread': 0,
'roomconfig': {},
'time_opened': this.get('time_opened') || new Date().getTime(),
'time_sent': new Date(0).toISOString(),
'type': shared_converse.CHATROOMS_TYPE
};
},
async initialize() {
this.initialized = getOpenPromise();
this.debouncedRejoin = lodash_es_debounce(this.rejoin, 250);
this.set('box_id', `box-${this.get('jid')}`);
this.initNotifications();
this.initMessages();
this.initUI();
this.initOccupants();
this.initDiscoModels(); // sendChatState depends on this.features
this.registerHandlers();
this.on('change:chat_state', this.sendChatState, this);
this.on('change:hidden', this.onHiddenChange, this);
this.on('destroy', this.removeHandlers, this);
this.ui.on('change:scrolled', this.onScrolledChanged, this);
await this.restoreSession();
this.session.on('change:connection_status', this.onConnectionStatusChanged, this);
this.listenTo(this.occupants, 'add', this.onOccupantAdded);
this.listenTo(this.occupants, 'remove', this.onOccupantRemoved);
this.listenTo(this.occupants, 'change:show', this.onOccupantShowChanged);
this.listenTo(this.occupants, 'change:affiliation', this.createAffiliationChangeMessage);
this.listenTo(this.occupants, 'change:role', this.createRoleChangeMessage);
const restored = await this.restoreFromCache();
if (!restored) {
this.join();
}
/**
* Triggered once a {@link _converse.ChatRoom} has been created and initialized.
* @event _converse#chatRoomInitialized
* @type { _converse.ChatRoom }
* @example _converse.api.listen.on('chatRoomInitialized', model => { ... });
*/
await shared_api.trigger('chatRoomInitialized', this, {
'Synchronous': true
});
this.initialized.resolve();
},
isEntered() {
return this.session.get('connection_status') === ROOMSTATUS.ENTERED;
},
/**
* Checks whether this MUC qualifies for subscribing to XEP-0437 Room Activity Indicators (RAI)
* @method _converse.ChatRoom#isRAICandidate
* @returns { Boolean }
*/
isRAICandidate() {
return this.get('hidden') && shared_api.settings.get('muc_subscribe_to_rai') && this.getOwnAffiliation() !== 'none';
},
/**
* Checks whether we're still joined and if so, restores the MUC state from cache.
* @private
* @method _converse.ChatRoom#restoreFromCache
* @returns { Boolean } Returns `true` if we're still joined, otherwise returns `false`.
*/
async restoreFromCache() {
if (this.isEntered()) {
await this.fetchOccupants().catch(e => log.error(e));
if (this.isRAICandidate()) {
this.session.save('connection_status', ROOMSTATUS.DISCONNECTED);
this.enableRAI();
return true;
} else if (await this.isJoined()) {
await new Promise(r => this.config.fetch({
'success': r,
'error': r
}));
await new Promise(r => this.features.fetch({
'success': r,
'error': r
}));
await this.fetchMessages().catch(e => log.error(e));
return true;
}
}
this.session.save('connection_status', ROOMSTATUS.DISCONNECTED);
this.clearOccupantsCache();
return false;
},
/**
* Join the MUC
* @private
* @method _converse.ChatRoom#join
* @param { String } nick - The user's nickname
* @param { String } [password] - Optional password, if required by the groupchat.
* Will fall back to the `password` value stored in the room
* model (if available).
*/
async join(nick, password) {
if (this.isEntered()) {
// We have restored a groupchat from session storage,
// so we don't send out a presence stanza again.
return this;
}
// Set this early, so we don't rejoin in onHiddenChange
this.session.save('connection_status', ROOMSTATUS.CONNECTING);
await this.refreshDiscoInfo();
nick = await this.getAndPersistNickname(nick);
if (!nick) {
safeSave(this.session, {
'connection_status': ROOMSTATUS.NICKNAME_REQUIRED
});
if (shared_api.settings.get('muc_show_logs_before_join')) {
await this.fetchMessages();
}
return this;
}
shared_api.send(await this.constructJoinPresence(password));
return this;
},
/**
* Clear stale cache and re-join a MUC we've been in before.
* @private
* @method _converse.ChatRoom#rejoin
*/
rejoin() {
this.session.save('connection_status', ROOMSTATUS.DISCONNECTED);
this.registerHandlers();
this.clearOccupantsCache();
return this.join();
},
async constructJoinPresence(password) {
let stanza = $pres({
'id': getUniqueId(),
'from': shared_converse.connection.jid,
'to': this.getRoomJIDAndNick()
}).c('x', {
'xmlns': core.NS.MUC
}).c('history', {
'maxstanzas': this.features.get('mam_enabled') ? 0 : shared_api.settings.get('muc_history_max_stanzas')
}).up();
password = password || this.get('password');
if (password) {
stanza.cnode(core.xmlElement('password', [], password));
}
stanza.up(); // Go one level up, out of the `x` element.
/**
* *Hook* which allows plugins to update an outgoing MUC join presence stanza
* @event _converse#constructedMUCPresence
* @param { _converse.ChatRoom } - The MUC from which this message stanza is being sent.
* @param { Element } stanza - The stanza which will be sent out
*/
stanza = await shared_api.hook('constructedMUCPresence', this, stanza);
return stanza;
},
clearOccupantsCache() {
if (this.occupants.length) {
// Remove non-members when reconnecting
this.occupants.filter(o => !o.isMember()).forEach(o => o.destroy());
} else {
// Looks like we haven't restored occupants from cache, so we clear it.
this.occupants.clearStore();
}
},
/**
* Given the passed in MUC message, send a XEP-0333 chat marker.
* @param { _converse.MUCMessage } msg
* @param { ('received'|'displayed'|'acknowledged') } [type='displayed']
* @param { Boolean } force - Whether a marker should be sent for the
* message, even if it didn't include a `markable` element.
*/
sendMarkerForMessage(msg) {
let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'displayed';
let force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!msg || !shared_api.settings.get('send_chat_markers').includes(type) || msg?.get('type') !== 'groupchat') {
return;
}
if (msg?.get('is_markable') || force) {
const key = `stanza_id ${this.get('jid')}`;
const id = msg.get(key);
if (!id) {
log.error(`Can't send marker for message without stanza ID: ${key}`);
return;
}
const from_jid = core.getBareJidFromJid(msg.get('from'));
sendMarker(from_jid, id, type, msg.get('type'));
}
},
/**
* Ensures that the user is subscribed to XEP-0437 Room Activity Indicators
* if `muc_subscribe_to_rai` is set to `true`.
* Only affiliated users can subscribe to RAI, but this method doesn't
* check whether the current user is affiliated because it's intended to be
* called after the MUC has been left and we don't have that information
* anymore.
* @private
* @method _converse.ChatRoom#enableRAI
*/
enableRAI() {
if (shared_api.settings.get('muc_subscribe_to_rai')) {
const muc_domain = core.getDomainFromJid(this.get('jid'));
shared_api.user.presence.send(null, muc_domain, null, $build('rai', {
'xmlns': core.NS.RAI
}));
}
},
/**
* Handler that gets called when the 'hidden' flag is toggled.
* @private
* @method _converse.ChatRoom#onHiddenChange
*/
async onHiddenChange() {
const roomstatus = ROOMSTATUS;
const conn_status = this.session.get('connection_status');
if (this.get('hidden')) {
if (conn_status === roomstatus.ENTERED && this.isRAICandidate()) {
this.sendMarkerForLastMessage('received', true);
await this.leave();
this.enableRAI();
}
} else {
if (conn_status === roomstatus.DISCONNECTED) {
this.rejoin();
}
this.clearUnreadMsgCounter();
}
},
onOccupantAdded(occupant) {
if (shared_converse.isInfoVisible(converse.MUC_TRAFFIC_STATES.ENTERED) && this.session.get('connection_status') === ROOMSTATUS.ENTERED && occupant.get('show') === 'online') {
this.updateNotifications(occupant.get('nick'), converse.MUC_TRAFFIC_STATES.ENTERED);
}
},
onOccupantRemoved(occupant) {
if (shared_converse.isInfoVisible(converse.MUC_TRAFFIC_STATES.EXITED) && this.isEntered() && occupant.get('show') === 'online') {
this.updateNotifications(occupant.get('nick'), converse.MUC_TRAFFIC_STATES.EXITED);
}
},
onOccupantShowChanged(occupant) {
if (occupant.get('states').includes('303')) {
return;
}
if (occupant.get('show') === 'offline' && shared_converse.isInfoVisible(converse.MUC_TRAFFIC_STATES.EXITED)) {
this.updateNotifications(occupant.get('nick'), converse.MUC_TRAFFIC_STATES.EXITED);
} else if (occupant.get('show') === 'online' && shared_converse.isInfoVisible(converse.MUC_TRAFFIC_STATES.ENTERED)) {
this.updateNotifications(occupant.get('nick'), converse.MUC_TRAFFIC_STATES.ENTERED);
}
},
async onRoomEntered() {
await this.occupants.fetchMembers();
if (shared_api.settings.get('clear_messages_on_reconnection')) {
await this.clearMessages();
} else {
await this.fetchMessages();
}
/**
* Triggered when the user has entered a new MUC
* @event _converse#enteredNewRoom
* @type { _converse.ChatRoom}
* @example _converse.api.listen.on('enteredNewRoom', model => { ... });
*/
shared_api.trigger('enteredNewRoom', this);
if (shared_api.settings.get('auto_register_muc_nickname') && (await shared_api.disco.supports(core.NS.MUC_REGISTER, this.get('jid')))) {
this.registerNickname();
}
},
async onConnectionStatusChanged() {
if (this.isEntered()) {
if (this.isRAICandidate()) {
try {
await this.leave();
} catch (e) {
log.error(e);
}
this.enableRAI();
} else {
await this.onRoomEntered();
}
}
},
async onReconnection() {
await this.rejoin();
this.announceReconnection();
},
getMessagesCollection() {
return new shared_converse.ChatRoomMessages();
},
restoreSession() {
const id = `muc.session-${shared_converse.bare_jid}-${this.get('jid')}`;
this.session = new MUCSession({
id
});
initStorage(this.session, id, 'session');
return new Promise(r => this.session.fetch({
'success': r,
'error': r
}));
},
initDiscoModels() {
let id = `converse.muc-features-${shared_converse.bare_jid}-${this.get('jid')}`;
this.features = new Model(Object.assign({
id
}, converse.ROOM_FEATURES.reduce((acc, feature) => {
acc[feature] = false;
return acc;
}, {})));
this.features.browserStorage = shared_converse.createStore(id, 'session');
this.features.listenTo(shared_converse, 'beforeLogout', () => this.features.browserStorage.flush());
id = `converse.muc-config-${shared_converse.bare_jid}-${this.get('jid')}`;
this.config = new Model({
id
});
this.config.browserStorage = shared_converse.createStore(id, 'session');
this.config.listenTo(shared_converse, 'beforeLogout', () => this.config.browserStorage.flush());
},
initOccupants() {
this.occupants = new shared_converse.ChatRoomOccupants();
const id = `converse.occupants-${shared_converse.bare_jid}${this.get('jid')}`;
this.occupants.browserStorage = shared_converse.createStore(id, 'session');
this.occupants.chatroom = this;
this.occupants.listenTo(shared_converse, 'beforeLogout', () => this.occupants.browserStorage.flush());
},
fetchOccupants() {
this.occupants.fetched = new Promise(resolve => {
this.occupants.fetch({
'add': true,
'silent': true,
'success': resolve,
'error': resolve
});
});
return this.occupants.fetched;
},
handleAffiliationChangedMessage(stanza) {
const item = sizzle_default()(`x[xmlns="${core.NS.MUC_USER}"] item`, stanza).pop();
if (item) {
const from = stanza.getAttribute('from');
const type = stanza.getAttribute('type');
const affiliation = item.getAttribute('affiliation');
const jid = item.getAttribute('jid');
const data = {
from,
type,
affiliation,
'states': [],
'show': type == 'unavailable' ? 'offline' : 'online',
'role': item.getAttribute('role'),
'jid': core.getBareJidFromJid(jid),
'resource': core.getResourceFromJid(jid)
};
const occupant = this.occupants.findOccupant({
'jid': data.jid
});
if (occupant) {
occupant.save(data);
} else {
this.occupants.create(data);
}
}
},
async handleErrorMessageStanza(stanza) {
const {
__
} = shared_converse;
const attrs = await parseMUCMessage(stanza, this);
if (!(await this.shouldShowErrorMessage(attrs))) {
return;
}
const message = this.getMessageReferencedByError(attrs);
if (message) {
const new_attrs = {
'error': attrs.error,
'error_condition': attrs.error_condition,
'error_text': attrs.error_text,
'error_type': attrs.error_type,
'editable': false
};
if (attrs.msgid === message.get('retraction_id')) {
// The error message refers to a retraction
new_attrs.retracted = undefined;
new_attrs.retraction_id = undefined;
new_attrs.retracted_id = undefined;
if (!attrs.error) {
if (attrs.error_condition === 'forbidden') {
new_attrs.error = __("You're not allowed to retract your message.");
} else if (attrs.error_condition === 'not-acceptable') {
new_attrs.error = __("Your retraction was not delivered because you're not present in the groupchat.");
} else {
new_attrs.error = __('Sorry, an error occurred while trying to retract your message.');
}
}
} else if (!attrs.error) {
if (attrs.error_condition === 'forbidden') {
new_attrs.error = __("Your message was not delivered because you weren't allowed to send it.");
} else if (attrs.error_condition === 'not-acceptable') {
new_attrs.error = __("Your message was not delivered because you're not present in the groupchat.");
} else {
new_attrs.error = __('Sorry, an error occurred while trying to send your message.');
}
}
message.save(new_attrs);
} else {
this.createMessage(attrs);
}
},
/**
* Handles incoming message stanzas from the service that hosts this MUC
* @private
* @method _converse.ChatRoom#handleMessageFromMUCHost
* @param { Element } stanza
*/
handleMessageFromMUCHost(stanza) {
if (this.isEntered()) {
// We're not interested in activity indicators when already joined to the room
return;
}
const rai = sizzle_default()(`rai[xmlns="${core.NS.RAI}"]`, stanza).pop();
const active_mucs = Array.from(rai?.querySelectorAll('activity') || []).map(m => m.textContent);
if (active_mucs.includes(this.get('jid'))) {
this.save({
'has_activity': true,
'num_unread_general': 0 // Either/or between activity and unreads
});
}
},
/**
* Handles XEP-0452 MUC Mention Notification messages
* @private
* @method _converse.ChatRoom#handleForwardedMentions
* @param { Element } stanza
*/
handleForwardedMentions(stanza) {
if (this.isEntered()) {
// Avoid counting mentions twice
return;
}
const msgs = sizzle_default()(`mentions[xmlns="${core.NS.MENTIONS}"] forwarded[xmlns="${core.NS.FORWARD}"] message[type="groupchat"]`, stanza);
const muc_jid = this.get('jid');
const mentions = msgs.filter(m => core.getBareJidFromJid(m.getAttribute('from')) === muc_jid);
if (mentions.length) {
this.save({
'has_activity': true,
'num_unread': this.get('num_unread') + mentions.length
});
mentions.forEach(async stanza => {
const attrs = await parseMUCMessage(stanza, this);
const data = {
stanza,
attrs,
'chatbox': this
};
shared_api.trigger('message', data);
});
}
},
/**
* Parses an incoming message stanza and queues it for processing.
* @private
* @method _converse.ChatRoom#handleMessageStanza
* @param { Element } stanza
*/
async handleMessageStanza(stanza) {
stanza = stanza.tree?.() ?? stanza;
const type = stanza.getAttribute('type');
if (type === 'error') {
return this.handleErrorMessageStanza(stanza);
}
if (type === 'groupchat') {
if (isArchived(stanza)) {
// MAM messages are handled in converse-mam.
// We shouldn't get MAM messages here because
// they shouldn't have a `type` attribute.
return log.warn(`Received a MAM message with type "groupchat"`);
}
this.createInfoMessages(stanza);
this.fetchFeaturesIfConfigurationChanged(stanza);
} else if (!type) {
return this.handleForwardedMentions(stanza);
}
/**
* @typedef { Object } MUCMessageData
* An object containing the parsed {@link MUCMessageAttributes} and
* current {@link ChatRoom}.
* @property { MUCMessageAttributes } attrs
* @property { ChatRoom } chatbox
*/
let attrs;
try {
attrs = await parseMUCMessage(stanza, this);
} catch (e) {
return log.error(e);
}
const data = {
stanza,
attrs,
'chatbox': this
};
/**
* Triggered when a groupchat message stanza has been received and parsed.
* @event _converse#message
* @type { object }
* @property { module:converse-muc~MUCMessageData } data
*/
shared_api.trigger('message', data);
return attrs && this.queueMessage(attrs);
},
/**
* Register presence and message handlers relevant to this groupchat
* @private
* @method _converse.ChatRoom#registerHandlers
*/
registerHandlers() {
const muc_jid = this.get('jid');
const muc_domain = core.getDomainFromJid(muc_jid);
this.removeHandlers();
this.presence_handler = shared_converse.connection.addHandler(stanza => this.onPresence(stanza) || true, null, 'presence', null, null, muc_jid, {
'ignoreNamespaceFragment': true,
'matchBareFromJid': true
});
this.domain_presence_handler = shared_converse.connection.addHandler(stanza => this.onPresenceFromMUCHost(stanza) || true, null, 'presence', null, null, muc_domain);
this.message_handler = shared_converse.connection.addHandler(stanza => !!this.handleMessageStanza(stanza) || true, null, 'message', null, null, muc_jid, {
'matchBareFromJid': true
});
this.domain_message_handler = shared_converse.connection.addHandler(stanza => this.handleMessageFromMUCHost(stanza) || true, null, 'message', null, null, muc_domain);
this.affiliation_message_handler = shared_converse.connection.addHandler(stanza => this.handleAffiliationChangedMessage(stanza) || true, core.NS.MUC_USER, 'message', null, null, muc_jid);
},
removeHandlers() {
// Remove the presence and message handlers that were
// registered for this groupchat.
if (this.message_handler) {
shared_converse.connection && shared_converse.connection.deleteHandler(this.message_handler);
delete this.message_handler;
}
if (this.domain_message_handler) {
shared_converse.connection && shared_converse.connection.deleteHandler(this.domain_message_handler);
delete this.domain_message_handler;
}
if (this.presence_handler) {
shared_converse.connection && shared_converse.connection.deleteHandler(this.presence_handler);
delete this.presence_handler;
}
if (this.domain_presence_handler) {
shared_converse.connection && shared_converse.connection.deleteHandler(this.domain_presence_handler);
delete this.domain_presence_handler;
}
if (this.affiliation_message_handler) {
shared_converse.connection && shared_converse.connection.deleteHandler(this.affiliation_message_handler);
delete this.affiliation_message_handler;
}
return this;
},
invitesAllowed() {
return shared_api.settings.get('allow_muc_invitations') && (this.features.get('open') || this.getOwnAffiliation() === 'owner');
},
getDisplayName() {
const name = this.get('name');
if (name) {
return name;
} else if (shared_api.settings.get('locked_muc_domain') === 'hidden') {
return core.getNodeFromJid(this.get('jid'));
} else {
return this.get('jid');
}
},
/**
* Sends a message stanza to the XMPP server and expects a reflection
* or error message within a specific timeout period.
* @private
* @method _converse.ChatRoom#sendTimedMessage
* @param { _converse.Message|Element } message
* @returns { Promise<Element>|Promise<TimeoutError> } Returns a promise
* which resolves with the reflected message stanza or with an error stanza or {@link TimeoutError}.
*/
sendTimedMessage(el) {
if (typeof el.tree === 'function') {
el = el.tree();
}
let id = el.getAttribute('id');
if (!id) {
// inject id if not found
id = this.getUniqueId('sendIQ');
el.setAttribute('id', id);
}
const promise = getOpenPromise();
const timeout = shared_api.settings.get('stanza_timeout');
const timeoutHandler = shared_converse.connection.addTimedHandler(timeout, () => {
shared_converse.connection.deleteHandler(handler);
const err = new TimeoutError('Timeout Error: No response from server');
promise.resolve(err);
return false;
});
const handler = shared_converse.connection.addHandler(stanza => {
timeoutHandler && shared_converse.connection.deleteTimedHandler(timeoutHandler);
promise.resolve(stanza);
}, null, 'message', ['error', 'groupchat'], id);
shared_api.send(el);
return promise;
},
/**
* Retract one of your messages in this groupchat
* @private
* @method _converse.ChatRoom#retractOwnMessage
* @param { _converse.Message } message - The message which we're retracting.
*/
async retractOwnMessage(message) {
const __ = shared_converse.__;
const origin_id = message.get('origin_id');
if (!origin_id) {
throw new Error("Can't retract message without a XEP-0359 Origin ID");
}
const editable = message.get('editable');
const stanza = $msg({
'id': getUniqueId(),
'to': this.get('jid'),
'type': 'groupchat'
}).c('store', {
xmlns: core.NS.HINTS
}).up().c('apply-to', {
'id': origin_id,
'xmlns': core.NS.FASTEN
}).c('retract', {
xmlns: core.NS.RETRACT
});
// Optimistic save
message.set({
'retracted': new Date().toISOString(),
'retracted_id': origin_id,
'retraction_id': stanza.tree().getAttribute('id'),
'editable': false
});
const result = await this.sendTimedMessage(stanza);
if (muc_u.isErrorStanza(result)) {
log.error(result);
} else if (result instanceof TimeoutError) {
log.error(result);
message.save({
editable,
'error_type': 'timeout',
'error': __('A timeout happened while while trying to retract your message.'),
'retracted': undefined,
'retracted_id': undefined,
'retraction_id': undefined
});
}
},
/**
* Retract someone else's message in this groupchat.
* @private
* @method _converse.ChatRoom#retractOtherMessage
* @param { _converse.ChatRoomMessage } message - The message which we're retracting.
* @param { string } [reason] - The reason for retracting the message.
* @example
* const room = await api.rooms.get(jid);
* const message = room.messages.findWhere({'body': 'Get rich quick!'});
* room.retractOtherMessage(message, 'spam');
*/
async retractOtherMessage(message, reason) {
const editable = message.get('editable');
// Optimistic save
message.save({
'moderated': 'retracted',
'moderated_by': shared_converse.bare_jid,
'moderated_id': message.get('msgid'),
'moderation_reason': reason,
'editable': false
});
const result = await this.sendRetractionIQ(message, reason);
if (result === null || muc_u.isErrorStanza(result)) {
// Undo the save if something went wrong
message.save({
editable,
'moderated': undefined,
'moderated_by': undefined,
'moderated_id': undefined,
'moderation_reason': undefined
});
}
return result;
},
/**
* Sends an IQ stanza to the XMPP server to retract a message in this groupchat.
* @private
* @method _converse.ChatRoom#sendRetractionIQ
* @param { _converse.ChatRoomMessage } message - The message which we're retracting.
* @param { string } [reason] - The reason for retracting the message.
*/
sendRetractionIQ(message, reason) {
const iq = $iq({
'to': this.get('jid'),
'type': 'set'
}).c('apply-to', {
'id': message.get(`stanza_id ${this.get('jid')}`),
'xmlns': core.NS.FASTEN
}).c('moderate', {
xmlns: core.NS.MODERATE
}).c('retract', {
xmlns: core.NS.RETRACT
}).up().c('reason').t(reason || '');
return shared_api.sendIQ(iq, null, false);
},
/**
* Sends an IQ stanza to the XMPP server to destroy this groupchat. Not
* to be confused with the {@link _converse.ChatRoom#destroy}
* method, which simply removes the room from the local browser storage cache.
* @private
* @method _converse.ChatRoom#sendDestroyIQ
* @param { string } [reason] - The reason for destroying the groupchat.
* @param { string } [new_jid] - The JID of the new groupchat which replaces this one.
*/
sendDestroyIQ(reason, new_jid) {
const destroy = $build('destroy');
if (new_jid) {
destroy.attrs({
'jid': new_jid
});
}
const iq = $iq({
'to': this.get('jid'),
'type': 'set'
}).c('query', {
'xmlns': core.NS.MUC_OWNER
}).cnode(destroy.node);
if (reason && reason.length > 0) {
iq.c('reason', reason);
}
return shared_api.sendIQ(iq);
},
/**
* Leave the groupchat.
* @private
* @method _converse.ChatRoom#leave
* @param { string } [exit_msg] - Message to indicate your reason for leaving
*/
async leave(exit_msg) {
shared_api.connection.connected() && shared_api.user.presence.send('unavailable', this.getRoomJIDAndNick(), exit_msg);
// Delete the features model
if (this.features) {
await new Promise(resolve => this.features.destroy({
'success': resolve,
'error': (_, e) => {
log.error(e);
resolve();
}
}));
}
// Delete disco entity
const disco_entity = shared_converse.disco_entities?.get(this.get('jid'));
if (disco_entity) {
await new Promise(resolve => disco_entity.destroy({
'success': resolve,
'error': (_, e) => {
log.error(e);
resolve();
}
}));
}
safeSave(this.session, {
'connection_status': ROOMSTATUS.DISCONNECTED
});
},
async close(ev) {
const {
ENTERED,
CLOSING
} = ROOMSTATUS;
const was_entered = this.session.get('connection_status') === ENTERED;
safeSave(this.session, {
'connection_status': CLOSING
});
was_entered && this.sendMarkerForLastMessage('received', true);
await this.unregisterNickname();
await this.leave();
this.occupants.clearStore();
if (ev?.name !== 'closeAllChatBoxes' && shared_api.settings.get('muc_clear_messages_on_leave')) {
this.clearMessages();
}
// Delete the session model
await new Promise(resolve => this.session.destroy({
'success': resolve,
'error': (_, e) => {
log.error(e);
resolve();
}
}));
return shared_converse.ChatBox.prototype.close.call(this);
},
canModerateMessages() {
const self = this.getOwnOccupant();
return self && self.isModerator() && shared_api.disco.supports(core.NS.MODERATE, this.get('jid'));
},
/**
* Return an array of unique nicknames based on all occupants and messages in this MUC.
* @private
* @method _converse.ChatRoom#getAllKnownNicknames
* @returns { String[] }
*/
getAllKnownNicknames() {
return [...new Set([...this.occupants.map(o => o.get('nick')), ...this.messages.map(m => m.get('nick'))])].filter(n => n);
},
getAllKnownNicknamesRegex() {
const longNickString = this.getAllKnownNicknames().map(n => parse_helpers.escapeRegexString(n)).join('|');
return RegExp(`(?:\\p{P}|\\p{Z}|^)@(${longNickString})(?![\\w@-])`, 'uig');
},
getOccupantByJID(jid) {
return this.occupants.findOccupant({
jid
});
},
getOccupantByNickname(nick) {
return this.occupants.findOccupant({
nick
});
},
getReferenceURIFromNickname(nickname) {
const muc_jid = this.get('jid');
const occupant = this.getOccupant(nickname);
const uri = this.features.get('nonanonymous') && occupant?.get('jid') || `${muc_jid}/${nickname}`;
return encodeURI(`xmpp:${uri}`);
},
/**
* Given a text message, look for `@` mentions and turn them into
* XEP-0372 references
* @param { String } text
*/
parseTextForReferences(text) {
const mentions_regex = /(\p{P}|\p{Z}|^)([@][\w_-]+(?:\.\w+)*)/giu;
if (!text || !mentions_regex.test(text)) {
return [text, []];
}
const getMatchingNickname = parse_helpers.findFirstMatchInArray(this.getAllKnownNicknames());
const matchToReference = match => {
let at_sign_index = match[0].indexOf('@');
if (match[0][at_sign_index + 1] === '@') {
// edge-case
at_sign_index += 1;
}
const begin = match.index + at_sign_index;
const end = begin + match[0].length - at_sign_index;
const value = getMatchingNickname(match[1]);
const type = 'mention';
const uri = this.getReferenceURIFromNickname(value);
return {
begin,
end,
value,
type,
uri
};
};
const regex = this.getAllKnownNicknamesRegex();
const mentions = [...text.matchAll(regex)].filter(m => !m[0].startsWith('/'));
const references = mentions.map(matchToReference);
const [updated_message, updated_references] = parse_helpers.reduceTextFromReferences(text, references);
return [updated_message, updated_references];
},
async getOutgoingMessageAttributes(attrs) {
await shared_api.emojis.initialize();
const is_spoiler = this.get('composing_spoiler');
let text = '',
references;
if (attrs?.body) {
[text, references] = this.parseTextForReferences(attrs.body);
}
const origin_id = getUniqueId();
const body = text ? muc_u.shortnamesToUnicode(text) : undefined;
attrs = Object.assign({}, attrs, {
body,
is_spoiler,
origin_id,
references,
'id': origin_id,
'msgid': origin_id,
'from': `${this.get('jid')}/${this.get('nick')}`,
'fullname': this.get('nick'),
'is_only_emojis': text ? muc_u.isOnlyEmojis(text) : false,
'message': body,
'nick': this.get('nick'),
'sender': 'me',
'type': 'groupchat'
}, getMediaURLsMetadata(text));
/**
* *Hook* which allows plugins to update the attributes of an outgoing
* message.
* @event _converse#getOutgoingMessageAttributes
*/
attrs = await shared_api.hook('getOutgoingMessageAttributes', this, attrs);
return attrs;
},
/**
* Utility method to construct the JID for the current user as occupant of the groupchat.
* @private
* @method _converse.ChatRoom#getRoomJIDAndNick
* @returns {string} - The groupchat JID with the user's nickname added at the end.
* @example groupchat@conference.example.org/nickname
*/
getRoomJIDAndNick() {
const nick = this.get('nick');
const jid = core.getBareJidFromJid(this.get('jid'));
return jid + (nick !== null ? `/${nick}` : '');
},
/**
* Sends a message with the current XEP-0085 chat state of the user
* as taken from the `chat_state` attribute of the {@link _converse.ChatRoom}.
* @private
* @method _converse.ChatRoom#sendChatState
*/
sendChatState() {
if (!shared_api.settings.get('send_chat_state_notifications') || !this.get('chat_state') || !this.isEntered() || this.features.get('moderated') && this.getOwnRole() === 'visitor') {
return;
}
const allowed = shared_api.settings.get('send_chat_state_notifications');
if (Array.isArray(allowed) && !allowed.includes(this.get('chat_state'))) {
return;
}
const chat_state = this.get('chat_state');
if (chat_state === shared_converse.GONE) {
// <gone/> is not applicable within MUC context
return;
}
shared_api.send($msg({
'to': this.get('jid'),
'type': 'groupchat'
}).c(chat_state, {
'xmlns': core.NS.CHATSTATES
}).up().c('no-store', {
'xmlns': core.NS.HINTS
}).up().c('no-permanent-store', {
'xmlns': core.NS.HINTS
}));
},
/**
* Send a direct invitation as per XEP-0249
* @private
* @method _converse.ChatRoom#directInvite
* @param { String } recipient - JID of the person being invited
* @param { String } [reason] - Reason for the invitation
*/
directInvite(recipient, reason) {
if (this.features.get('membersonly')) {
// When inviting to a members-only groupchat, we first add
// the person to the member list by giving them an
// affiliation of 'member' otherwise they won't be able to join.
this.updateMemberLists([{
'jid': recipient,
'affiliation': 'member',
'reason': reason
}]);
}
const attrs = {
'xmlns': 'jabber:x:conference',
'jid': this.get('jid')
};
if (reason !== null) {
attrs.reason = reason;
}
if (this.get('password')) {
attrs.password = this.get('password');
}
const invitation = $msg({
'from': shared_converse.connection.jid,
'to': recipient,
'id': getUniqueId()
}).c('x', attrs);
shared_api.send(invitation);
/**
* After the user has sent out a direct invitation (as per XEP-0249),
* to a roster contact, asking them to join a room.
* @event _converse#chatBoxMaximized
* @type {object}
* @property {_converse.ChatRoom} room
* @property {string} recipient - The JID of the person being invited
* @property {string} reason - The original reason for the invitation
* @example _converse.api.listen.on('chatBoxMaximized', view => { ... });
*/
shared_api.trigger('roomInviteSent', {
'room': this,
'recipient': recipient,
'reason': reason
});
},
/**
* Refresh the disco identity, features and fields for this {@link _converse.ChatRoom}.
* *features* are stored on the features {@link Model} attribute on this {@link _converse.ChatRoom}.
* *fields* are stored on the config {@link Model} attribute on this {@link _converse.ChatRoom}.
* @private
* @returns {Promise}
*/
refreshDiscoInfo() {
return shared_api.disco.refresh(this.get('jid')).then(() => this.getDiscoInfo()).catch(e => log.error(e));
},
/**
* Fetch the *extended* MUC info from the server and cache it locally
* https://xmpp.org/extensions/xep-0045.html#disco-roominfo
* @private
* @method _converse.ChatRoom#getDiscoInfo
* @returns {Promise}
*/
getDiscoInfo() {
return shared_api.disco.getIdentity('conference', 'text', this.get('jid')).then(identity => this.save({
'name': identity?.get('name')
})).then(() => this.getDiscoInfoFields()).then(() => this.getDiscoInfoFeatures()).catch(e => log.error(e));
},
/**
* Fetch the *extended* MUC info fields from the server and store them locally
* in the `config` {@link Model} attribute.
* See: https://xmpp.org/extensions/xep-0045.html#disco-roominfo
* @private
* @method _converse.ChatRoom#getDiscoInfoFields
* @returns {Promise}
*/
async getDiscoInfoFields() {
const fields = await shared_api.disco.getFields(this.get('jid'));
const config = fields.reduce((config, f) => {
const name = f.get('var');
if (name?.startsWith('muc#roominfo_')) {
config[name.replace('muc#roominfo_', '')] = f.get('value');
}
return config;
}, {});
this.config.save(config);
},
/**
* Use converse-disco to populate the features {@link Model} which
* is stored as an attibute on this {@link _converse.ChatRoom}.
* The results may be cached. If you want to force fetching the features from the
* server, call {@link _converse.ChatRoom#refreshDiscoInfo} instead.
* @private
* @returns {Promise}
*/
async getDiscoInfoFeatures() {
const features = await shared_api.disco.getFeatures(this.get('jid'));
const attrs = converse.ROOM_FEATURES.reduce((acc, feature) => {
acc[feature] = false;
return acc;
}, {
'fetched': new Date().toISOString()
});
features.each(feature => {
const fieldname = feature.get('var');
if (!fieldname.startsWith('muc_')) {
if (fieldname === core.NS.MAM) {
attrs.mam_enabled = true;
} else {
attrs[fieldname] = true;
}
return;
}
attrs[fieldname.replace('muc_', '')] = true;
});
this.features.save(attrs);
},
/**
* Given a <field> element, return a copy with a <value> child if
* we can find a value for it in this rooms config.
* @private
* @method _converse.ChatRoom#addFieldValue
* @returns { Element }
*/
addFieldValue(field) {
const type = field.getAttribute('type');
if (type === 'fixed') {
return field;
}
const fieldname = field.getAttribute('var').replace('muc#roomconfig_', '');
const config = this.get('roomconfig');
if (fieldname in config) {
let values;
switch (type) {
case 'boolean':
values = [config[fieldname] ? 1 : 0];
break;
case 'list-multi':
values = config[fieldname];
break;
default:
values = [config[fieldname]];
}
field.innerHTML = values.map(v => $build('value').t(v)).join('');
}
return field;
},
/**
* Automatically configure the groupchat based on this model's
* 'roomconfig' data.
* @private
* @method _converse.ChatRoom#autoConfigureChatRoom
* @returns { Promise<Element> }
* Returns a promise which resolves once a response IQ has
* been received.
*/
async autoConfigureChatRoom() {
const stanza = await this.fetchRoomConfiguration();
const fields = sizzle_default()('field', stanza);
const configArray = fields.map(f => this.addFieldValue(f));
if (configArray.length) {
return this.sendConfiguration(configArray);
}
},
/**
* Send an IQ stanza to fetch the groupchat configuration data.
* Returns a promise which resolves once the response IQ
* has been received.
* @private
* @method _converse.ChatRoom#fetchRoomConfiguration
* @returns { Promise<Element> }
*/
fetchRoomConfiguration() {
return shared_api.sendIQ($iq({
'to': this.get('jid'),
'type': 'get'
}).c('query', {
xmlns: core.NS.MUC_OWNER
}));
},
/**
* Sends an IQ stanza with the groupchat configuration.
* @private
* @method _converse.ChatRoom#sendConfiguration
* @param { Array } config - The groupchat configuration
* @returns { Promise<Element> } - A promise which resolves with
* the `result` stanza received from the XMPP server.
*/
sendConfiguration() {
let config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
const iq = $iq({
to: this.get('jid'),
type: 'set'
}).c('query', {
xmlns: core.NS.MUC_OWNER
}).c('x', {
xmlns: core.NS.XFORM,
type: 'submit'
});
config.forEach(node => iq.cnode(node).up());
return shared_api.sendIQ(iq);
},
onCommandError(err) {
const {
__
} = shared_converse;
log.fatal(err);
const message = __('Sorry, an error happened while running the command.') + ' ' + __("Check your browser's developer console for details.");
this.createMessage({
message,
'type': 'error'
});
},
getNickOrJIDFromCommandArgs(args) {
const {
__
} = shared_converse;
if (muc_u.isValidJID(args.trim())) {
return args.trim();
}
if (!args.startsWith('@')) {
args = '@' + args;
}
const [_text, references] = this.parseTextForReferences(args); // eslint-disable-line no-unused-vars
if (!references.length) {
const message = __("Error: couldn't find a groupchat participant based on your arguments");
this.createMessage({
message,
'type': 'error'
});
return;
}
if (references.length > 1) {
const message = __('Error: found multiple groupchat participant based on your arguments');
this.createMessage({
message,
'type': 'error'
});
return;
}
const nick_or_jid = references.pop().value;
const reason = args.split(nick_or_jid, 2)[1];
if (reason && !reason.startsWith(' ')) {
const message = __("Error: couldn't find a groupchat participant based on your arguments");
this.createMessage({
message,
'type': 'error'
});
return;
}
return nick_or_jid;
},
validateRoleOrAffiliationChangeArgs(command, args) {
const {
__
} = shared_converse;
if (!args) {
const message = __('Error: the "%1$s" command takes two arguments, the user\'s nickname and optionally a reason.', command);
this.createMessage({
message,
'type': 'error'
});
return false;
}
return true;
},
getAllowedCommands() {
let allowed_commands = ['clear', 'help', 'me', 'nick', 'register'];
if (this.config.get('changesubject') || ['owner', 'admin'].includes(this.getOwnAffiliation())) {
allowed_commands = [...allowed_commands, ...['subject', 'topic']];
}
const occupant = this.occupants.findWhere({
'jid': shared_converse.bare_jid
});
if (this.verifyAffiliations(['owner'], occupant, false)) {
allowed_commands = allowed_commands.concat(OWNER_COMMANDS).concat(ADMIN_COMMANDS);
} else if (this.verifyAffiliations(['admin'], occupant, false)) {
allowed_commands = allowed_commands.concat(ADMIN_COMMANDS);
}
if (this.verifyRoles(['moderator'], occupant, false)) {
allowed_commands = allowed_commands.concat(MODERATOR_COMMANDS).concat(VISITOR_COMMANDS);
} else if (!this.verifyRoles(['visitor', 'participant', 'moderator'], occupant, false)) {
allowed_commands = allowed_commands.concat(VISITOR_COMMANDS);
}
allowed_commands.sort();
if (Array.isArray(shared_api.settings.get('muc_disable_slash_commands'))) {
return allowed_commands.filter(c => !shared_api.settings.get('muc_disable_slash_commands').includes(c));
} else {
return allowed_commands;
}
},
verifyAffiliations(affiliations, occupant) {
let show_error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
const {
__
} = shared_converse;
if (!Array.isArray(affiliations)) {
throw new TypeError('affiliations must be an Array');
}
if (!affiliations.length) {
return true;
}
occupant = occupant || this.occupants.findWhere({
'jid': shared_converse.bare_jid
});
if (occupant) {
const a = occupant.get('affiliation');
if (affiliations.includes(a)) {
return true;
}
}
if (show_error) {
const message = __('Forbidden: you do not have the necessary affiliation in order to do that.');
this.createMessage({
message,
'type': 'error'
});
}
return false;
},
verifyRoles(roles, occupant) {
let show_error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
const {
__
} = shared_converse;
if (!Array.isArray(roles)) {
throw new TypeError('roles must be an Array');
}
if (!roles.length) {
return true;
}
occupant = occupant || this.occupants.findWhere({
'jid': shared_converse.bare_jid
});
if (occupant) {
const role = occupant.get('role');
if (roles.includes(role)) {
return true;
}
}
if (show_error) {
const message = __('Forbidden: you do not have the necessary role in order to do that.');
this.createMessage({
message,
'type': 'error',
'is_ephemeral': 20000
});
}
return false;
},
/**
* Returns the `role` which the current user has in this MUC
* @private
* @method _converse.ChatRoom#getOwnRole
* @returns { ('none'|'visitor'|'participant'|'moderator') }
*/
getOwnRole() {
return this.getOwnOccupant()?.attributes?.role;
},
/**
* Returns the `affiliation` which the current user has in this MUC
* @private
* @method _converse.ChatRoom#getOwnAffiliation
* @returns { ('none'|'outcast'|'member'|'admin'|'owner') }
*/
getOwnAffiliation() {
return this.getOwnOccupant()?.attributes?.affiliation || 'none';
},
/**
* Get the {@link _converse.ChatRoomOccupant} instance which
* represents the current user.
* @method _converse.ChatRoom#getOwnOccupant
* @returns { _converse.ChatRoomOccupant }
*/
getOwnOccupant() {
return this.occupants.getOwnOccupant();
},
/**
* Send a presence stanza to update the user's nickname in this MUC.
* @param { String } nick
*/
async setNickname(nick) {
if (shared_api.settings.get('auto_register_muc_nickname') && (await shared_api.disco.supports(core.NS.MUC_REGISTER, this.get('jid')))) {
const old_nick = this.get('nick');
this.set({
nick
});
try {
await this.registerNickname();
} catch (e) {
const {
__
} = shared_converse;
log.error(e);
const message = __("Error: couldn't register new nickname in members only room");
this.createMessage({
message,
'type': 'error',
'is_ephemeral': true
});
this.set({
'nick': old_nick
});
return;
}
}
const jid = core.getBareJidFromJid(this.get('jid'));
shared_api.send($pres({
'from': shared_converse.connection.jid,
'to': `${jid}/${nick}`,
'id': getUniqueId()
}).tree());
},
/**
* Send an IQ stanza to modify an occupant's role
* @private
* @method _converse.ChatRoom#setRole
* @param { _converse.ChatRoomOccupant } occupant
* @param { String } role
* @param { String } reason
* @param { function } onSuccess - callback for a succesful response
* @param { function } onError - callback for an error response
*/
setRole(occupant, role, reason, onSuccess, onError) {
const item = $build('item', {
'nick': occupant.get('nick'),
role
});
const iq = $iq({
'to': this.get('jid'),
'type': 'set'
}).c('query', {
xmlns: core.NS.MUC_ADMIN
}).cnode(item.node);
if (reason !== null) {
iq.c('reason', reason);
}
return shared_api.sendIQ(iq).then(onSuccess).catch(onError);
},
/**
* @private
* @method _converse.ChatRoom#getOccupant
* @param { String } nickname_or_jid - The nickname or JID of the occupant to be returned
* @returns { _converse.ChatRoomOccupant }
*/
getOccupant(nickname_or_jid) {
return muc_u.isValidJID(nickname_or_jid) ? this.getOccupantByJID(nickname_or_jid) : this.getOccupantByNickname(nickname_or_jid);
},
/**
* Return an array of occupant models that have the required role
* @private
* @method _converse.ChatRoom#getOccupantsWithRole
* @param { String } role
* @returns { _converse.ChatRoomOccupant[] }
*/
getOccupantsWithRole(role) {
return this.getOccupantsSortedBy('nick').filter(o => o.get('role') === role).map(item => {
return {
'jid': item.get('jid'),
'nick': item.get('nick'),
'role': item.get('role')
};
});
},
/**
* Return an array of occupant models that have the required affiliation
* @private
* @method _converse.ChatRoom#getOccupantsWithAffiliation
* @param { String } affiliation
* @returns { _converse.ChatRoomOccupant[] }
*/
getOccupantsWithAffiliation(affiliation) {
return this.getOccupantsSortedBy('nick').filter(o => o.get('affiliation') === affiliation).map(item => {
return {
'jid': item.get('jid'),
'nick': item.get('nick'),
'affiliation': item.get('affiliation')
};
});
},
/**
* Return an array of occupant models, sorted according to the passed-in attribute.
* @private
* @method _converse.ChatRoom#getOccupantsSortedBy
* @param { String } attr - The attribute to sort the returned array by
* @returns { _converse.ChatRoomOccupant[] }
*/
getOccupantsSortedBy(attr) {
return Array.from(this.occupants.models).sort((a, b) => a.get(attr) < b.get(attr) ? -1 : a.get(attr) > b.get(attr) ? 1 : 0);
},
/**
* Fetch the lists of users with the given affiliations.
* Then compute the delta between those users and
* the passed in members, and if it exists, send the delta
* to the XMPP server to update the member list.
* @private
* @method _converse.ChatRoom#updateMemberLists
* @param { object } members - Map of member jids and affiliations.
* @returns { Promise }
* A promise which is resolved once the list has been
* updated or once it's been established there's no need
* to update the list.
*/
async updateMemberLists(members) {
const muc_jid = this.get('jid');
const all_affiliations = ['member', 'admin', 'owner'];
const aff_lists = await Promise.all(all_affiliations.map(a => getAffiliationList(a, muc_jid)));
const old_members = aff_lists.reduce((acc, val) => muc_u.isErrorObject(val) ? acc : [...val, ...acc], []);
await setAffiliations(muc_jid, computeAffiliationsDelta(true, false, members, old_members));
await this.occupants.fetchMembers();
},
/**
* Given a nick name, save it to the model state, otherwise, look
* for a server-side reserved nickname or default configured
* nickname and if found, persist that to the model state.
* @private
* @method _converse.ChatRoom#getAndPersistNickname
* @returns { Promise<string> } A promise which resolves with the nickname
*/
async getAndPersistNickname(nick) {
nick = nick || this.get('nick') || (await this.getReservedNick()) || shared_converse.getDefaultMUCNickname();
if (nick) safeSave(this, {
nick
}, {
'silent': true
});
return nick;
},
/**
* Use service-discovery to ask the XMPP server whether
* this user has a reserved nickname for this groupchat.
* If so, we'll use that, otherwise we render the nickname form.
* @private
* @method _converse.ChatRoom#getReservedNick
* @returns { Promise<string> } A promise which resolves with the reserved nick or null
*/
async getReservedNick() {
const stanza = $iq({
'to': this.get('jid'),
'from': shared_converse.connection.jid,
'type': 'get'
}).c('query', {
'xmlns': core.NS.DISCO_INFO,
'node': 'x-roomuser-item'
});
const result = await shared_api.sendIQ(stanza, null, false);
if (muc_u.isErrorObject(result)) {
throw result;
}
// Result might be undefined due to a timeout
const identity_el = result?.querySelector('query[node="x-roomuser-item"] identity');
return identity_el ? identity_el.getAttribute('name') : null;
},
/**
* Send an IQ stanza to the MUC to register this user's nickname.
* This sets the user's affiliation to 'member' (if they weren't affiliated
* before) and reserves the nickname for this user, thereby preventing other
* users from using it in this MUC.
* See https://xmpp.org/extensions/xep-0045.html#register
* @private
* @method _converse.ChatRoom#registerNickname
*/
async registerNickname() {
const {
__
} = shared_converse;
const nick = this.get('nick');
const jid = this.get('jid');
let iq, err_msg;
try {
iq = await shared_api.sendIQ($iq({
'to': jid,
'type': 'get'
}).c('query', {
'xmlns': core.NS.MUC_REGISTER
}));
} catch (e) {
if (sizzle_default()(`not-allowed[xmlns="${core.NS.STANZAS}"]`, e).length) {
err_msg = __("You're not allowed to register yourself in this groupchat.");
} else if (sizzle_default()(`registration-required[xmlns="${core.NS.STANZAS}"]`, e).length) {
err_msg = __("You're not allowed to register in this groupchat because it's members-only.");
}
log.error(e);
return err_msg;
}
const required_fields = sizzle_default()('field required', iq).map(f => f.parentElement);
if (required_fields.length > 1 && required_fields[0].getAttribute('var') !== 'muc#register_roomnick') {
return log.error(`Can't register the user register in the groupchat ${jid} due to the required fields`);
}
try {
await shared_api.sendIQ($iq({
'to': jid,
'type': 'set'
}).c('query', {
'xmlns': core.NS.MUC_REGISTER
}).c('x', {
'xmlns': core.NS.XFORM,
'type': 'submit'
}).c('field', {
'var': 'FORM_TYPE'
}).c('value').t('http://jabber.org/protocol/muc#register').up().up().c('field', {
'var': 'muc#register_roomnick'
}).c('value').t(nick));
} catch (e) {
if (sizzle_default()(`service-unavailable[xmlns="${core.NS.STANZAS}"]`, e).length) {
err_msg = __("Can't register your nickname in this groupchat, it doesn't support registration.");
} else if (sizzle_default()(`bad-request[xmlns="${core.NS.STANZAS}"]`, e).length) {
err_msg = __("Can't register your nickname in this groupchat, invalid data form supplied.");
}
log.error(err_msg);
log.error(e);
return err_msg;
}
},
/**
* Check whether we should unregister the user from this MUC, and if so,
* call { @link _converse.ChatRoom#sendUnregistrationIQ }
* @method _converse.ChatRoom#unregisterNickname
*/
async unregisterNickname() {
if (shared_api.settings.get('auto_register_muc_nickname') === 'unregister') {
try {
if (await shared_api.disco.supports(core.NS.MUC_REGISTER, this.get('jid'))) {
await this.sendUnregistrationIQ();
}
} catch (e) {
log.error(e);
}
}
},
/**
* Send an IQ stanza to the MUC to unregister this user's nickname.
* If the user had a 'member' affiliation, it'll be removed and their
* nickname will no longer be reserved and can instead be used (and
* registered) by other users.
* @method _converse.ChatRoom#sendUnregistrationIQ
*/
sendUnregistrationIQ() {
const iq = $iq({
'to': this.get('jid'),
'type': 'set'
}).c('query', {
'xmlns': core.NS.MUC_REGISTER
}).c('remove');
return shared_api.sendIQ(iq).catch(e => log.error(e));
},
/**
* Given a presence stanza, update the occupant model based on its contents.
* @private
* @method _converse.ChatRoom#updateOccupantsOnPresence
* @param { Element } pres - The presence stanza
*/
updateOccupantsOnPresence(pres) {
const data = parseMUCPresence(pres, this);
if (data.type === 'error' || !data.jid && !data.nick && !data.occupant_id) {
return true;
}
const occupant = this.occupants.findOccupant(data);
// Destroy an unavailable occupant if this isn't a nick change operation and if they're not affiliated
if (data.type === 'unavailable' && occupant && !data.states.includes(converse.MUC_NICK_CHANGED_CODE) && !['admin', 'owner', 'member'].includes(data['affiliation'])) {
// Before destroying we set the new data, so that we can show the disconnection message
occupant.set(data);
occupant.destroy();
return;
}
const jid = data.jid || '';
const attributes = {
...data,
'jid': core.getBareJidFromJid(jid) || occupant?.attributes?.jid,
'resource': core.getResourceFromJid(jid) || occupant?.attributes?.resource
};
if (data.is_me) {
let modified = false;
if (data.states.includes(converse.MUC_NICK_CHANGED_CODE)) {
modified = true;
this.set('nick', data.nick);
}
if (this.features.get(core.NS.OCCUPANTID) && this.get('occupant-id') !== data.occupant_id) {
modified = true;
this.set('occupant_id', data.occupant_id);
}
modified && this.save();
}
if (occupant) {
occupant.save(attributes);
} else {
this.occupants.create(attributes);
}
},
fetchFeaturesIfConfigurationChanged(stanza) {
// 104: configuration change
// 170: logging enabled
// 171: logging disabled
// 172: room no longer anonymous
// 173: room now semi-anonymous
// 174: room now fully anonymous
const codes = ['104', '170', '171', '172', '173', '174'];
if (sizzle_default()('status', stanza).filter(e => codes.includes(e.getAttribute('status'))).length) {
this.refreshDiscoInfo();
}
},
/**
* Given two JIDs, which can be either user JIDs or MUC occupant JIDs,
* determine whether they belong to the same user.
* @private
* @method _converse.ChatRoom#isSameUser
* @param { String } jid1
* @param { String } jid2
* @returns { Boolean }
*/
isSameUser(jid1, jid2) {
const bare_jid1 = core.getBareJidFromJid(jid1);
const bare_jid2 = core.getBareJidFromJid(jid2);
const resource1 = core.getResourceFromJid(jid1);
const resource2 = core.getResourceFromJid(jid2);
if (muc_u.isSameBareJID(jid1, jid2)) {
if (bare_jid1 === this.get('jid')) {
// MUC JIDs
return resource1 === resource2;
} else {
return true;
}
} else {
const occupant1 = bare_jid1 === this.get('jid') ? this.occupants.findOccupant({
'nick': resource1
}) : this.occupants.findOccupant({
'jid': bare_jid1
});
const occupant2 = bare_jid2 === this.get('jid') ? this.occupants.findOccupant({
'nick': resource2
}) : this.occupants.findOccupant({
'jid': bare_jid2
});
return occupant1 === occupant2;
}
},
async isSubjectHidden() {
const jids = await shared_api.user.settings.get('mucs_with_hidden_subject', []);
return jids.includes(this.get('jid'));
},
async toggleSubjectHiddenState() {
const muc_jid = this.get('jid');
const jids = await shared_api.user.settings.get('mucs_with_hidden_subject', []);
if (jids.includes(this.get('jid'))) {
shared_api.user.settings.set('mucs_with_hidden_subject', jids.filter(jid => jid !== muc_jid));
} else {
shared_api.user.settings.set('mucs_with_hidden_subject', [...jids, muc_jid]);
}
},
/**
* Handle a possible subject change and return `true` if so.
* @private
* @method _converse.ChatRoom#handleSubjectChange
* @param { object } attrs - Attributes representing a received
* message, as returned by {@link parseMUCMessage}
*/
async handleSubjectChange(attrs) {
const __ = shared_converse.__;
if (typeof attrs.subject === 'string' && !attrs.thread && !attrs.message) {
// https://xmpp.org/extensions/xep-0045.html#subject-mod
// -----------------------------------------------------
// The subject is changed by sending a message of type "groupchat" to the <room@service>,
// where the <message/> MUST contain a <subject/> element that specifies the new subject but
// MUST NOT contain a <body/> element (or a <thread/> element).
const subject = attrs.subject;
const author = attrs.nick;
safeSave(this, {
'subject': {
author,
'text': attrs.subject || ''
}
});
if (!attrs.is_delayed && author) {
const message = subject ? __('Topic set by %1$s', author) : __('Topic cleared by %1$s', author);
const prev_msg = this.messages.last();
if (prev_msg?.get('nick') !== attrs.nick || prev_msg?.get('type') !== 'info' || prev_msg?.get('message') !== message) {
this.createMessage({
message,
'nick': attrs.nick,
'type': 'info',
'is_ephemeral': true
});
}
if (await this.isSubjectHidden()) {
this.toggleSubjectHiddenState();
}
}
return true;
}
return false;
},
/**
* Set the subject for this {@link _converse.ChatRoom}
* @private
* @method _converse.ChatRoom#setSubject
* @param { String } value
*/
setSubject() {
let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
shared_api.send($msg({
to: this.get('jid'),
from: shared_converse.connection.jid,
type: 'groupchat'
}).c('subject', {
xmlns: 'jabber:client'
}).t(value).tree());
},
/**
* Is this a chat state notification that can be ignored,
* because it's old or because it's from us.
* @private
* @method _converse.ChatRoom#ignorableCSN
* @param { Object } attrs - The message attributes
*/
ignorableCSN(attrs) {
return attrs.chat_state && !attrs.body && (attrs.is_delayed || this.isOwnMessage(attrs));
},
/**
* Determines whether the message is from ourselves by checking
* the `from` attribute. Doesn't check the `type` attribute.
* @private
* @method _converse.ChatRoom#isOwnMessage
* @param { Object|Element|_converse.Message } msg
* @returns { boolean }
*/
isOwnMessage(msg) {
let from;
if (lodash_es_isElement(msg)) {
from = msg.getAttribute('from');
} else if (msg instanceof shared_converse.Message) {
from = msg.get('from');
} else {
from = msg.from;
}
return core.getResourceFromJid(from) == this.get('nick');
},
getUpdatedMessageAttributes(message, attrs) {
const new_attrs = {
...shared_converse.ChatBox.prototype.getUpdatedMessageAttributes.call(this, message, attrs),
...lodash_es_pick(attrs, ['from_muc', 'occupant_id'])
};
if (this.isOwnMessage(attrs)) {
const stanza_id_keys = Object.keys(attrs).filter(k => k.startsWith('stanza_id'));
Object.assign(new_attrs, lodash_es_pick(attrs, stanza_id_keys));
if (!message.get('received')) {
new_attrs.received = new Date().toISOString();
}
}
return new_attrs;
},
/**
* Send a MUC-0410 MUC Self-Ping stanza to room to determine
* whether we're still joined.
* @async
* @private
* @method _converse.ChatRoom#isJoined
* @returns {Promise<boolean>}
*/
async isJoined() {
if (!this.isEntered()) {
log.info(`isJoined: not pinging MUC ${this.get('jid')} since we're not entered`);
return false;
}
if (!shared_api.connection.connected()) {
await new Promise(resolve => shared_api.listen.once('reconnected', resolve));
}
return shared_api.ping(`${this.get('jid')}/${this.get('nick')}`);
},
/**
* Sends a status update presence (i.e. based on the `<show>` element)
* @method _converse.ChatRoom#sendStatusPresence
* @param { String } type
* @param { String } [status] - An optional status message
* @param { Element[]|Strophe.Builder[]|Element|Strophe.Builder } [child_nodes]
* Nodes(s) to be added as child nodes of the `presence` XML element.
*/
async sendStatusPresence(type, status, child_nodes) {
if (this.session.get('connection_status') === ROOMSTATUS.ENTERED) {
const presence = await shared_converse.xmppstatus.constructPresence(type, this.getRoomJIDAndNick(), status);
child_nodes?.map(c => c?.tree() ?? c).forEach(c => presence.cnode(c).up());
shared_api.send(presence);
}
},
/**
* Check whether we're still joined and re-join if not
* @method _converse.ChatRoom#rejoinIfNecessary
*/
async rejoinIfNecessary() {
if (this.isRAICandidate()) {
log.debug(`rejoinIfNecessary: not rejoining hidden MUC "${this.get('jid')}" since we're using RAI`);
return true;
}
if (!(await this.isJoined())) {
this.rejoin();
return true;
}
},
/**
* @private
* @method _converse.ChatRoom#shouldShowErrorMessage
* @returns {Promise<boolean>}
*/
async shouldShowErrorMessage(attrs) {
if (attrs.error_type === 'Decryption') {
if (attrs.error_message === "Message key not found. The counter was repeated or the key was not filled.") {
// OMEMO message which we already decrypted before
return false;
} else if (attrs.error_condition === 'not-encrypted-for-this-device') {
return false;
}
} else if (attrs.error_condition === 'not-acceptable' && (await this.rejoinIfNecessary())) {
return false;
}
return shared_converse.ChatBox.prototype.shouldShowErrorMessage.call(this, attrs);
},
/**
* Looks whether we already have a moderation message for this
* incoming message. If so, it's considered "dangling" because
* it probably hasn't been applied to anything yet, given that
* the relevant message is only coming in now.
* @private
* @method _converse.ChatRoom#findDanglingModeration
* @param { object } attrs - Attributes representing a received
* message, as returned by {@link parseMUCMessage}
* @returns { _converse.ChatRoomMessage }
*/
findDanglingModeration(attrs) {
if (!this.messages.length) {
return null;
}
// Only look for dangling moderation if there are newer
// messages than this one, since moderation come after.
if (this.messages.last().get('time') > attrs.time) {
// Search from latest backwards
const messages = Array.from(this.messages.models);
const stanza_id = attrs[`stanza_id ${this.get('jid')}`];
if (!stanza_id) {
return null;
}
messages.reverse();
return messages.find(_ref => {
let {
attributes
} = _ref;
return attributes.moderated === 'retracted' && attributes.moderated_id === stanza_id && attributes.moderated_by;
});
}
},
/**
* Handles message moderation based on the passed in attributes.
* @private
* @method _converse.ChatRoom#handleModeration
* @param { object } attrs - Attributes representing a received
* message, as returned by {@link parseMUCMessage}
* @returns { Boolean } Returns `true` or `false` depending on
* whether a message was moderated or not.
*/
async handleModeration(attrs) {
const MODERATION_ATTRIBUTES = ['editable', 'moderated', 'moderated_by', 'moderated_id', 'moderation_reason'];
if (attrs.moderated === 'retracted') {
const query = {};
const key = `stanza_id ${this.get('jid')}`;
query[key] = attrs.moderated_id;
const message = this.messages.findWhere(query);
if (!message) {
attrs['dangling_moderation'] = true;
await this.createMessage(attrs);
return true;
}
message.save(lodash_es_pick(attrs, MODERATION_ATTRIBUTES));
return true;
} else {
// Check if we have dangling moderation message
const message = this.findDanglingModeration(attrs);
if (message) {
const moderation_attrs = lodash_es_pick(message.attributes, MODERATION_ATTRIBUTES);
const new_attrs = Object.assign({
'dangling_moderation': false
}, attrs, moderation_attrs);
delete new_attrs['id']; // Delete id, otherwise a new cache entry gets created
message.save(new_attrs);
return true;
}
}
return false;
},
getNotificationsText() {
const {
__
} = shared_converse;
const actors_per_state = this.notifications.toJSON();
const role_changes = shared_api.settings.get('muc_show_info_messages').filter(role_change => converse.MUC_ROLE_CHANGES_LIST.includes(role_change));
const join_leave_events = shared_api.settings.get('muc_show_info_messages').filter(join_leave_event => converse.MUC_TRAFFIC_STATES_LIST.includes(join_leave_event));
const states = [...converse.CHAT_STATES, ...join_leave_events, ...role_changes];
return states.reduce((result, state) => {
const existing_actors = actors_per_state[state];
if (!existing_actors?.length) {
return result;
}
const actors = existing_actors.map(a => this.getOccupant(a)?.getDisplayName() || a);
if (actors.length === 1) {
if (state === 'composing') {
return `${result}${__('%1$s is typing', actors[0])}\n`;
} else if (state === 'paused') {
return `${result}${__('%1$s has stopped typing', actors[0])}\n`;
} else if (state === shared_converse.GONE) {
return `${result}${__('%1$s has gone away', actors[0])}\n`;
} else if (state === 'entered') {
return `${result}${__('%1$s has entered the groupchat', actors[0])}\n`;
} else if (state === 'exited') {
return `${result}${__('%1$s has left the groupchat', actors[0])}\n`;
} else if (state === 'op') {
return `${result}${__('%1$s is now a moderator', actors[0])}\n`;
} else if (state === 'deop') {
return `${result}${__('%1$s is no longer a moderator', actors[0])}\n`;
} else if (state === 'voice') {
return `${result}${__('%1$s has been given a voice', actors[0])}\n`;
} else if (state === 'mute') {
return `${result}${__('%1$s has been muted', actors[0])}\n`;
}
} else if (actors.length > 1) {
let actors_str;
if (actors.length > 3) {
actors_str = `${Array.from(actors).slice(0, 2).join(', ')} and others`;
} else {
const last_actor = actors.pop();
actors_str = __('%1$s and %2$s', actors.join(', '), last_actor);
}
if (state === 'composing') {
return `${result}${__('%1$s are typing', actors_str)}\n`;
} else if (state === 'paused') {
return `${result}${__('%1$s have stopped typing', actors_str)}\n`;
} else if (state === shared_converse.GONE) {
return `${result}${__('%1$s have gone away', actors_str)}\n`;
} else if (state === 'entered') {
return `${result}${__('%1$s have entered the groupchat', actors_str)}\n`;
} else if (state === 'exited') {
return `${result}${__('%1$s have left the groupchat', actors_str)}\n`;
} else if (state === 'op') {
return `${result}${__('%1$s are now moderators', actors[0])}\n`;
} else if (state === 'deop') {
return `${result}${__('%1$s are no longer moderators', actors[0])}\n`;
} else if (state === 'voice') {
return `${result}${__('%1$s have been given voices', actors[0])}\n`;
} else if (state === 'mute') {
return `${result}${__('%1$s have been muted', actors[0])}\n`;
}
}
return result;
}, '');
},
/**
* @param { String } actor - The nickname of the actor that caused the notification
* @param {String|Array<String>} states - The state or states representing the type of notificcation
*/
removeNotification(actor, states) {
const actors_per_state = this.notifications.toJSON();
states = Array.isArray(states) ? states : [states];
states.forEach(state => {
const existing_actors = Array.from(actors_per_state[state] || []);
if (existing_actors.includes(actor)) {
const idx = existing_actors.indexOf(actor);
existing_actors.splice(idx, 1);
this.notifications.set(state, Array.from(existing_actors));
}
});
},
/**
* Update the notifications model by adding the passed in nickname
* to the array of nicknames that all match a particular state.
*
* Removes the nickname from any other states it might be associated with.
*
* The state can be a XEP-0085 Chat State or a XEP-0045 join/leave
* state.
* @param { String } actor - The nickname of the actor that causes the notification
* @param { String } state - The state representing the type of notificcation
*/
updateNotifications(actor, state) {
const actors_per_state = this.notifications.toJSON();
const existing_actors = actors_per_state[state] || [];
if (existing_actors.includes(actor)) {
return;
}
const reducer = (out, s) => {
if (s === state) {
out[s] = [...existing_actors, actor];
} else {
out[s] = (actors_per_state[s] || []).filter(a => a !== actor);
}
return out;
};
const actors_per_chat_state = converse.CHAT_STATES.reduce(reducer, {});
const actors_per_traffic_state = converse.MUC_TRAFFIC_STATES_LIST.reduce(reducer, {});
const actors_per_role_change = converse.MUC_ROLE_CHANGES_LIST.reduce(reducer, {});
this.notifications.set(Object.assign(actors_per_chat_state, actors_per_traffic_state, actors_per_role_change));
window.setTimeout(() => this.removeNotification(actor, state), 10000);
},
handleMetadataFastening(attrs) {
if (attrs.ogp_for_id) {
if (attrs.from !== this.get('jid')) {
// For now we only allow metadata from the MUC itself and not
// from individual users who are deemed less trustworthy.
return false;
}
const message = this.messages.findWhere({
'origin_id': attrs.ogp_for_id
});
if (message) {
const old_list = message.get('ogp_metadata') || [];
if (old_list.filter(m => m['og:url'] === attrs['og:url']).length) {
// Don't add metadata for the same URL again
return false;
}
const list = [...old_list, lodash_es_pick(attrs, METADATA_ATTRIBUTES)];
message.save('ogp_metadata', list);
return true;
}
}
return false;
},
/**
* Given {@link MessageAttributes} look for XEP-0316 Room Notifications and create info
* messages for them.
* @param { Element } stanza
*/
handleMEPNotification(attrs) {
if (attrs.from !== this.get('jid') || !attrs.activities) {
return false;
}
attrs.activities?.forEach(activity_attrs => {
const data = Object.assign(attrs, activity_attrs);
this.createMessage(data);
// Trigger so that notifications are shown
shared_api.trigger('message', {
'attrs': data,
'chatbox': this
});
});
return !!attrs.activities.length;
},
/**
* Returns an already cached message (if it exists) based on the
* passed in attributes map.
* @method _converse.ChatRoom#getDuplicateMessage
* @param { object } attrs - Attributes representing a received
* message, as returned by {@link parseMUCMessage}
* @returns {Promise<_converse.Message>}
*/
getDuplicateMessage(attrs) {
if (attrs.activities?.length) {
return this.messages.findWhere({
'type': 'mep',
'msgid': attrs.msgid
});
} else {
return shared_converse.ChatBox.prototype.getDuplicateMessage.call(this, attrs);
}
},
/**
* Handler for all MUC messages sent to this groupchat. This method
* shouldn't be called directly, instead {@link _converse.ChatRoom#queueMessage}
* should be called.
* @method _converse.ChatRoom#onMessage
* @param { MessageAttributes } attrs - A promise which resolves to the message attributes.
*/
async onMessage(attrs) {
attrs = await attrs;
if (muc_u.isErrorObject(attrs)) {
attrs.stanza && log.error(attrs.stanza);
return log.error(attrs.message);
} else if (attrs.type === 'error' && !(await this.shouldShowErrorMessage(attrs))) {
return;
}
const message = this.getDuplicateMessage(attrs);
if (message) {
message.get('type') === 'groupchat' && this.updateMessage(message, attrs);
return;
} else if (attrs.receipt_id || attrs.is_marker || this.ignorableCSN(attrs)) {
return;
}
if (this.handleMetadataFastening(attrs) || this.handleMEPNotification(attrs) || (await this.handleRetraction(attrs)) || (await this.handleModeration(attrs)) || (await this.handleSubjectChange(attrs))) {
attrs.nick && this.removeNotification(attrs.nick, ['composing', 'paused']);
return;
}
this.setEditable(attrs, attrs.time);
if (attrs['chat_state']) {
this.updateNotifications(attrs.nick, attrs.chat_state);
}
if (muc_u.shouldCreateGroupchatMessage(attrs)) {
const msg = (await handleCorrection(this, attrs)) || (await this.createMessage(attrs));
this.removeNotification(attrs.nick, ['composing', 'paused']);
this.handleUnreadMessage(msg);
}
},
handleModifyError(pres) {
const text = pres.querySelector('error text')?.textContent;
if (text) {
if (this.session.get('connection_status') === ROOMSTATUS.CONNECTING) {
this.setDisconnectionState(text);
} else {
const attrs = {
'type': 'error',
'message': text,
'is_ephemeral': true
};
this.createMessage(attrs);
}
}
},
/**
* Handle a presence stanza that disconnects the user from the MUC
* @param { Element } stanza
*/
handleDisconnection(stanza) {
const is_self = stanza.querySelector("status[code='110']") !== null;
const x = sizzle_default()(`x[xmlns="${core.NS.MUC_USER}"]`, stanza).pop();
if (!x) {
return;
}
const disconnection_codes = Object.keys(shared_converse.muc.disconnect_messages);
const codes = sizzle_default()('status', x).map(s => s.getAttribute('code')).filter(c => disconnection_codes.includes(c));
const disconnected = is_self && codes.length > 0;
if (!disconnected) {
return;
}
// By using querySelector we assume here there is
// one <item> per <x xmlns='http://jabber.org/protocol/muc#user'>
// element. This appears to be a safe assumption, since
// each <x/> element pertains to a single user.
const item = x.querySelector('item');
const reason = item ? item.querySelector('reason')?.textContent : undefined;
const actor = item ? item.querySelector('actor')?.getAttribute('nick') : undefined;
const message = shared_converse.muc.disconnect_messages[codes[0]];
const status = codes.includes('301') ? ROOMSTATUS.BANNED : ROOMSTATUS.DISCONNECTED;
this.setDisconnectionState(message, reason, actor, status);
},
getActionInfoMessage(code, nick, actor) {
const __ = shared_converse.__;
if (code === '301') {
return actor ? __('%1$s has been banned by %2$s', nick, actor) : __('%1$s has been banned', nick);
} else if (code === '303') {
return __("%1$s's nickname has changed", nick);
} else if (code === '307') {
return actor ? __('%1$s has been kicked out by %2$s', nick, actor) : __('%1$s has been kicked out', nick);
} else if (code === '321') {
return __('%1$s has been removed because of an affiliation change', nick);
} else if (code === '322') {
return __('%1$s has been removed for not being a member', nick);
}
},
createAffiliationChangeMessage(occupant) {
const __ = shared_converse.__;
const previous_affiliation = occupant._previousAttributes.affiliation;
if (!previous_affiliation) {
// If no previous affiliation was set, then we don't
// interpret this as an affiliation change.
// For example, if muc_send_probes is true, then occupants
// are created based on incoming messages, in which case
// we don't yet know the affiliation
return;
}
const current_affiliation = occupant.get('affiliation');
if (previous_affiliation === 'admin' && shared_converse.isInfoVisible(converse.AFFILIATION_CHANGES.EXADMIN)) {
this.createMessage({
'type': 'info',
'message': __('%1$s is no longer an admin of this groupchat', occupant.get('nick'))
});
} else if (previous_affiliation === 'owner' && shared_converse.isInfoVisible(converse.AFFILIATION_CHANGES.EXOWNER)) {
this.createMessage({
'type': 'info',
'message': __('%1$s is no longer an owner of this groupchat', occupant.get('nick'))
});
} else if (previous_affiliation === 'outcast' && shared_converse.isInfoVisible(converse.AFFILIATION_CHANGES.EXOUTCAST)) {
this.createMessage({
'type': 'info',
'message': __('%1$s is no longer banned from this groupchat', occupant.get('nick'))
});
}
if (current_affiliation === 'none' && previous_affiliation === 'member' && shared_converse.isInfoVisible(converse.AFFILIATION_CHANGES.EXMEMBER)) {
this.createMessage({
'type': 'info',
'message': __('%1$s is no longer a member of this groupchat', occupant.get('nick'))
});
}
if (current_affiliation === 'member' && shared_converse.isInfoVisible(converse.AFFILIATION_CHANGES.MEMBER)) {
this.createMessage({
'type': 'info',
'message': __('%1$s is now a member of this groupchat', occupant.get('nick'))
});
} else if (current_affiliation === 'admin' && shared_converse.isInfoVisible(converse.AFFILIATION_CHANGES.ADMIN) || current_affiliation == 'owner' && shared_converse.isInfoVisible(converse.AFFILIATION_CHANGES.OWNER)) {
// For example: AppleJack is now an (admin|owner) of this groupchat
this.createMessage({
'type': 'info',
'message': __('%1$s is now an %2$s of this groupchat', occupant.get('nick'), current_affiliation)
});
}
},
createRoleChangeMessage(occupant, changed) {
if (changed === 'none' || occupant.changed.affiliation) {
// We don't inform of role changes if they accompany affiliation changes.
return;
}
const previous_role = occupant._previousAttributes.role;
if (previous_role === 'moderator' && shared_converse.isInfoVisible(converse.MUC_ROLE_CHANGES.DEOP)) {
this.updateNotifications(occupant.get('nick'), converse.MUC_ROLE_CHANGES.DEOP);
} else if (previous_role === 'visitor' && shared_converse.isInfoVisible(converse.MUC_ROLE_CHANGES.VOICE)) {
this.updateNotifications(occupant.get('nick'), converse.MUC_ROLE_CHANGES.VOICE);
}
if (occupant.get('role') === 'visitor' && shared_converse.isInfoVisible(converse.MUC_ROLE_CHANGES.MUTE)) {
this.updateNotifications(occupant.get('nick'), converse.MUC_ROLE_CHANGES.MUTE);
} else if (occupant.get('role') === 'moderator') {
if (!['owner', 'admin'].includes(occupant.get('affiliation')) && shared_converse.isInfoVisible(converse.MUC_ROLE_CHANGES.OP)) {
// Oly show this message if the user isn't already
// an admin or owner, otherwise this isn't new information.
this.updateNotifications(occupant.get('nick'), converse.MUC_ROLE_CHANGES.OP);
}
}
},
/**
* Create an info message based on a received MUC status code
* @private
* @method _converse.ChatRoom#createInfoMessage
* @param { string } code - The MUC status code
* @param { Element } stanza - The original stanza that contains the code
* @param { Boolean } is_self - Whether this stanza refers to our own presence
*/
createInfoMessage(code, stanza, is_self) {
const __ = shared_converse.__;
const data = {
'type': 'info',
'is_ephemeral': true
};
if (!shared_converse.isInfoVisible(code)) {
return;
}
if (code === '110' || code === '100' && !is_self) {
return;
} else if (code in shared_converse.muc.info_messages) {
data.message = shared_converse.muc.info_messages[code];
} else if (!is_self && ACTION_INFO_CODES.includes(code)) {
const nick = core.getResourceFromJid(stanza.getAttribute('from'));
const item = sizzle_default()(`x[xmlns="${core.NS.MUC_USER}"] item`, stanza).pop();
data.actor = item ? item.querySelector('actor')?.getAttribute('nick') : undefined;
data.reason = item ? item.querySelector('reason')?.textContent : undefined;
data.message = this.getActionInfoMessage(code, nick, data.actor);
} else if (is_self && code in shared_converse.muc.new_nickname_messages) {
// XXX: Side-effect of setting the nick. Should ideally be refactored out of this method
let nick;
if (code === '210') {
nick = core.getResourceFromJid(stanza.getAttribute('from'));
} else if (code === '303') {
nick = sizzle_default()(`x[xmlns="${core.NS.MUC_USER}"] item`, stanza).pop().getAttribute('nick');
}
this.save('nick', nick);
data.message = __(shared_converse.muc.new_nickname_messages[code], nick);
}
if (data.message) {
if (code === '201' && this.messages.findWhere(data)) {
return;
}
this.createMessage(data);
}
},
/**
* Create info messages based on a received presence or message stanza
* @private
* @method _converse.ChatRoom#createInfoMessages
* @param { Element } stanza
*/
createInfoMessages(stanza) {
const codes = sizzle_default()(`x[xmlns="${core.NS.MUC_USER}"] status`, stanza).map(s => s.getAttribute('code'));
if (codes.includes('333') && codes.includes('307')) {
// See: https://github.com/xsf/xeps/pull/969/files#diff-ac5113766e59219806793c1f7d967f1bR4966
codes.splice(codes.indexOf('307'), 1);
}
const is_self = codes.includes('110');
codes.forEach(code => this.createInfoMessage(code, stanza, is_self));
},
/**
* Set parameters regarding disconnection from this room. This helps to
* communicate to the user why they were disconnected.
* @param { String } message - The disconnection message, as received from (or
* implied by) the server.
* @param { String } reason - The reason provided for the disconnection
* @param { String } actor - The person (if any) responsible for this disconnection
* @param { number } status - The status code (see `ROOMSTATUS`)
*/
setDisconnectionState(message, reason, actor) {
let status = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ROOMSTATUS.DISCONNECTED;
this.session.save({
'connection_status': status,
'disconnection_actor': actor,
'disconnection_message': message,
'disconnection_reason': reason
});
},
onNicknameClash(presence) {
const __ = shared_converse.__;
if (shared_api.settings.get('muc_nickname_from_jid')) {
const nick = presence.getAttribute('from').split('/')[1];
if (nick === shared_converse.getDefaultMUCNickname()) {
this.join(nick + '-2');
} else {
const del = nick.lastIndexOf('-');
const num = nick.substring(del + 1, nick.length);
this.join(nick.substring(0, del + 1) + String(Number(num) + 1));
}
} else {
this.save({
'nickname_validation_message': __('The nickname you chose is reserved or ' + 'currently in use, please choose a different one.')
});
this.session.save({
'connection_status': ROOMSTATUS.NICKNAME_REQUIRED
});
}
},
/**
* Parses a <presence> stanza with type "error" and sets the proper
* `connection_status` value for this {@link _converse.ChatRoom} as
* well as any additional output that can be shown to the user.
* @private
* @param { Element } stanza - The presence stanza
*/
onErrorPresence(stanza) {
const __ = shared_converse.__;
const error = stanza.querySelector('error');
const error_type = error.getAttribute('type');
const reason = sizzle_default()(`text[xmlns="${core.NS.STANZAS}"]`, error).pop()?.textContent;
if (error_type === 'modify') {
this.handleModifyError(stanza);
} else if (error_type === 'auth') {
if (sizzle_default()(`not-authorized[xmlns="${core.NS.STANZAS}"]`, error).length) {
this.save({
'password_validation_message': reason || __('Password incorrect')
});
this.session.save({
'connection_status': ROOMSTATUS.PASSWORD_REQUIRED
});
}
if (error.querySelector('registration-required')) {
const message = __('You are not on the member list of this groupchat.');
this.setDisconnectionState(message, reason);
} else if (error.querySelector('forbidden')) {
this.setDisconnectionState(shared_converse.muc.disconnect_messages[301], reason, null, ROOMSTATUS.BANNED);
}
} else if (error_type === 'cancel') {
if (error.querySelector('not-allowed')) {
const message = __('You are not allowed to create new groupchats.');
this.setDisconnectionState(message, reason);
} else if (error.querySelector('not-acceptable')) {
const message = __("Your nickname doesn't conform to this groupchat's policies.");
this.setDisconnectionState(message, reason);
} else if (sizzle_default()(`gone[xmlns="${core.NS.STANZAS}"]`, error).length) {
const moved_jid = sizzle_default()(`gone[xmlns="${core.NS.STANZAS}"]`, error).pop()?.textContent.replace(/^xmpp:/, '').replace(/\?join$/, '');
this.save({
moved_jid,
'destroyed_reason': reason
});
this.session.save({
'connection_status': ROOMSTATUS.DESTROYED
});
} else if (error.querySelector('conflict')) {
this.onNicknameClash(stanza);
} else if (error.querySelector('item-not-found')) {
const message = __('This groupchat does not (yet) exist.');
this.setDisconnectionState(message, reason);
} else if (error.querySelector('service-unavailable')) {
const message = __('This groupchat has reached its maximum number of participants.');
this.setDisconnectionState(message, reason);
} else if (error.querySelector('remote-server-not-found')) {
const message = __('Remote server not found');
this.setDisconnectionState(message, reason);
} else if (error.querySelector('forbidden')) {
const message = __("You're not allowed to enter this groupchat");
this.setDisconnectionState(message, reason);
} else {
const message = __("An error happened while trying to enter this groupchat");
this.setDisconnectionState(message, reason);
}
}
},
/**
* Listens for incoming presence stanzas from the service that hosts this MUC
* @private
* @method _converse.ChatRoom#onPresenceFromMUCHost
* @param { Element } stanza - The presence stanza
*/
onPresenceFromMUCHost(stanza) {
if (stanza.getAttribute('type') === 'error') {
const error = stanza.querySelector('error');
if (error?.getAttribute('type') === 'wait' && error?.querySelector('resource-constraint')) {
// If we get a <resource-constraint> error, we assume it's in context of XEP-0437 RAI.
// We remove this MUC's host from the list of enabled domains and rejoin the MUC.
if (this.session.get('connection_status') === ROOMSTATUS.DISCONNECTED) {
this.rejoin();
}
}
}
},
/**
* Handles incoming presence stanzas coming from the MUC
* @private
* @method _converse.ChatRoom#onPresence
* @param { Element } stanza
*/
onPresence(stanza) {
if (stanza.getAttribute('type') === 'error') {
return this.onErrorPresence(stanza);
}
this.createInfoMessages(stanza);
if (stanza.querySelector("status[code='110']")) {
this.onOwnPresence(stanza);
if (this.getOwnRole() !== 'none' && this.session.get('connection_status') === ROOMSTATUS.CONNECTING) {
this.session.save('connection_status', ROOMSTATUS.CONNECTED);
}
} else {
this.updateOccupantsOnPresence(stanza);
}
},
/**
* Handles a received presence relating to the current user.
*
* For locked groupchats (which are by definition "new"), the
* groupchat will either be auto-configured or created instantly
* (with default config) or a configuration groupchat will be
* rendered.
*
* If the groupchat is not locked, then the groupchat will be
* auto-configured only if applicable and if the current
* user is the groupchat's owner.
* @private
* @method _converse.ChatRoom#onOwnPresence
* @param { Element } pres - The stanza
*/
async onOwnPresence(stanza) {
await this.occupants.fetched;
if (stanza.getAttribute('type') === 'unavailable') {
this.handleDisconnection(stanza);
return;
}
const old_status = this.session.get('connection_status');
if (old_status !== ROOMSTATUS.ENTERED && old_status !== ROOMSTATUS.CLOSING) {
// Set connection_status before creating the occupant, but
// only trigger afterwards, so that plugins can access the
// occupant in their event handlers.
this.session.save('connection_status', ROOMSTATUS.ENTERED, {
'silent': true
});
this.updateOccupantsOnPresence(stanza);
this.session.trigger('change:connection_status', this.session, old_status);
} else {
this.updateOccupantsOnPresence(stanza);
}
const locked_room = stanza.querySelector("status[code='201']");
if (locked_room) {
if (this.get('auto_configure')) {
await this.autoConfigureChatRoom().then(() => this.refreshDiscoInfo());
} else if (shared_api.settings.get('muc_instant_rooms')) {
// Accept default configuration
await this.sendConfiguration().then(() => this.refreshDiscoInfo());
} else {
this.session.save({
'view': converse.MUC.VIEWS.CONFIG
});
}
}
},
/**
* Returns a boolean to indicate whether the current user
* was mentioned in a message.
* @private
* @method _converse.ChatRoom#isUserMentioned
* @param { String } - The text message
*/
isUserMentioned(message) {
const nick = this.get('nick');
if (message.get('references').length) {
const mentions = message.get('references').filter(ref => ref.type === 'mention').map(ref => ref.value);
return mentions.includes(nick);
} else {
return new RegExp(`\\b${nick}\\b`).test(message.get('body'));
}
},
incrementUnreadMsgsCounter(message) {
const settings = {
'num_unread_general': this.get('num_unread_general') + 1
};
if (this.get('num_unread_general') === 0) {
settings['first_unread_id'] = message.get('id');
}
if (this.isUserMentioned(message)) {
settings.num_unread = this.get('num_unread') + 1;
}
this.save(settings);
},
clearUnreadMsgCounter() {
if (this.get('num_unread_general') > 0 || this.get('num_unread') > 0 || this.get('has_activity')) {
this.sendMarkerForMessage(this.messages.last());
}
safeSave(this, {
'has_activity': false,
'num_unread': 0,
'num_unread_general': 0
});
}
};
/* harmony default export */ const muc = (ChatRoomMixin);
;// CONCATENATED MODULE: ./src/headless/plugins/muc/occupant.js
/**
* Represents a participant in a MUC
* @class
* @namespace _converse.ChatRoomOccupant
* @memberOf _converse
*/
class ChatRoomOccupant extends Model {
defaults() {
// eslint-disable-line class-methods-use-this
return {
hats: [],
show: 'offline',
states: []
};
}
save(key, val, options) {
let attrs;
if (key == null) {
// eslint-disable-line no-eq-null
return super.save(key, val, options);
} else if (typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
if (attrs.occupant_id) {
attrs.id = attrs.occupant_id;
}
return super.save(attrs, options);
}
getDisplayName() {
return this.get('nick') || this.get('jid');
}
isMember() {
return ['admin', 'owner', 'member'].includes(this.get('affiliation'));
}
isModerator() {
return ['admin', 'owner'].includes(this.get('affiliation')) || this.get('role') === 'moderator';
}
isSelf() {
return this.get('states').includes('110');
}
}
/* harmony default export */ const occupant = (ChatRoomOccupant);
;// CONCATENATED MODULE: ./src/headless/plugins/muc/utils.js
const {
Strophe: muc_utils_Strophe,
sizzle: utils_sizzle,
u: muc_utils_u
} = converse.env;
function getAutoFetchedAffiliationLists() {
const affs = shared_api.settings.get('muc_fetch_members');
return Array.isArray(affs) ? affs : affs ? ['member', 'admin', 'owner'] : [];
}
/**
* Given an occupant model, see which roles may be assigned to that user.
* @param { Model } occupant
* @returns { Array<('moderator'|'participant'|'visitor')> } - An array of assignable roles
*/
function getAssignableRoles(occupant) {
let disabled = shared_api.settings.get('modtools_disable_assign');
if (!Array.isArray(disabled)) {
disabled = disabled ? ROLES : [];
}
if (occupant.get('role') === 'moderator') {
return ROLES.filter(r => !disabled.includes(r));
} else {
return [];
}
}
function registerDirectInvitationHandler() {
shared_converse.connection.addHandler(message => {
shared_converse.onDirectMUCInvitation(message);
return true;
}, 'jabber:x:conference', 'message');
}
function disconnectChatRooms() {
/* When disconnecting, mark all groupchats as
* disconnected, so that they will be properly entered again
* when fetched from session storage.
*/
return shared_converse.chatboxes.filter(m => m.get('type') === shared_converse.CHATROOMS_TYPE).forEach(m => m.session.save({
'connection_status': converse.ROOMSTATUS.DISCONNECTED
}));
}
async function onWindowStateChanged(data) {
if (data.state === 'visible' && shared_api.connection.connected()) {
const rooms = await shared_api.rooms.get();
rooms.forEach(room => room.rejoinIfNecessary());
}
}
async function routeToRoom(jid) {
if (!muc_utils_u.isValidMUCJID(jid)) {
return log.warn(`invalid jid "${jid}" provided in url fragment`);
}
await shared_api.waitUntil('roomsAutoJoined');
if (shared_api.settings.get('allow_bookmarks')) {
await shared_api.waitUntil('bookmarksInitialized');
}
shared_api.rooms.open(jid);
}
/* Opens a groupchat, making sure that certain attributes
* are correct, for example that the "type" is set to
* "chatroom".
*/
async function openChatRoom(jid, settings) {
settings.type = shared_converse.CHATROOMS_TYPE;
settings.id = jid;
const chatbox = await shared_api.rooms.get(jid, settings, true);
chatbox.maybeShow(true);
return chatbox;
}
/**
* A direct MUC invitation to join a groupchat has been received
* See XEP-0249: Direct MUC invitations.
* @private
* @method _converse.ChatRoom#onDirectMUCInvitation
* @param { Element } message - The message stanza containing the invitation.
*/
async function onDirectMUCInvitation(message) {
const x_el = utils_sizzle('x[xmlns="jabber:x:conference"]', message).pop(),
from = muc_utils_Strophe.getBareJidFromJid(message.getAttribute('from')),
room_jid = x_el.getAttribute('jid'),
reason = x_el.getAttribute('reason');
let result;
if (shared_api.settings.get('auto_join_on_invite')) {
result = true;
} else {
// Invite request might come from someone not your roster list
const contact = shared_converse.roster.get(from)?.getDisplayName() ?? from;
/**
* *Hook* which is used to gather confirmation whether a direct MUC
* invitation should be accepted or not.
*
* It's meant for consumers of `@converse/headless` to subscribe to
* this hook and then ask the user to confirm.
*
* @event _converse#confirmDirectMUCInvitation
*/
result = await shared_api.hook('confirmDirectMUCInvitation', {
contact,
reason,
jid: room_jid
}, false);
}
if (result) {
const chatroom = await openChatRoom(room_jid, {
'password': x_el.getAttribute('password')
});
if (chatroom.session.get('connection_status') === converse.ROOMSTATUS.DISCONNECTED) {
shared_converse.chatboxes.get(room_jid).rejoin();
}
}
}
function getDefaultMUCNickname() {
// XXX: if anything changes here, update the docs for the
// locked_muc_nickname setting.
if (!shared_converse.xmppstatus) {
throw new Error("Can't call _converse.getDefaultMUCNickname before the statusInitialized has been fired.");
}
const nick = shared_converse.xmppstatus.getNickname();
if (nick) {
return nick;
} else if (shared_api.settings.get('muc_nickname_from_jid')) {
return muc_utils_Strophe.unescapeNode(muc_utils_Strophe.getNodeFromJid(shared_converse.bare_jid));
}
}
/**
* Determines info message visibility based on
* muc_show_info_messages configuration setting
* @param {*} code
* @memberOf _converse
*/
function isInfoVisible(code) {
const info_messages = shared_api.settings.get('muc_show_info_messages');
if (info_messages.includes(code)) {
return true;
}
return false;
}
/**
* Automatically join groupchats, based on the
* "auto_join_rooms" configuration setting, which is an array
* of strings (groupchat JIDs) or objects (with groupchat JID and other settings).
*/
async function autoJoinRooms() {
await Promise.all(shared_api.settings.get('auto_join_rooms').map(muc => {
if (typeof muc === 'string') {
if (shared_converse.chatboxes.where({
'jid': muc
}).length) {
return Promise.resolve();
}
return shared_api.rooms.open(muc);
} else if (lodash_es_isObject(muc)) {
return shared_api.rooms.open(muc.jid, {
...muc
});
} else {
log.error('Invalid muc criteria specified for "auto_join_rooms"');
return Promise.resolve();
}
}));
/**
* Triggered once any rooms that have been configured to be automatically joined,
* specified via the _`auto_join_rooms` setting, have been entered.
* @event _converse#roomsAutoJoined
* @example _converse.api.listen.on('roomsAutoJoined', () => { ... });
* @example _converse.api.waitUntil('roomsAutoJoined').then(() => { ... });
*/
shared_api.trigger('roomsAutoJoined');
}
function onAddClientFeatures() {
shared_api.disco.own.features.add(muc_utils_Strophe.NS.MUC);
if (shared_api.settings.get('allow_muc_invitations')) {
shared_api.disco.own.features.add('jabber:x:conference'); // Invites
}
}
function onBeforeTearDown() {
shared_converse.chatboxes.where({
'type': shared_converse.CHATROOMS_TYPE
}).forEach(muc => safeSave(muc.session, {
'connection_status': converse.ROOMSTATUS.DISCONNECTED
}));
}
function onStatusInitialized() {
window.addEventListener(shared_converse.unloadevent, () => {
const using_websocket = shared_api.connection.isType('websocket');
if (using_websocket && (!shared_api.settings.get('enable_smacks') || !shared_converse.session.get('smacks_stream_id'))) {
// For non-SMACKS websocket connections, or non-resumeable
// connections, we disconnect all chatrooms when the page unloads.
// See issue #1111
disconnectChatRooms();
}
});
}
function onBeforeResourceBinding() {
shared_converse.connection.addHandler(stanza => {
const muc_jid = muc_utils_Strophe.getBareJidFromJid(stanza.getAttribute('from'));
if (!shared_converse.chatboxes.get(muc_jid)) {
shared_api.waitUntil('chatBoxesFetched').then(async () => {
const muc = shared_converse.chatboxes.get(muc_jid);
if (muc) {
await muc.initialized;
muc.message_handler.run(stanza);
}
});
}
return true;
}, null, 'message', 'groupchat');
}
Object.assign(shared_converse, {
getAssignableRoles
});
;// CONCATENATED MODULE: ./src/headless/plugins/muc/occupants.js
const {
u: occupants_u
} = converse.env;
/**
* A list of {@link _converse.ChatRoomOccupant} instances, representing participants in a MUC.
* @class
* @namespace _converse.ChatRoomOccupants
* @memberOf _converse
*/
class ChatRoomOccupants extends Collection {
model = occupant;
comparator(occupant1, occupant2) {
// eslint-disable-line class-methods-use-this
const role1 = occupant1.get('role') || 'none';
const role2 = occupant2.get('role') || 'none';
if (MUC_ROLE_WEIGHTS[role1] === MUC_ROLE_WEIGHTS[role2]) {
const nick1 = occupant1.getDisplayName().toLowerCase();
const nick2 = occupant2.getDisplayName().toLowerCase();
return nick1 < nick2 ? -1 : nick1 > nick2 ? 1 : 0;
} else {
return MUC_ROLE_WEIGHTS[role1] < MUC_ROLE_WEIGHTS[role2] ? -1 : 1;
}
}
create(attrs, options) {
if (attrs.id || attrs instanceof Model) {
return super.create(attrs, options);
}
attrs.id = attrs.occupant_id || getUniqueId();
return super.create(attrs, options);
}
async fetchMembers() {
if (!['member', 'admin', 'owner'].includes(this.getOwnOccupant()?.get('affiliation'))) {
// https://xmpp.org/extensions/xep-0045.html#affil-priv
return;
}
const affiliations = getAutoFetchedAffiliationLists();
if (affiliations.length === 0) {
return;
}
const muc_jid = this.chatroom.get('jid');
const aff_lists = await Promise.all(affiliations.map(a => getAffiliationList(a, muc_jid)));
const new_members = aff_lists.reduce((acc, val) => occupants_u.isErrorObject(val) ? acc : [...val, ...acc], []);
const known_affiliations = affiliations.filter(a => !occupants_u.isErrorObject(aff_lists[affiliations.indexOf(a)]));
const new_jids = new_members.map(m => m.jid).filter(m => m !== undefined);
const new_nicks = new_members.map(m => !m.jid && m.nick || undefined).filter(m => m !== undefined);
const removed_members = this.filter(m => {
return known_affiliations.includes(m.get('affiliation')) && !new_nicks.includes(m.get('nick')) && !new_jids.includes(m.get('jid'));
});
removed_members.forEach(occupant => {
if (occupant.get('jid') === shared_converse.bare_jid) {
return;
} else if (occupant.get('show') === 'offline') {
occupant.destroy();
} else {
occupant.save('affiliation', null);
}
});
new_members.forEach(attrs => {
const occupant = this.findOccupant(attrs);
occupant ? occupant.save(attrs) : this.create(attrs);
});
/**
* Triggered once the member lists for this MUC have been fetched and processed.
* @event _converse#membersFetched
* @example _converse.api.listen.on('membersFetched', () => { ... });
*/
shared_api.trigger('membersFetched');
}
/**
* @typedef { Object} OccupantData
* @property { String } [jid]
* @property { String } [nick]
* @property { String } [occupant_id] - The XEP-0421 unique occupant id
*/
/**
* Try to find an existing occupant based on the provided
* @link { OccupantData } object.
*
* Fetching the user by `occupant_id` is the quickest, O(1),
* since it's a dictionary lookup.
*
* Fetching by jid or nick is O(n), since it requires traversing an array.
*
* Lookup by occupant_id is done first, then jid, and then nick.
*
* @method _converse.ChatRoomOccupants#findOccupant
* @param { OccupantData } data
*/
findOccupant(data) {
if (data.occupant_id) {
return this.get(data.occupant_id);
}
const jid = data.jid && core.getBareJidFromJid(data.jid);
return jid && this.findWhere({
jid
}) || data.nick && this.findWhere({
'nick': data.nick
});
}
/**
* Get the {@link _converse.ChatRoomOccupant} instance which
* represents the current user.
* @method _converse.ChatRoomOccupants#getOwnOccupant
* @returns { _converse.ChatRoomOccupant }
*/
getOwnOccupant() {
return this.findOccupant({
'jid': shared_converse.bare_jid,
'occupant_id': this.chatroom.get('occupant_id')
});
}
}
/* harmony default export */ const occupants = (ChatRoomOccupants);
;// CONCATENATED MODULE: ./src/headless/plugins/muc/affiliations/api.js
/* harmony default export */ const affiliations_api = ({
/**
* The "affiliations" namespace groups methods relevant to setting and
* getting MUC affiliations.
*
* @namespace api.rooms.affiliations
* @memberOf api.rooms
*/
affiliations: {
/**
* Set the given affliation for the given JIDs in the specified MUCs
*
* @param { String|Array<String> } muc_jids - The JIDs of the MUCs in
* which the affiliation should be set.
* @param { Object[] } users - An array of objects representing users
* for whom the affiliation is to be set.
* @param { String } users[].jid - The JID of the user whose affiliation will change
* @param { ('outcast'|'member'|'admin'|'owner') } users[].affiliation - The new affiliation for this user
* @param { String } [users[].reason] - An optional reason for the affiliation change
* @returns { Promise }
*
* @example
* api.rooms.affiliations.set(
* [
* 'muc1@muc.example.org',
* 'muc2@muc.example.org'
* ], [
* {
* 'jid': 'user@example.org',
* 'affiliation': 'member',
* 'reason': "You're one of us now!"
* }
* ]
* )
*/
set(muc_jids, users) {
users = !Array.isArray(users) ? [users] : users;
muc_jids = !Array.isArray(muc_jids) ? [muc_jids] : muc_jids;
return setAffiliations(muc_jids, users);
}
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/muc/api.js
const {
u: api_u
} = converse.env;
/* harmony default export */ const muc_api = ({
/**
* The "rooms" namespace groups methods relevant to chatrooms
* (aka groupchats).
*
* @namespace api.rooms
* @memberOf api
*/
rooms: {
/**
* Creates a new MUC chatroom (aka groupchat)
*
* Similar to {@link api.rooms.open}, but creates
* the chatroom in the background (i.e. doesn't cause a view to open).
*
* @method api.rooms.create
* @param {(string[]|string)} jid|jids The JID or array of
* JIDs of the chatroom(s) to create
* @param { object } [attrs] attrs The room attributes
* @returns {Promise} Promise which resolves with the Model representing the chat.
*/
create(jids) {
let attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
attrs = typeof attrs === 'string' ? {
'nick': attrs
} : attrs || {};
if (!attrs.nick && shared_api.settings.get('muc_nickname_from_jid')) {
attrs.nick = core.getNodeFromJid(shared_converse.bare_jid);
}
if (jids === undefined) {
throw new TypeError('rooms.create: You need to provide at least one JID');
} else if (typeof jids === 'string') {
return shared_api.rooms.get(api_u.getJIDFromURI(jids), attrs, true);
}
return jids.map(jid => shared_api.rooms.get(api_u.getJIDFromURI(jid), attrs, true));
},
/**
* Opens a MUC chatroom (aka groupchat)
*
* Similar to {@link api.chats.open}, but for groupchats.
*
* @method api.rooms.open
* @param { string } jid The room JID or JIDs (if not specified, all
* currently open rooms will be returned).
* @param { string } attrs A map containing any extra room attributes.
* @param { string } [attrs.nick] The current user's nickname for the MUC
* @param { boolean } [attrs.auto_configure] A boolean, indicating
* whether the room should be configured automatically or not.
* If set to `true`, then it makes sense to pass in configuration settings.
* @param { object } [attrs.roomconfig] A map of configuration settings to be used when the room gets
* configured automatically. Currently it doesn't make sense to specify
* `roomconfig` values if `auto_configure` is set to `false`.
* For a list of configuration values that can be passed in, refer to these values
* in the [XEP-0045 MUC specification](https://xmpp.org/extensions/xep-0045.html#registrar-formtype-owner).
* The values should be named without the `muc#roomconfig_` prefix.
* @param { boolean } [attrs.minimized] A boolean, indicating whether the room should be opened minimized or not.
* @param { boolean } [attrs.bring_to_foreground] A boolean indicating whether the room should be
* brought to the foreground and therefore replace the currently shown chat.
* If there is no chat currently open, then this option is ineffective.
* @param { Boolean } [force=false] - By default, a minimized
* room won't be maximized (in `overlayed` view mode) and in
* `fullscreen` view mode a newly opened room won't replace
* another chat already in the foreground.
* Set `force` to `true` if you want to force the room to be
* maximized or shown.
* @returns {Promise} Promise which resolves with the Model representing the chat.
*
* @example
* api.rooms.open('group@muc.example.com')
*
* @example
* // To return an array of rooms, provide an array of room JIDs:
* api.rooms.open(['group1@muc.example.com', 'group2@muc.example.com'])
*
* @example
* // To setup a custom nickname when joining the room, provide the optional nick argument:
* api.rooms.open('group@muc.example.com', {'nick': 'mycustomnick'})
*
* @example
* // For example, opening a room with a specific default configuration:
* api.rooms.open(
* 'myroom@conference.example.org',
* { 'nick': 'coolguy69',
* 'auto_configure': true,
* 'roomconfig': {
* 'changesubject': false,
* 'membersonly': true,
* 'persistentroom': true,
* 'publicroom': true,
* 'roomdesc': 'Comfy room for hanging out',
* 'whois': 'anyone'
* }
* }
* );
*/
async open(jids) {
let attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
await shared_api.waitUntil('chatBoxesFetched');
if (jids === undefined) {
const err_msg = 'rooms.open: You need to provide at least one JID';
log.error(err_msg);
throw new TypeError(err_msg);
} else if (typeof jids === 'string') {
const room = await shared_api.rooms.get(jids, attrs, true);
!attrs.hidden && room?.maybeShow(force);
return room;
} else {
const rooms = await Promise.all(jids.map(jid => shared_api.rooms.get(jid, attrs, true)));
rooms.forEach(r => !attrs.hidden && r.maybeShow(force));
return rooms;
}
},
/**
* Fetches the object representing a MUC chatroom (aka groupchat)
*
* @method api.rooms.get
* @param { String } [jid] The room JID (if not specified, all rooms will be returned).
* @param { Object } [attrs] A map containing any extra room attributes
* to be set if `create` is set to `true`
* @param { String } [attrs.nick] Specify the nickname
* @param { String } [attrs.password ] Specify a password if needed to enter a new room
* @param { Boolean } create A boolean indicating whether the room should be created
* if not found (default: `false`)
* @returns { Promise<_converse.ChatRoom> }
* @example
* api.waitUntil('roomsAutoJoined').then(() => {
* const create_if_not_found = true;
* api.rooms.get(
* 'group@muc.example.com',
* {'nick': 'dread-pirate-roberts', 'password': 'secret'},
* create_if_not_found
* )
* });
*/
async get(jids) {
let attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let create = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
await shared_api.waitUntil('chatBoxesFetched');
async function _get(jid) {
jid = api_u.getJIDFromURI(jid);
let model = await shared_api.chatboxes.get(jid);
if (!model && create) {
model = await shared_api.chatboxes.create(jid, attrs, shared_converse.ChatRoom);
} else {
model = model && model.get('type') === shared_converse.CHATROOMS_TYPE ? model : null;
if (model && Object.keys(attrs).length) {
model.save(attrs);
}
}
return model;
}
if (jids === undefined) {
const chats = await shared_api.chatboxes.get();
return chats.filter(c => c.get('type') === shared_converse.CHATROOMS_TYPE);
} else if (typeof jids === 'string') {
return _get(jids);
}
return Promise.all(jids.map(jid => _get(jid)));
}
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/muc/index.js
/**
* @copyright The Converse.js contributors
* @license Mozilla Public License (MPLv2)
* @description Implements the non-view logic for XEP-0045 Multi-User Chat
*/
const muc_ROLES = (/* unused pure expression or super */ null && (['moderator', 'participant', 'visitor']));
const muc_AFFILIATIONS = ['owner', 'admin', 'member', 'outcast', 'none'];
converse.AFFILIATION_CHANGES = AFFILIATION_CHANGES;
converse.AFFILIATION_CHANGES_LIST = AFFILIATION_CHANGES_LIST;
converse.MUC_TRAFFIC_STATES = MUC_TRAFFIC_STATES;
converse.MUC_TRAFFIC_STATES_LIST = MUC_TRAFFIC_STATES_LIST;
converse.MUC_ROLE_CHANGES = MUC_ROLE_CHANGES;
converse.MUC_ROLE_CHANGES_LIST = MUC_ROLE_CHANGES_LIST;
converse.MUC = {
INFO_CODES: INFO_CODES
};
converse.MUC_NICK_CHANGED_CODE = MUC_NICK_CHANGED_CODE;
converse.ROOM_FEATURES = ROOM_FEATURES;
converse.ROOMSTATUS = ROOMSTATUS;
const {
Strophe: muc_Strophe
} = converse.env;
// Add Strophe Namespaces
muc_Strophe.addNamespace('MUC_ADMIN', muc_Strophe.NS.MUC + '#admin');
muc_Strophe.addNamespace('MUC_OWNER', muc_Strophe.NS.MUC + '#owner');
muc_Strophe.addNamespace('MUC_REGISTER', 'jabber:iq:register');
muc_Strophe.addNamespace('MUC_ROOMCONF', muc_Strophe.NS.MUC + '#roomconfig');
muc_Strophe.addNamespace('MUC_USER', muc_Strophe.NS.MUC + '#user');
muc_Strophe.addNamespace('MUC_HATS', 'xmpp:prosody.im/protocol/hats:1');
muc_Strophe.addNamespace('CONFINFO', 'urn:ietf:params:xml:ns:conference-info');
converse.plugins.add('converse-muc', {
dependencies: ['converse-chatboxes', 'converse-chat', 'converse-disco'],
overrides: {
ChatBoxes: {
model(attrs, options) {
const {
_converse
} = this.__super__;
if (attrs && attrs.type == _converse.CHATROOMS_TYPE) {
return new _converse.ChatRoom(attrs, options);
} else {
return this.__super__.model.apply(this, arguments);
}
}
}
},
initialize() {
/* The initialize function gets called as soon as the plugin is
* loaded by converse.js's plugin machinery.
*/
const {
__,
___
} = shared_converse;
// Configuration values for this plugin
// ====================================
// Refer to docs/source/configuration.rst for explanations of these
// configuration settings.
shared_api.settings.extend({
'allow_muc_invitations': true,
'auto_join_on_invite': false,
'auto_join_rooms': [],
'auto_register_muc_nickname': false,
'hide_muc_participants': false,
'locked_muc_domain': false,
'modtools_disable_assign': false,
'muc_clear_messages_on_leave': true,
'muc_domain': undefined,
'muc_fetch_members': true,
'muc_history_max_stanzas': undefined,
'muc_instant_rooms': true,
'muc_nickname_from_jid': false,
'muc_send_probes': false,
'muc_show_info_messages': [...converse.MUC.INFO_CODES.visibility_changes, ...converse.MUC.INFO_CODES.self, ...converse.MUC.INFO_CODES.non_privacy_changes, ...converse.MUC.INFO_CODES.muc_logging_changes, ...converse.MUC.INFO_CODES.nickname_changes, ...converse.MUC.INFO_CODES.disconnected, ...converse.MUC.INFO_CODES.affiliation_changes, ...converse.MUC.INFO_CODES.join_leave_events, ...converse.MUC.INFO_CODES.role_changes],
'muc_show_logs_before_join': false,
'muc_subscribe_to_rai': false
});
shared_api.promises.add(['roomsAutoJoined']);
if (shared_api.settings.get('locked_muc_domain') && typeof shared_api.settings.get('muc_domain') !== 'string') {
throw new Error('Config Error: it makes no sense to set locked_muc_domain ' + 'to true when muc_domain is not set');
}
// This is for tests (at least until we can import modules inside tests)
converse.env.muc_utils = {
computeAffiliationsDelta: computeAffiliationsDelta
};
Object.assign(shared_api, muc_api);
Object.assign(shared_api.rooms, affiliations_api);
/* https://xmpp.org/extensions/xep-0045.html
* ----------------------------------------
* 100 message Entering a groupchat Inform user that any occupant is allowed to see the user's full JID
* 101 message (out of band) Affiliation change Inform user that his or her affiliation changed while not in the groupchat
* 102 message Configuration change Inform occupants that groupchat now shows unavailable members
* 103 message Configuration change Inform occupants that groupchat now does not show unavailable members
* 104 message Configuration change Inform occupants that a non-privacy-related groupchat configuration change has occurred
* 110 presence Any groupchat presence Inform user that presence refers to one of its own groupchat occupants
* 170 message or initial presence Configuration change Inform occupants that groupchat logging is now enabled
* 171 message Configuration change Inform occupants that groupchat logging is now disabled
* 172 message Configuration change Inform occupants that the groupchat is now non-anonymous
* 173 message Configuration change Inform occupants that the groupchat is now semi-anonymous
* 174 message Configuration change Inform occupants that the groupchat is now fully-anonymous
* 201 presence Entering a groupchat Inform user that a new groupchat has been created
* 210 presence Entering a groupchat Inform user that the service has assigned or modified the occupant's roomnick
* 301 presence Removal from groupchat Inform user that he or she has been banned from the groupchat
* 303 presence Exiting a groupchat Inform all occupants of new groupchat nickname
* 307 presence Removal from groupchat Inform user that he or she has been kicked from the groupchat
* 321 presence Removal from groupchat Inform user that he or she is being removed from the groupchat because of an affiliation change
* 322 presence Removal from groupchat Inform user that he or she is being removed from the groupchat because the groupchat has been changed to members-only and the user is not a member
* 332 presence Removal from groupchat Inform user that he or she is being removed from the groupchat because of a system shutdown
*/
shared_converse.muc = {
info_messages: {
100: __('This groupchat is not anonymous'),
102: __('This groupchat now shows unavailable members'),
103: __('This groupchat does not show unavailable members'),
104: __('The groupchat configuration has changed'),
170: __('Groupchat logging is now enabled'),
171: __('Groupchat logging is now disabled'),
172: __('This groupchat is now no longer anonymous'),
173: __('This groupchat is now semi-anonymous'),
174: __('This groupchat is now fully-anonymous'),
201: __('A new groupchat has been created')
},
new_nickname_messages: {
// XXX: Note the triple underscore function and not double underscore.
210: ___('Your nickname has been automatically set to %1$s'),
303: ___('Your nickname has been changed to %1$s')
},
disconnect_messages: {
301: __('You have been banned from this groupchat'),
333: __('You have exited this groupchat due to a technical problem'),
307: __('You have been kicked from this groupchat'),
321: __('You have been removed from this groupchat because of an affiliation change'),
322: __("You have been removed from this groupchat because the groupchat has changed to members-only and you're not a member"),
332: __('You have been removed from this groupchat because the service hosting it is being shut down')
}
};
shared_converse.router.route('converse/room?jid=:jid', routeToRoom);
shared_converse.ChatRoom = shared_converse.ChatBox.extend(muc);
shared_converse.ChatRoomMessage = shared_converse.Message.extend(muc_message);
shared_converse.ChatRoomOccupants = occupants;
shared_converse.ChatRoomOccupant = occupant;
/**
* Collection which stores MUC messages
* @class
* @namespace _converse.ChatRoomMessages
* @memberOf _converse
*/
shared_converse.ChatRoomMessages = Collection.extend({
model: shared_converse.ChatRoomMessage,
comparator: 'time'
});
Object.assign(shared_converse, {
getDefaultMUCNickname: getDefaultMUCNickname,
isInfoVisible: isInfoVisible,
onDirectMUCInvitation: onDirectMUCInvitation
});
/************************ BEGIN Event Handlers ************************/
if (shared_api.settings.get('allow_muc_invitations')) {
shared_api.listen.on('connected', registerDirectInvitationHandler);
shared_api.listen.on('reconnected', registerDirectInvitationHandler);
}
shared_api.listen.on('addClientFeatures', () => shared_api.disco.own.features.add(`${muc_Strophe.NS.CONFINFO}+notify`));
shared_api.listen.on('addClientFeatures', onAddClientFeatures);
shared_api.listen.on('beforeResourceBinding', onBeforeResourceBinding);
shared_api.listen.on('beforeTearDown', onBeforeTearDown);
shared_api.listen.on('chatBoxesFetched', autoJoinRooms);
shared_api.listen.on('disconnected', disconnectChatRooms);
shared_api.listen.on('statusInitialized', onStatusInitialized);
shared_api.listen.on('windowStateChanged', onWindowStateChanged);
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/bookmarks/model.js
const {
Strophe: bookmarks_model_Strophe
} = converse.env;
const Bookmark = Model.extend({
idAttribute: 'jid',
getDisplayName() {
return bookmarks_model_Strophe.xmlunescape(this.get('name'));
}
});
/* harmony default export */ const bookmarks_model = (Bookmark);
;// CONCATENATED MODULE: ./src/headless/plugins/bookmarks/collection.js
const {
Strophe: collection_Strophe,
$iq: collection_$iq,
sizzle: collection_sizzle
} = converse.env;
const Bookmarks = {
model: bookmarks_model,
comparator: item => item.get('name').toLowerCase(),
async initialize() {
this.on('add', bm => this.openBookmarkedRoom(bm).then(bm => this.markRoomAsBookmarked(bm)).catch(e => log.fatal(e)));
this.on('remove', this.markRoomAsUnbookmarked, this);
this.on('remove', this.sendBookmarkStanza, this);
const cache_key = `converse.room-bookmarks${shared_converse.bare_jid}`;
this.fetched_flag = cache_key + 'fetched';
initStorage(this, cache_key);
await this.fetchBookmarks();
/**
* Triggered once the _converse.Bookmarks collection
* has been created and cached bookmarks have been fetched.
* @event _converse#bookmarksInitialized
* @type { _converse.Bookmarks }
* @example _converse.api.listen.on('bookmarksInitialized', (bookmarks) => { ... });
*/
shared_api.trigger('bookmarksInitialized', this);
},
async openBookmarkedRoom(bookmark) {
if (shared_api.settings.get('muc_respect_autojoin') && bookmark.get('autojoin')) {
const groupchat = await shared_api.rooms.create(bookmark.get('jid'), {
'nick': bookmark.get('nick')
});
groupchat.maybeShow();
}
return bookmark;
},
fetchBookmarks() {
const deferred = getOpenPromise();
if (window.sessionStorage.getItem(this.fetched_flag)) {
this.fetch({
'success': () => deferred.resolve(),
'error': () => deferred.resolve()
});
} else {
this.fetchBookmarksFromServer(deferred);
}
return deferred;
},
createBookmark(options) {
this.create(options);
this.sendBookmarkStanza().catch(iq => this.onBookmarkError(iq, options));
},
sendBookmarkStanza() {
const stanza = collection_$iq({
'type': 'set',
'from': shared_converse.connection.jid
}).c('pubsub', {
'xmlns': collection_Strophe.NS.PUBSUB
}).c('publish', {
'node': collection_Strophe.NS.BOOKMARKS
}).c('item', {
'id': 'current'
}).c('storage', {
'xmlns': collection_Strophe.NS.BOOKMARKS
});
this.forEach(model => {
stanza.c('conference', {
'name': model.get('name'),
'autojoin': model.get('autojoin'),
'jid': model.get('jid')
}).c('nick').t(model.get('nick')).up().up();
});
stanza.up().up().up();
stanza.c('publish-options').c('x', {
'xmlns': collection_Strophe.NS.XFORM,
'type': 'submit'
}).c('field', {
'var': 'FORM_TYPE',
'type': 'hidden'
}).c('value').t('http://jabber.org/protocol/pubsub#publish-options').up().up().c('field', {
'var': 'pubsub#persist_items'
}).c('value').t('true').up().up().c('field', {
'var': 'pubsub#access_model'
}).c('value').t('whitelist');
return shared_api.sendIQ(stanza);
},
onBookmarkError(iq, options) {
const {
__
} = shared_converse;
log.error("Error while trying to add bookmark");
log.error(iq);
shared_api.alert('error', __('Error'), [__("Sorry, something went wrong while trying to save your bookmark.")]);
this.get(options.jid)?.destroy();
},
fetchBookmarksFromServer(deferred) {
const stanza = collection_$iq({
'from': shared_converse.connection.jid,
'type': 'get'
}).c('pubsub', {
'xmlns': collection_Strophe.NS.PUBSUB
}).c('items', {
'node': collection_Strophe.NS.BOOKMARKS
});
shared_api.sendIQ(stanza).then(iq => this.onBookmarksReceived(deferred, iq)).catch(iq => this.onBookmarksReceivedError(deferred, iq));
},
markRoomAsBookmarked(bookmark) {
const groupchat = shared_converse.chatboxes.get(bookmark.get('jid'));
groupchat?.save('bookmarked', true);
},
markRoomAsUnbookmarked(bookmark) {
const groupchat = shared_converse.chatboxes.get(bookmark.get('jid'));
groupchat?.save('bookmarked', false);
},
createBookmarksFromStanza(stanza) {
const xmlns = collection_Strophe.NS.BOOKMARKS;
const sel = `items[node="${xmlns}"] item storage[xmlns="${xmlns}"] conference`;
collection_sizzle(sel, stanza).forEach(el => {
const jid = el.getAttribute('jid');
const bookmark = this.get(jid);
const attrs = {
'jid': jid,
'name': el.getAttribute('name') || jid,
'autojoin': el.getAttribute('autojoin') === 'true',
'nick': el.querySelector('nick')?.textContent || ''
};
bookmark ? bookmark.save(attrs) : this.create(attrs);
});
},
onBookmarksReceived(deferred, iq) {
this.createBookmarksFromStanza(iq);
window.sessionStorage.setItem(this.fetched_flag, true);
if (deferred !== undefined) {
return deferred.resolve();
}
},
onBookmarksReceivedError(deferred, iq) {
const {
__
} = shared_converse;
if (iq === null) {
log.error('Error: timeout while fetching bookmarks');
shared_api.alert('error', __('Timeout Error'), [__("The server did not return your bookmarks within the allowed time. " + "You can reload the page to request them again.")]);
} else if (deferred) {
if (iq.querySelector('error[type="cancel"] item-not-found')) {
// Not an exception, the user simply doesn't have any bookmarks.
window.sessionStorage.setItem(this.fetched_flag, true);
return deferred.resolve();
} else {
log.error('Error while fetching bookmarks');
log.error(iq);
return deferred.reject(new Error("Could not fetch bookmarks"));
}
} else {
log.error('Error while fetching bookmarks');
log.error(iq);
}
},
async getUnopenedBookmarks() {
await shared_api.waitUntil('bookmarksInitialized');
await shared_api.waitUntil('chatBoxesFetched');
return this.filter(b => !shared_converse.chatboxes.get(b.get('jid')));
}
};
/* harmony default export */ const collection = (Bookmarks);
;// CONCATENATED MODULE: ./src/headless/plugins/bookmarks/utils.js
const {
Strophe: bookmarks_utils_Strophe,
sizzle: bookmarks_utils_sizzle
} = converse.env;
async function checkBookmarksSupport() {
const identity = await shared_api.disco.getIdentity('pubsub', 'pep', shared_converse.bare_jid);
if (shared_api.settings.get('allow_public_bookmarks')) {
return !!identity;
} else {
return shared_api.disco.supports(bookmarks_utils_Strophe.NS.PUBSUB + '#publish-options', shared_converse.bare_jid);
}
}
async function initBookmarks() {
if (!shared_api.settings.get('allow_bookmarks')) {
return;
}
if (await checkBookmarksSupport()) {
shared_converse.bookmarks = new shared_converse.Bookmarks();
}
}
function getNicknameFromBookmark(jid) {
if (!shared_api.settings.get('allow_bookmarks')) {
return null;
}
return shared_converse.bookmarks?.get(jid)?.get('nick');
}
function handleBookmarksPush(message) {
if (bookmarks_utils_sizzle(`event[xmlns="${bookmarks_utils_Strophe.NS.PUBSUB}#event"] items[node="${bookmarks_utils_Strophe.NS.BOOKMARKS}"]`, message).length) {
shared_api.waitUntil('bookmarksInitialized').then(() => shared_converse.bookmarks.createBookmarksFromStanza(message)).catch(e => log.fatal(e));
}
return true;
}
;// CONCATENATED MODULE: ./src/headless/plugins/bookmarks/index.js
/**
* @description
* Converse.js plugin which adds views for bookmarks specified in XEP-0048.
* @copyright 2022, the Converse.js contributors
* @license Mozilla Public License (MPLv2)
*/
const {
Strophe: bookmarks_Strophe
} = converse.env;
bookmarks_Strophe.addNamespace('BOOKMARKS', 'storage:bookmarks');
converse.plugins.add('converse-bookmarks', {
dependencies: ["converse-chatboxes", "converse-muc"],
overrides: {
// Overrides mentioned here will be picked up by converse.js's
// plugin architecture they will replace existing methods on the
// relevant objects or classes.
// New functions which don't exist yet can also be added.
ChatRoom: {
getDisplayName() {
const {
_converse,
getDisplayName
} = this.__super__;
const bookmark = this.get('bookmarked') ? _converse.bookmarks?.get(this.get('jid')) : null;
return bookmark?.get('name') || getDisplayName.apply(this, arguments);
},
getAndPersistNickname(nick) {
nick = nick || getNicknameFromBookmark(this.get('jid'));
return this.__super__.getAndPersistNickname.call(this, nick);
}
}
},
initialize() {
// Configuration values for this plugin
// ====================================
// Refer to docs/source/configuration.rst for explanations of these
// configuration settings.
shared_api.settings.extend({
allow_bookmarks: true,
allow_public_bookmarks: false,
muc_respect_autojoin: true
});
shared_api.promises.add('bookmarksInitialized');
shared_converse.Bookmark = bookmarks_model;
shared_converse.Bookmarks = Collection.extend(collection);
shared_api.listen.on('addClientFeatures', () => {
if (shared_api.settings.get('allow_bookmarks')) {
shared_api.disco.own.features.add(bookmarks_Strophe.NS.BOOKMARKS + '+notify');
}
});
shared_api.listen.on('clearSession', () => {
if (shared_converse.bookmarks) {
shared_converse.bookmarks.clearStore({
'silent': true
});
window.sessionStorage.removeItem(shared_converse.bookmarks.fetched_flag);
delete shared_converse.bookmarks;
}
});
shared_api.listen.on('connected', async () => {
// Add a handler for bookmarks pushed from other connected clients
const {
connection
} = shared_converse;
connection.addHandler(handleBookmarksPush, null, 'message', 'headline', null, shared_converse.bare_jid);
await Promise.all([shared_api.waitUntil('chatBoxesFetched')]);
initBookmarks();
});
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/bosh.js
/**
* @copyright The Converse.js contributors
* @license Mozilla Public License (MPLv2)
* @description Converse.js plugin which add support for XEP-0206: XMPP Over BOSH
*/
const {
Strophe: bosh_Strophe
} = converse.env;
const BOSH_SESSION_ID = 'converse.bosh-session';
converse.plugins.add('converse-bosh', {
enabled() {
return !shared_converse.api.settings.get("blacklisted_plugins").includes('converse-bosh');
},
initialize() {
shared_api.settings.extend({
bosh_service_url: undefined,
prebind_url: null
});
async function initBOSHSession() {
const id = BOSH_SESSION_ID;
if (!shared_converse.bosh_session) {
shared_converse.bosh_session = new Model({
id
});
shared_converse.bosh_session.browserStorage = shared_converse.createStore(id, "session");
await new Promise(resolve => shared_converse.bosh_session.fetch({
'success': resolve,
'error': resolve
}));
}
if (shared_converse.jid) {
if (shared_converse.bosh_session.get('jid') !== shared_converse.jid) {
const jid = await setUserJID(shared_converse.jid);
shared_converse.bosh_session.clear({
'silent': true
});
shared_converse.bosh_session.save({
jid
});
}
} else {
// Keepalive
const jid = shared_converse.bosh_session.get('jid');
jid && (await setUserJID(jid));
}
return shared_converse.bosh_session;
}
shared_converse.startNewPreboundBOSHSession = function () {
if (!shared_api.settings.get('prebind_url')) {
throw new Error("startNewPreboundBOSHSession: If you use prebind then you MUST supply a prebind_url");
}
const xhr = new XMLHttpRequest();
xhr.open('GET', shared_api.settings.get('prebind_url'), true);
xhr.setRequestHeader('Accept', 'application/json, text/javascript');
xhr.onload = async function () {
if (xhr.status >= 200 && xhr.status < 400) {
const data = JSON.parse(xhr.responseText);
const jid = await setUserJID(data.jid);
shared_converse.connection.attach(jid, data.sid, data.rid, shared_converse.connection.onConnectStatusChanged, BOSH_WAIT);
} else {
xhr.onerror();
}
};
xhr.onerror = function () {
delete shared_converse.connection;
/**
* Triggered when fetching prebind tokens failed
* @event _converse#noResumeableBOSHSession
* @type { _converse }
* @example _converse.api.listen.on('noResumeableBOSHSession', _converse => { ... });
*/
shared_api.trigger('noResumeableBOSHSession', shared_converse);
};
xhr.send();
};
shared_converse.restoreBOSHSession = async function () {
const jid = (await initBOSHSession()).get('jid');
if (jid && shared_converse.connection._proto instanceof bosh_Strophe.Bosh) {
try {
shared_converse.connection.restore(jid, shared_converse.connection.onConnectStatusChanged);
return true;
} catch (e) {
!shared_converse.isTestEnv() && log.warn("Could not restore session for jid: " + jid + " Error message: " + e.message);
return false;
}
}
return false;
};
/************************ BEGIN Event Handlers ************************/
shared_api.listen.on('clearSession', () => {
if (shared_converse.bosh_session === undefined) {
// Remove manually, even if we don't have the corresponding
// model, to avoid trying to reconnect to a stale BOSH session
const id = BOSH_SESSION_ID;
sessionStorage.removeItem(id);
sessionStorage.removeItem(`${id}-${id}`);
} else {
shared_converse.bosh_session.destroy();
delete shared_converse.bosh_session;
}
});
shared_api.listen.on('setUserJID', () => {
if (shared_converse.bosh_session !== undefined) {
shared_converse.bosh_session.save({
'jid': shared_converse.jid
});
}
});
shared_api.listen.on('addClientFeatures', () => shared_api.disco.own.features.add(bosh_Strophe.NS.BOSH));
/************************ END Event Handlers ************************/
/************************ BEGIN API ************************/
Object.assign(shared_api, {
/**
* This namespace lets you access the BOSH tokens
*
* @namespace api.tokens
* @memberOf api
*/
tokens: {
/**
* @method api.tokens.get
* @param { string } [id] The type of token to return ('rid' or 'sid').
* @returns 'string' A token, either the RID or SID token depending on what's asked for.
* @example _converse.api.tokens.get('rid');
*/
get(id) {
if (shared_converse.connection === undefined) {
return null;
}
if (id.toLowerCase() === 'rid') {
return shared_converse.connection.rid || shared_converse.connection._proto.rid;
} else if (id.toLowerCase() === 'sid') {
return shared_converse.connection.sid || shared_converse.connection._proto.sid;
}
}
}
});
/************************ end api ************************/
}
});
;// CONCATENATED MODULE: ./src/headless/utils/arraybuffer.js
const {
u: arraybuffer_u
} = converse.env;
function appendArrayBuffer(buffer1, buffer2) {
const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
tmp.set(new Uint8Array(buffer1), 0);
tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
return tmp.buffer;
}
function arrayBufferToHex(ab) {
// https://stackoverflow.com/questions/40031688/javascript-arraybuffer-to-hex#40031979
return Array.prototype.map.call(new Uint8Array(ab), x => ('00' + x.toString(16)).slice(-2)).join('');
}
function arrayBufferToString(ab) {
return new TextDecoder("utf-8").decode(ab);
}
function stringToArrayBuffer(string) {
const bytes = new TextEncoder("utf-8").encode(string);
return bytes.buffer;
}
function arrayBufferToBase64(ab) {
return btoa(new Uint8Array(ab).reduce((data, byte) => data + String.fromCharCode(byte), ''));
}
function base64ToArrayBuffer(b64) {
const binary_string = window.atob(b64),
len = binary_string.length,
bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
function hexToArrayBuffer(hex) {
const typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(h => parseInt(h, 16)));
return typedArray.buffer;
}
Object.assign(arraybuffer_u, {
arrayBufferToHex,
arrayBufferToString,
stringToArrayBuffer,
arrayBufferToBase64,
base64ToArrayBuffer
});
;// CONCATENATED MODULE: ./src/headless/plugins/caps/utils.js
const {
Strophe: caps_utils_Strophe,
$build: utils_$build
} = converse.env;
function propertySort(array, property) {
return array.sort((a, b) => {
return a[property] > b[property] ? -1 : 1;
});
}
async function generateVerificationString() {
const identities = shared_converse.api.disco.own.identities.get();
const features = shared_converse.api.disco.own.features.get();
if (identities.length > 1) {
propertySort(identities, "category");
propertySort(identities, "type");
propertySort(identities, "lang");
}
let S = identities.reduce((result, id) => `${result}${id.category}/${id.type}/${id?.lang ?? ''}/${id.name}<`, "");
features.sort();
S = features.reduce((result, feature) => `${result}${feature}<`, S);
const ab = await crypto.subtle.digest('SHA-1', stringToArrayBuffer(S));
return arrayBufferToBase64(ab);
}
async function createCapsNode() {
return utils_$build("c", {
'xmlns': caps_utils_Strophe.NS.CAPS,
'hash': "sha-1",
'node': "https://conversejs.org",
'ver': await generateVerificationString()
}).tree();
}
/**
* Given a stanza, adds a XEP-0115 CAPS element
* @param { Element } stanza
*/
async function addCapsNode(stanza) {
const caps_el = await createCapsNode();
stanza.root().cnode(caps_el).up();
return stanza;
}
;// CONCATENATED MODULE: ./src/headless/plugins/caps/index.js
/**
* @copyright 2022, the Converse.js contributors
* @license Mozilla Public License (MPLv2)
*/
const {
Strophe: caps_Strophe
} = converse.env;
caps_Strophe.addNamespace('CAPS', "http://jabber.org/protocol/caps");
converse.plugins.add('converse-caps', {
dependencies: ['converse-status'],
initialize() {
shared_api.listen.on('constructedPresence', (_, p) => addCapsNode(p));
shared_api.listen.on('constructedMUCPresence', (_, p) => addCapsNode(p));
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/chatboxes/chatboxes.js
const ChatBoxes = Collection.extend({
comparator: 'time_opened',
model(attrs, options) {
return new shared_converse.ChatBox(attrs, options);
},
onChatBoxesFetched(collection) {
collection.filter(c => !c.isValid()).forEach(c => c.destroy());
/**
* Triggered once all chat boxes have been recreated from the browser cache
* @event _converse#chatBoxesFetched
* @type { object }
* @property { _converse.ChatBox | _converse.ChatRoom } chatbox
* @property { Element } stanza
* @example _converse.api.listen.on('chatBoxesFetched', obj => { ... });
* @example _converse.api.waitUntil('chatBoxesFetched').then(() => { ... });
*/
shared_api.trigger('chatBoxesFetched');
},
onConnected(reconnecting) {
if (reconnecting) {
return;
}
initStorage(this, `converse.chatboxes-${shared_converse.bare_jid}`);
this.fetch({
'add': true,
'success': c => this.onChatBoxesFetched(c)
});
}
});
/* harmony default export */ const chatboxes = (ChatBoxes);
;// CONCATENATED MODULE: ./src/headless/plugins/chatboxes/utils.js
const {
Strophe: chatboxes_utils_Strophe
} = converse.env;
async function createChatBox(jid, attrs, Model) {
jid = chatboxes_utils_Strophe.getBareJidFromJid(jid.toLowerCase());
Object.assign(attrs, {
'jid': jid,
'id': jid
});
let chatbox;
try {
chatbox = new Model(attrs, {
'collection': shared_converse.chatboxes
});
} catch (e) {
log.error(e);
return null;
}
await chatbox.initialized;
if (!chatbox.isValid()) {
chatbox.destroy();
return null;
}
shared_converse.chatboxes.add(chatbox);
return chatbox;
}
;// CONCATENATED MODULE: ./src/headless/plugins/chatboxes/api.js
/**
* The "chatboxes" namespace.
*
* @namespace api.chatboxes
* @memberOf api
*/
/* harmony default export */ const chatboxes_api = ({
/**
* @method api.chats.create
* @param { String|String[] } jids - A JID or array of JIDs
* @param { Object } [attrs] An object containing configuration attributes
* @param { Model } model - The type of chatbox that should be created
*/
async create() {
let jids = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let model = arguments.length > 2 ? arguments[2] : undefined;
await shared_api.waitUntil('chatBoxesFetched');
if (typeof jids === 'string') {
return createChatBox(jids, attrs, model);
} else {
return Promise.all(jids.map(jid => createChatBox(jid, attrs, model)));
}
},
/**
* @method api.chats.get
* @param { String|String[] } jids - A JID or array of JIDs
*/
async get(jids) {
await shared_api.waitUntil('chatBoxesFetched');
if (jids === undefined) {
return shared_converse.chatboxes.models;
} else if (typeof jids === 'string') {
return shared_converse.chatboxes.get(jids.toLowerCase());
} else {
jids = jids.map(j => j.toLowerCase());
return shared_converse.chatboxes.models.filter(m => jids.includes(m.get('jid')));
}
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/chatboxes/index.js
/**
* @copyright 2022, the Converse.js contributors
* @license Mozilla Public License (MPLv2)
*/
const {
Strophe: chatboxes_Strophe
} = converse.env;
converse.plugins.add('converse-chatboxes', {
dependencies: ["converse-emoji", "converse-roster", "converse-vcard"],
initialize() {
shared_api.promises.add(['chatBoxesFetched', 'chatBoxesInitialized', 'privateChatsAutoJoined']);
Object.assign(shared_api, {
'chatboxes': chatboxes_api
});
shared_converse.ChatBoxes = chatboxes;
shared_api.listen.on('addClientFeatures', () => {
shared_api.disco.own.features.add(chatboxes_Strophe.NS.MESSAGE_CORRECT);
shared_api.disco.own.features.add(chatboxes_Strophe.NS.HTTPUPLOAD);
shared_api.disco.own.features.add(chatboxes_Strophe.NS.OUTOFBAND);
});
shared_api.listen.on('pluginsInitialized', () => {
shared_converse.chatboxes = new shared_converse.ChatBoxes();
/**
* Triggered once the _converse.ChatBoxes collection has been initialized.
* @event _converse#chatBoxesInitialized
* @example _converse.api.listen.on('chatBoxesInitialized', () => { ... });
* @example _converse.api.waitUntil('chatBoxesInitialized').then(() => { ... });
*/
shared_api.trigger('chatBoxesInitialized');
});
shared_api.listen.on('presencesInitialized', reconnecting => shared_converse.chatboxes.onConnected(reconnecting));
shared_api.listen.on('reconnected', () => shared_converse.chatboxes.forEach(m => m.onReconnection()));
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/adhoc/utils.js
const {
Strophe: adhoc_utils_Strophe,
u: adhoc_utils_u
} = converse.env;
function parseForCommands(stanza) {
const items = sizzle_default()(`query[xmlns="${adhoc_utils_Strophe.NS.DISCO_ITEMS}"][node="${adhoc_utils_Strophe.NS.ADHOC}"] item`, stanza);
return items.map(getAttributes);
}
function getCommandFields(iq, jid) {
const cmd_el = sizzle_default()(`command[xmlns="${adhoc_utils_Strophe.NS.ADHOC}"]`, iq).pop();
const data = {
sessionid: cmd_el.getAttribute('sessionid'),
instructions: sizzle_default()('x[type="form"][xmlns="jabber:x:data"] instructions', cmd_el).pop()?.textContent,
fields: sizzle_default()('x[type="form"][xmlns="jabber:x:data"] field', cmd_el).map(f => adhoc_utils_u.xForm2TemplateResult(f, cmd_el, {
domain: jid
})),
actions: Array.from(cmd_el.querySelector('actions')?.children).map(a => a.nodeName.toLowerCase()) ?? []
};
return data;
}
;// CONCATENATED MODULE: ./src/headless/plugins/adhoc/api.js
const {
Strophe: adhoc_api_Strophe,
$iq: adhoc_api_$iq,
u: adhoc_api_u,
stx: api_stx
} = converse.env;
/* harmony default export */ const adhoc_api = ({
/**
* The XEP-0050 Ad-Hoc Commands API
*
* This API lets you discover ad-hoc commands available for an entity in the XMPP network.
*
* @namespace api.adhoc
* @memberOf api
*/
adhoc: {
/**
* @method api.adhoc.getCommands
* @param { String } to_jid
*/
async getCommands(to_jid) {
try {
return parseForCommands(await shared_api.disco.items(to_jid, adhoc_api_Strophe.NS.ADHOC));
} catch (e) {
if (e === null) {
log.error(`Error: timeout while fetching ad-hoc commands for ${to_jid}`);
} else {
log.error(`Error while fetching ad-hoc commands for ${to_jid}`);
log.error(e);
}
return [];
}
},
/**
* @method api.adhoc.fetchCommandForm
*/
async fetchCommandForm(command) {
const node = command.node;
const jid = command.jid;
const stanza = adhoc_api_$iq({
'type': 'set',
'to': jid
}).c('command', {
'xmlns': adhoc_api_Strophe.NS.ADHOC,
'node': node,
'action': 'execute'
});
try {
return getCommandFields(await shared_api.sendIQ(stanza), jid);
} catch (e) {
if (e === null) {
log.error(`Error: timeout while trying to execute command for ${jid}`);
} else {
log.error(`Error while trying to execute command for ${jid}`);
log.error(e);
}
const {
__
} = shared_converse;
return {
instructions: __('An error occurred while trying to fetch the command form'),
fields: []
};
}
},
/**
* @method api.adhoc.runCommand
* @param { String } jid
* @param { String } sessionid
* @param { 'execute' | 'cancel' | 'prev' | 'next' | 'complete' } action
* @param { String } node
* @param { Array<{ string: string }> } inputs
*/
async runCommand(jid, sessionid, node, action, inputs) {
const iq = api_stx`<iq type="set" to="${jid}" xmlns="jabber:client">
<command sessionid="${sessionid}" node="${node}" action="${action}" xmlns="${adhoc_api_Strophe.NS.ADHOC}">
${!['cancel', 'prev'].includes(action) ? api_stx`
<x xmlns="${adhoc_api_Strophe.NS.XFORM}" type="submit">
${inputs.reduce((out, _ref) => {
let {
name,
value
} = _ref;
return out + `<field var="${name}"><value>${value}</value></field>`;
}, '')}
</x>` : ''}
</command>
</iq>`;
const result = await shared_api.sendIQ(iq, null, false);
if (result === null) {
log.warn(`A timeout occurred while trying to run an ad-hoc command`);
const {
__
} = shared_converse;
return {
status: 'error',
note: __('A timeout occurred')
};
} else if (adhoc_api_u.isErrorStanza(result)) {
log.error('Error while trying to execute an ad-hoc command');
log.error(result);
}
const command = result.querySelector('command');
const status = command?.getAttribute('status');
return {
status,
...(status === 'executing' ? getCommandFields(result) : {}),
note: result.querySelector('note')?.textContent
};
}
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/adhoc/index.js
const {
Strophe: adhoc_Strophe
} = converse.env;
adhoc_Strophe.addNamespace('ADHOC', 'http://jabber.org/protocol/commands');
converse.plugins.add('converse-adhoc', {
dependencies: ["converse-disco"],
initialize() {
Object.assign(this._converse.api, adhoc_api);
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/headlines/feed.js
class HeadlinesFeed extends model {
defaults() {
return {
'bookmarked': false,
'hidden': ['mobile', 'fullscreen'].includes(shared_api.settings.get("view_mode")),
'message_type': 'headline',
'num_unread': 0,
'time_opened': this.get('time_opened') || new Date().getTime(),
'type': shared_converse.HEADLINES_TYPE
};
}
async initialize() {
this.set({
'box_id': `box-${this.get('jid')}`
});
this.initUI();
this.initMessages();
await this.fetchMessages();
/**
* Triggered once a { @link _converse.HeadlinesFeed } has been created and initialized.
* @event _converse#headlinesFeedInitialized
* @type { _converse.HeadlinesFeed }
* @example _converse.api.listen.on('headlinesFeedInitialized', model => { ... });
*/
shared_api.trigger('headlinesFeedInitialized', this);
}
}
;// CONCATENATED MODULE: ./src/headless/plugins/headlines/api.js
/* harmony default export */ const headlines_api = ({
/**
* The "headlines" namespace, which is used for headline-channels
* which are read-only channels containing messages of type
* "headline".
*
* @namespace api.headlines
* @memberOf api
*/
headlines: {
/**
* Retrieves a headline-channel or all headline-channels.
*
* @method api.headlines.get
* @param {String|String[]} jids - e.g. 'buddy@example.com' or ['buddy1@example.com', 'buddy2@example.com']
* @param { Object } [attrs] - Attributes to be set on the _converse.ChatBox model.
* @param { Boolean } [create=false] - Whether the chat should be created if it's not found.
* @returns { Promise<_converse.HeadlinesFeed> }
*/
async get(jids) {
let attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let create = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
async function _get(jid) {
let model = await shared_api.chatboxes.get(jid);
if (!model && create) {
model = await shared_api.chatboxes.create(jid, attrs, shared_converse.HeadlinesFeed);
} else {
model = model && model.get('type') === shared_converse.HEADLINES_TYPE ? model : null;
if (model && Object.keys(attrs).length) {
model.save(attrs);
}
}
return model;
}
if (jids === undefined) {
const chats = await shared_api.chatboxes.get();
return chats.filter(c => c.get('type') === shared_converse.HEADLINES_TYPE);
} else if (typeof jids === 'string') {
return _get(jids);
}
return Promise.all(jids.map(jid => _get(jid)));
}
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/headlines/utils.js
/**
* Handler method for all incoming messages of type "headline".
* @param { Element } stanza
*/
async function onHeadlineMessage(stanza) {
if (isHeadline(stanza) || isServerMessage(stanza)) {
const from_jid = stanza.getAttribute('from');
await shared_api.waitUntil('rosterInitialized');
if (from_jid.includes('@') && !shared_converse.roster.get(from_jid) && !shared_api.settings.get("allow_non_roster_messaging")) {
return;
}
if (stanza.querySelector('body') === null) {
// Avoid creating a chat box if we have nothing to show inside it.
return;
}
const chatbox = shared_converse.chatboxes.create({
'id': from_jid,
'jid': from_jid,
'type': shared_converse.HEADLINES_TYPE,
'from': from_jid
});
const attrs = await parseMessage(stanza, shared_converse);
await chatbox.createMessage(attrs);
shared_api.trigger('message', {
chatbox,
stanza,
attrs
});
}
}
;// CONCATENATED MODULE: ./src/headless/plugins/headlines/index.js
/**
* @module converse-headlines
* @copyright 2022, the Converse.js contributors
*/
converse.plugins.add('converse-headlines', {
dependencies: ["converse-chat"],
overrides: {
// Overrides mentioned here will be picked up by converse.js's
// plugin architecture they will replace existing methods on the
// relevant objects or classes.
ChatBoxes: {
model(attrs, options) {
const {
_converse
} = this.__super__;
if (attrs.type == _converse.HEADLINES_TYPE) {
return new _converse.HeadlinesFeed(attrs, options);
} else {
return this.__super__.model.apply(this, arguments);
}
}
}
},
initialize() {
/**
* Shows headline messages
* @class
* @namespace _converse.HeadlinesFeed
* @memberOf _converse
*/
shared_converse.HeadlinesFeed = HeadlinesFeed;
function registerHeadlineHandler() {
shared_converse.connection.addHandler(m => onHeadlineMessage(m) || true, null, 'message');
}
shared_api.listen.on('connected', registerHeadlineHandler);
shared_api.listen.on('reconnected', registerHeadlineHandler);
Object.assign(shared_api, headlines_api);
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/mam/placeholder.js
const placeholder_u = converse.env.utils;
class MAMPlaceholderMessage extends Model {
defaults() {
// eslint-disable-line class-methods-use-this
return {
'msgid': placeholder_u.getUniqueId(),
'is_ephemeral': false
};
}
}
;// CONCATENATED MODULE: ./src/headless/shared/rsm.js
/**
* @module converse-rsm
* @copyright The Converse.js contributors
* @license Mozilla Public License (MPLv2)
* @description XEP-0059 Result Set Management
* Some code taken from the Strophe RSM plugin, licensed under the MIT License
* Copyright 2006-2017 Strophe (https://github.com/strophe/strophejs)
*/
const {
Strophe: rsm_Strophe,
$build: rsm_$build
} = converse.env;
rsm_Strophe.addNamespace('RSM', 'http://jabber.org/protocol/rsm');
/**
* @typedef { Object } RSMQueryParameters
* [XEP-0059 RSM](https://xmpp.org/extensions/xep-0059.html) Attributes that can be used to filter query results
* @property { String } [after] - The XEP-0359 stanza ID of a message after which messages should be returned. Implies forward paging.
* @property { String } [before] - The XEP-0359 stanza ID of a message before which messages should be returned. Implies backward paging.
* @property { number } [index=0] - The index of the results page to return.
* @property { number } [max] - The maximum number of items to return.
*/
const RSM_QUERY_PARAMETERS = ['after', 'before', 'index', 'max'];
const rsm_toNumber = v => Number(v);
const rsm_toString = v => v.toString();
const RSM_TYPES = {
'after': rsm_toString,
'before': rsm_toString,
'count': rsm_toNumber,
'first': rsm_toString,
'index': rsm_toNumber,
'last': rsm_toString,
'max': rsm_toNumber
};
const isUndefined = x => typeof x === 'undefined';
// This array contains both query attributes and response attributes
const RSM_ATTRIBUTES = Object.keys(RSM_TYPES);
/**
* Instances of this class are used to page through query results according to XEP-0059 Result Set Management
* @class RSM
*/
class RSM {
static getQueryParameters() {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return lodash_es_pick(options, RSM_QUERY_PARAMETERS);
}
static parseXMLResult(set) {
const result = {};
for (var i = 0; i < RSM_ATTRIBUTES.length; i++) {
const attr = RSM_ATTRIBUTES[i];
const elem = set.getElementsByTagName(attr)[0];
if (!isUndefined(elem) && elem !== null) {
result[attr] = RSM_TYPES[attr](rsm_Strophe.getText(elem));
if (attr == 'first') {
result.index = RSM_TYPES['index'](elem.getAttribute('index'));
}
}
}
return result;
}
/**
* Create a new RSM instance
* @param { Object } options - Configuration options
* @constructor
*/
constructor() {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.query = RSM.getQueryParameters(options);
this.result = options.xml ? RSM.parseXMLResult(options.xml) : {};
}
/**
* Returns a `<set>` XML element that confirms to XEP-0059 Result Set Management.
* The element is constructed based on the {@link module:converse-rsm~RSMQueryParameters}
* that are set on this RSM instance.
* @returns { Element }
*/
toXML() {
const xml = rsm_$build('set', {
xmlns: rsm_Strophe.NS.RSM
});
const reducer = (xml, a) => !isUndefined(this.query[a]) ? xml.c(a).t((this.query[a] || '').toString()).up() : xml;
return RSM_QUERY_PARAMETERS.reduce(reducer, xml).tree();
}
next(max, before) {
const options = Object.assign({}, this.query, {
after: this.result.last,
before,
max
});
return new RSM(options);
}
previous(max, after) {
const options = Object.assign({}, this.query, {
after,
before: this.result.first,
max
});
return new RSM(options);
}
}
shared_converse.RSM_ATTRIBUTES = RSM_ATTRIBUTES;
shared_converse.RSM = RSM;
;// CONCATENATED MODULE: ./src/headless/plugins/mam/api.js
const {
Strophe: mam_api_Strophe,
$iq: mam_api_$iq,
dayjs
} = converse.env;
const {
NS: api_NS
} = mam_api_Strophe;
const mam_api_u = converse.env.utils;
/* harmony default export */ const mam_api = ({
/**
* The [XEP-0313](https://xmpp.org/extensions/xep-0313.html) Message Archive Management API
*
* Enables you to query an XMPP server for archived messages.
*
* See also the [message-archiving](/docs/html/configuration.html#message-archiving)
* option in the configuration settings section, which you'll
* usually want to use in conjunction with this API.
*
* @namespace _converse.api.archive
* @memberOf _converse.api
*/
archive: {
/**
* @typedef { module:converse-rsm~RSMQueryParameters } MAMFilterParameters
* Filter parameters which can be used to filter a MAM XEP-0313 archive
* @property { String } [end] - A date string in ISO-8601 format, before which messages should be returned. Implies backward paging.
* @property { String } [start] - A date string in ISO-8601 format, after which messages should be returned. Implies forward paging.
* @property { String } [with] - A JID against which to match messages, according to either their `to` or `from` attributes.
* An item in a MUC archive matches if the publisher of the item matches the JID.
* If `with` is omitted, all messages that match the rest of the query will be returned, regardless of to/from
* addresses of each message.
*/
/**
* The options that can be passed in to the {@link _converse.api.archive.query } method
* @typedef { module:converse-mam~MAMFilterParameters } ArchiveQueryOptions
* @property { Boolean } [groupchat=false] - Whether the MAM archive is for a groupchat.
*/
/**
* Query for archived messages.
*
* The options parameter can also be an instance of
* RSM to enable easy querying between results pages.
*
* @method _converse.api.archive.query
* @param { module:converse-mam~ArchiveQueryOptions } options - An object containing query parameters
* @throws {Error} An error is thrown if the XMPP server responds with an error.
* @returns { Promise<module:converse-mam~MAMQueryResult> } A promise which resolves
* to a {@link module:converse-mam~MAMQueryResult } object.
*
* @example
* // Requesting all archived messages
* // ================================
* //
* // The simplest query that can be made is to simply not pass in any parameters.
* // Such a query will return all archived messages for the current user.
*
* let result;
* try {
* result = await api.archive.query();
* } catch (e) {
* // The query was not successful, perhaps inform the user?
* // The IQ stanza returned by the XMPP server is passed in, so that you
* // may inspect it and determine what the problem was.
* }
* // Do something with the messages, like showing them in your webpage.
* result.messages.forEach(m => this.showMessage(m));
*
* @example
* // Requesting all archived messages for a particular contact or room
* // =================================================================
* //
* // To query for messages sent between the current user and another user or room,
* // the query options need to contain the the JID (Jabber ID) of the user or
* // room under the `with` key.
*
* // For a particular user
* let result;
* try {
* result = await api.archive.query({'with': 'john@doe.net'});
* } catch (e) {
* // The query was not successful
* }
*
* // For a particular room
* let result;
* try {
* result = await api.archive.query({'with': 'discuss@conference.doglovers.net', 'groupchat': true});
* } catch (e) {
* // The query was not successful
* }
*
* @example
* // Requesting all archived messages before or after a certain date
* // ===============================================================
* //
* // The `start` and `end` parameters are used to query for messages
* // within a certain timeframe. The passed in date values may either be ISO8601
* // formatted date strings, or JavaScript Date objects.
*
* const options = {
* 'with': 'john@doe.net',
* 'start': '2010-06-07T00:00:00Z',
* 'end': '2010-07-07T13:23:54Z'
* };
* let result;
* try {
* result = await api.archive.query(options);
* } catch (e) {
* // The query was not successful
* }
*
* @example
* // Limiting the amount of messages returned
* // ========================================
* //
* // The amount of returned messages may be limited with the `max` parameter.
* // By default, the messages are returned from oldest to newest.
*
* // Return maximum 10 archived messages
* let result;
* try {
* result = await api.archive.query({'with': 'john@doe.net', 'max':10});
* } catch (e) {
* // The query was not successful
* }
*
* @example
* // Paging forwards through a set of archived messages
* // ==================================================
* //
* // When limiting the amount of messages returned per query, you might want to
* // repeatedly make a further query to fetch the next batch of messages.
* //
* // To simplify this usecase for you, the callback method receives not only an array
* // with the returned archived messages, but also a special RSM (*Result Set Management*)
* // object which contains the query parameters you passed in, as well
* // as two utility methods `next`, and `previous`.
* //
* // When you call one of these utility methods on the returned RSM object, and then
* // pass the result into a new query, you'll receive the next or previous batch of
* // archived messages. Please note, when calling these methods, pass in an integer
* // to limit your results.
*
* const options = {'with': 'john@doe.net', 'max':10};
* let result;
* try {
* result = await api.archive.query(options);
* } catch (e) {
* // The query was not successful
* }
* // Do something with the messages, like showing them in your webpage.
* result.messages.forEach(m => this.showMessage(m));
*
* while (!result.complete) {
* try {
* result = await api.archive.query(Object.assign(options, rsm.next(10).query));
* } catch (e) {
* // The query was not successful
* }
* // Do something with the messages, like showing them in your webpage.
* result.messages.forEach(m => this.showMessage(m));
* }
*
* @example
* // Paging backwards through a set of archived messages
* // ===================================================
* //
* // To page backwards through the archive, you need to know the UID of the message
* // which you'd like to page backwards from and then pass that as value for the
* // `before` parameter. If you simply want to page backwards from the most recent
* // message, pass in the `before` parameter with an empty string value `''`.
*
* let result;
* const options = {'before': '', 'max':5};
* try {
* result = await api.archive.query(options);
* } catch (e) {
* // The query was not successful
* }
* // Do something with the messages, like showing them in your webpage.
* result.messages.forEach(m => this.showMessage(m));
*
* // Now we query again, to get the previous batch.
* try {
* result = await api.archive.query(Object.assign(options, rsm.previous(5).query));
* } catch (e) {
* // The query was not successful
* }
* // Do something with the messages, like showing them in your webpage.
* result.messages.forEach(m => this.showMessage(m));
*
*/
async query(options) {
if (!shared_api.connection.connected()) {
throw new Error('Can\'t call `api.archive.query` before having established an XMPP session');
}
const attrs = {
'type': 'set'
};
if (options && options.groupchat) {
if (!options['with']) {
throw new Error('You need to specify a "with" value containing ' + 'the chat room JID, when querying groupchat messages.');
}
attrs.to = options['with'];
}
const jid = attrs.to || shared_converse.bare_jid;
const supported = await shared_api.disco.supports(api_NS.MAM, jid);
if (!supported) {
log.warn(`Did not fetch MAM archive for ${jid} because it doesn't support ${api_NS.MAM}`);
return {
'messages': []
};
}
const queryid = mam_api_u.getUniqueId();
const stanza = mam_api_$iq(attrs).c('query', {
'xmlns': api_NS.MAM,
'queryid': queryid
});
if (options) {
stanza.c('x', {
'xmlns': api_NS.XFORM,
'type': 'submit'
}).c('field', {
'var': 'FORM_TYPE',
'type': 'hidden'
}).c('value').t(api_NS.MAM).up().up();
if (options['with'] && !options.groupchat) {
stanza.c('field', {
'var': 'with'
}).c('value').t(options['with']).up().up();
}
['start', 'end'].forEach(t => {
if (options[t]) {
const date = dayjs(options[t]);
if (date.isValid()) {
stanza.c('field', {
'var': t
}).c('value').t(date.toISOString()).up().up();
} else {
throw new TypeError(`archive.query: invalid date provided for: ${t}`);
}
}
});
stanza.up();
const rsm = new RSM(options);
if (Object.keys(rsm.query).length) {
stanza.cnode(rsm.toXML());
}
}
const messages = [];
const message_handler = shared_converse.connection.addHandler(stanza => {
const result = sizzle_default()(`message > result[xmlns="${api_NS.MAM}"]`, stanza).pop();
if (result === undefined || result.getAttribute('queryid') !== queryid) {
return true;
}
const from = stanza.getAttribute('from') || shared_converse.bare_jid;
if (options.groupchat) {
if (from !== options['with']) {
log.warn(`Ignoring alleged groupchat MAM message from ${stanza.getAttribute('from')}`);
return true;
}
} else if (from !== shared_converse.bare_jid) {
log.warn(`Ignoring alleged MAM message from ${stanza.getAttribute('from')}`);
return true;
}
messages.push(stanza);
return true;
}, api_NS.MAM);
let error;
const timeout = shared_api.settings.get('message_archiving_timeout');
const iq_result = await shared_api.sendIQ(stanza, timeout, false);
if (iq_result === null) {
const {
__
} = shared_converse;
const err_msg = __("Timeout while trying to fetch archived messages.");
log.error(err_msg);
error = new TimeoutError(err_msg);
return {
messages,
error
};
} else if (mam_api_u.isErrorStanza(iq_result)) {
const {
__
} = shared_converse;
const err_msg = __('An error occurred while querying for archived messages.');
log.error(err_msg);
log.error(iq_result);
error = new Error(err_msg);
return {
messages,
error
};
}
shared_converse.connection.deleteHandler(message_handler);
let rsm;
const fin = iq_result && sizzle_default()(`fin[xmlns="${api_NS.MAM}"]`, iq_result).pop();
const complete = fin?.getAttribute('complete') === 'true';
const set = sizzle_default()(`set[xmlns="${api_NS.RSM}"]`, fin).pop();
if (set) {
rsm = new RSM({
...options,
'xml': set
});
}
/**
* @typedef { Object } MAMQueryResult
* @property { Array } messages
* @property { RSM } [rsm] - An instance of {@link RSM}.
* You can call `next()` or `previous()` on this instance,
* to get the RSM query parameters for the next or previous
* page in the result set.
* @property { Boolean } complete
* @property { Error } [error]
*/
return {
messages,
rsm,
complete
};
}
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/mam/utils.js
const {
Strophe: mam_utils_Strophe,
$iq: mam_utils_$iq
} = converse.env;
const {
NS: utils_NS
} = mam_utils_Strophe;
const mam_utils_u = converse.env.utils;
function onMAMError(iq) {
if (iq?.querySelectorAll('feature-not-implemented').length) {
log.warn(`Message Archive Management (XEP-0313) not supported by ${iq.getAttribute('from')}`);
} else {
log.error(`Error while trying to set archiving preferences for ${iq.getAttribute('from')}.`);
log.error(iq);
}
}
/**
* Handle returned IQ stanza containing Message Archive
* Management (XEP-0313) preferences.
*
* XXX: For now we only handle the global default preference.
* The XEP also provides for per-JID preferences, which is
* currently not supported in converse.js.
*
* Per JID preferences will be set in chat boxes, so it'll
* probbaly be handled elsewhere in any case.
*/
function onMAMPreferences(iq, feature) {
const preference = sizzle_default()(`prefs[xmlns="${utils_NS.MAM}"]`, iq).pop();
const default_pref = preference.getAttribute('default');
if (default_pref !== shared_api.settings.get('message_archiving')) {
const stanza = mam_utils_$iq({
'type': 'set'
}).c('prefs', {
'xmlns': utils_NS.MAM,
'default': shared_api.settings.get('message_archiving')
});
Array.from(preference.children).forEach(child => stanza.cnode(child).up());
// XXX: Strictly speaking, the server should respond with the updated prefs
// (see example 18: https://xmpp.org/extensions/xep-0313.html#config)
// but Prosody doesn't do this, so we don't rely on it.
shared_api.sendIQ(stanza).then(() => feature.save({
'preferences': {
'default': shared_api.settings.get('message_archiving')
}
})).catch(shared_converse.onMAMError);
} else {
feature.save({
'preferences': {
'default': shared_api.settings.get('message_archiving')
}
});
}
}
function getMAMPrefsFromFeature(feature) {
const prefs = feature.get('preferences') || {};
if (feature.get('var') !== utils_NS.MAM || shared_api.settings.get('message_archiving') === undefined) {
return;
}
if (prefs['default'] !== shared_api.settings.get('message_archiving')) {
shared_api.sendIQ(mam_utils_$iq({
'type': 'get'
}).c('prefs', {
'xmlns': utils_NS.MAM
})).then(iq => shared_converse.onMAMPreferences(iq, feature)).catch(shared_converse.onMAMError);
}
}
function preMUCJoinMAMFetch(muc) {
if (!shared_api.settings.get('muc_show_logs_before_join') || !muc.features.get('mam_enabled') || muc.get('prejoin_mam_fetched')) {
return;
}
fetchNewestMessages(muc);
muc.save({
'prejoin_mam_fetched': true
});
}
async function handleMAMResult(model, result, query, options, should_page) {
await shared_api.emojis.initialize();
const is_muc = model.get('type') === shared_converse.CHATROOMS_TYPE;
const doParseMessage = s => is_muc ? parseMUCMessage(s, model) : parseMessage(s);
const messages = await Promise.all(result.messages.map(doParseMessage));
result.messages = messages;
/**
* Synchronous event which allows listeners to first do some
* work based on the MAM result before calling the handlers here.
* @event _converse#MAMResult
*/
const data = {
query,
'chatbox': model,
messages
};
await shared_api.trigger('MAMResult', data, {
'synchronous': true
});
messages.forEach(m => model.queueMessage(m));
if (result.error) {
const event_id = result.error.retry_event_id = mam_utils_u.getUniqueId();
shared_api.listen.once(event_id, () => fetchArchivedMessages(model, options, should_page));
model.createMessageFromError(result.error);
}
}
/**
* @typedef { Object } MAMOptions
* A map of MAM related options that may be passed to fetchArchivedMessages
* @param { number } [options.max] - The maximum number of items to return.
* Defaults to "archived_messages_page_size"
* @param { string } [options.after] - The XEP-0359 stanza ID of a message
* after which messages should be returned. Implies forward paging.
* @param { string } [options.before] - The XEP-0359 stanza ID of a message
* before which messages should be returned. Implies backward paging.
* @param { string } [options.end] - A date string in ISO-8601 format,
* before which messages should be returned. Implies backward paging.
* @param { string } [options.start] - A date string in ISO-8601 format,
* after which messages should be returned. Implies forward paging.
* @param { string } [options.with] - The JID of the entity with
* which messages were exchanged.
* @param { boolean } [options.groupchat] - True if archive in groupchat.
*/
/**
* Fetch XEP-0313 archived messages based on the passed in criteria.
* @param { ChatBox | ChatRoom } model
* @param { MAMOptions } [options]
* @param { ('forwards'|'backwards'|null)} [should_page=null] - Determines whether
* this function should recursively page through the entire result set if a limited
* number of results were returned.
*/
async function fetchArchivedMessages(model) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let should_page = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
if (model.disable_mam) {
return;
}
const is_muc = model.get('type') === shared_converse.CHATROOMS_TYPE;
const mam_jid = is_muc ? model.get('jid') : shared_converse.bare_jid;
if (!(await shared_api.disco.supports(utils_NS.MAM, mam_jid))) {
return;
}
const max = shared_api.settings.get('archived_messages_page_size');
const query = Object.assign({
'groupchat': is_muc,
'max': max,
'with': model.get('jid')
}, options);
const result = await shared_api.archive.query(query);
await handleMAMResult(model, result, query, options, should_page);
if (result.rsm && !result.complete) {
if (should_page) {
if (should_page === 'forwards') {
options = result.rsm.next(max, options.before).query;
} else if (should_page === 'backwards') {
options = result.rsm.previous(max, options.after).query;
}
return fetchArchivedMessages(model, options, should_page);
} else {
createPlaceholder(model, options, result);
}
}
}
/**
* Create a placeholder message which is used to indicate gaps in the history.
* @param { _converse.ChatBox | _converse.ChatRoom } model
* @param { MAMOptions } options
* @param { object } result - The RSM result object
*/
async function createPlaceholder(model, options, result) {
if (options.before == '' && (model.messages.length === 0 || !options.start)) {
// Fetching the latest MAM messages with an empty local cache
return;
}
if (options.before && !options.start) {
// Infinite scrolling upward
return;
}
if (options.before == null) {
// eslint-disable-line no-eq-null
// Adding placeholders when paging forwards is not supported yet,
// since currently with standard Converse, we only page forwards
// when fetching the entire history (i.e. no gaps should arise).
return;
}
const msgs = await Promise.all(result.messages);
const {
rsm
} = result;
const key = `stanza_id ${model.get('jid')}`;
const adjacent_message = msgs.find(m => m[key] === rsm.result.first);
const msg_data = {
'template_hook': 'getMessageTemplate',
'time': new Date(new Date(adjacent_message['time']) - 1).toISOString(),
'before': rsm.result.first,
'start': options.start
};
model.messages.add(new MAMPlaceholderMessage(msg_data));
}
/**
* Fetches messages that might have been archived *after*
* the last archived message in our local cache.
* @param { _converse.ChatBox | _converse.ChatRoom }
*/
function fetchNewestMessages(model) {
if (model.disable_mam) {
return;
}
const most_recent_msg = model.getMostRecentMessage();
// if clear_messages_on_reconnection is true, than any recent messages
// must have been received *after* connection and we instead must query
// for earlier messages
if (most_recent_msg && !shared_api.settings.get('clear_messages_on_reconnection')) {
const should_page = shared_api.settings.get('mam_request_all_pages');
if (should_page) {
const stanza_id = most_recent_msg.get(`stanza_id ${model.get('jid')}`);
if (stanza_id) {
fetchArchivedMessages(model, {
'after': stanza_id
}, 'forwards');
} else {
fetchArchivedMessages(model, {
'start': most_recent_msg.get('time')
}, 'forwards');
}
} else {
fetchArchivedMessages(model, {
'before': '',
'start': most_recent_msg.get('time')
});
}
} else {
fetchArchivedMessages(model, {
'before': ''
});
}
}
;// CONCATENATED MODULE: ./src/headless/plugins/mam/index.js
/**
* @description XEP-0313 Message Archive Management
* @copyright 2022, the Converse.js contributors
* @license Mozilla Public License (MPLv2)
*/
const {
Strophe: mam_Strophe
} = converse.env;
const {
NS: mam_NS
} = mam_Strophe;
converse.plugins.add('converse-mam', {
dependencies: ['converse-disco', 'converse-muc'],
initialize() {
shared_api.settings.extend({
archived_messages_page_size: '50',
mam_request_all_pages: true,
message_archiving: undefined,
// Supported values are 'always', 'never', 'roster' (https://xmpp.org/extensions/xep-0313.html#prefs)
message_archiving_timeout: 20000 // Time (in milliseconds) to wait before aborting MAM request
});
Object.assign(shared_api, mam_api);
// This is mainly done to aid with tests
Object.assign(shared_converse, {
onMAMError: onMAMError,
onMAMPreferences: onMAMPreferences,
handleMAMResult: handleMAMResult,
MAMPlaceholderMessage: MAMPlaceholderMessage
});
/************************ Event Handlers ************************/
shared_api.listen.on('addClientFeatures', () => shared_api.disco.own.features.add(mam_NS.MAM));
shared_api.listen.on('serviceDiscovered', getMAMPrefsFromFeature);
shared_api.listen.on('chatRoomViewInitialized', view => {
if (shared_api.settings.get('muc_show_logs_before_join')) {
preMUCJoinMAMFetch(view.model);
// If we want to show MAM logs before entering the MUC, we need
// to be informed once it's clear that this MUC supports MAM.
view.model.features.on('change:mam_enabled', () => preMUCJoinMAMFetch(view.model));
}
});
shared_api.listen.on('enteredNewRoom', muc => muc.features.get('mam_enabled') && fetchNewestMessages(muc));
shared_api.listen.on('chatReconnected', chat => {
if (chat.get('type') === shared_converse.PRIVATE_CHAT_TYPE) {
fetchNewestMessages(chat);
}
});
shared_api.listen.on('afterMessagesFetched', chat => {
if (chat.get('type') === shared_converse.PRIVATE_CHAT_TYPE) {
fetchNewestMessages(chat);
}
});
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/ping/utils.js
const {
Strophe: ping_utils_Strophe,
$iq: ping_utils_$iq
} = converse.env;
let lastStanzaDate;
function utils_onWindowStateChanged(data) {
data.state === 'visible' && shared_api.ping(null, 5000);
}
function setLastStanzaDate(date) {
lastStanzaDate = date;
}
function pong(ping) {
lastStanzaDate = new Date();
const from = ping.getAttribute('from');
const id = ping.getAttribute('id');
const iq = ping_utils_$iq({
type: 'result',
to: from,
id: id
});
shared_converse.connection.sendIQ(iq);
return true;
}
function registerPongHandler() {
const {
connection
} = shared_converse;
if (connection.disco) {
shared_api.disco.own.features.add(ping_utils_Strophe.NS.PING);
}
return connection.addHandler(pong, ping_utils_Strophe.NS.PING, "iq", "get");
}
function registerPingHandler() {
shared_converse.connection.addHandler(() => {
if (shared_api.settings.get('ping_interval') > 0) {
// Handler on each stanza, saves the received date
// in order to ping only when needed.
lastStanzaDate = new Date();
return true;
}
});
}
let intervalId;
function registerHandlers() {
// Wrapper so that we can spy on registerPingHandler in tests
registerPongHandler();
registerPingHandler();
clearInterval(intervalId);
intervalId = setInterval(onEverySecond, 1000);
}
function unregisterIntervalHandler() {
clearInterval(intervalId);
}
function onEverySecond() {
if (shared_converse.isTestEnv() || !shared_api.connection.authenticated()) {
return;
}
const ping_interval = shared_api.settings.get('ping_interval');
if (ping_interval > 0) {
const now = new Date();
lastStanzaDate = lastStanzaDate ?? now;
if ((now - lastStanzaDate) / 1000 > ping_interval) {
shared_api.ping();
}
}
}
;// CONCATENATED MODULE: ./src/headless/plugins/ping/api.js
const {
Strophe: ping_api_Strophe,
$iq: ping_api_$iq,
u: ping_api_u
} = converse.env;
/* harmony default export */ const ping_api = ({
/**
* Pings the entity represented by the passed in JID by sending an IQ stanza to it.
* @method api.ping
* @param { String } [jid] - The JID of the service to ping
* If the ping is sent out to the user's bare JID and no response is received it will attempt to reconnect.
* @param { number } [timeout] - The amount of time in
* milliseconds to wait for a response. The default is 10000;
* @returns { Boolean | null }
* Whether the pinged entity responded with a non-error IQ stanza.
* If we already know we're not connected, no ping is sent out and `null` is returned.
*/
async ping(jid, timeout) {
if (!shared_api.connection.authenticated()) {
log.warn("Not pinging when we know we're not authenticated");
return null;
}
// XXX: We could first check here if the server advertised that it supports PING.
// However, some servers don't advertise while still responding to pings
// const feature = _converse.disco_entities[_converse.domain].features.findWhere({'var': Strophe.NS.PING});
setLastStanzaDate(new Date());
jid = jid || ping_api_Strophe.getDomainFromJid(shared_converse.bare_jid);
const iq = ping_api_$iq({
'type': 'get',
'to': jid,
'id': ping_api_u.getUniqueId('ping')
}).c('ping', {
'xmlns': ping_api_Strophe.NS.PING
});
const result = await shared_api.sendIQ(iq, timeout || 10000, false);
if (result === null) {
log.warn(`Timeout while pinging ${jid}`);
if (jid === ping_api_Strophe.getDomainFromJid(shared_converse.bare_jid)) {
shared_api.connection.reconnect();
}
return false;
} else if (ping_api_u.isErrorStanza(result)) {
log.error(`Error while pinging ${jid}`);
log.error(result);
return false;
}
return true;
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/ping/index.js
/**
* @description
* Converse.js plugin which add support for application-level pings
* as specified in XEP-0199 XMPP Ping.
* @copyright 2022, the Converse.js contributors
* @license Mozilla Public License (MPLv2)
*/
const {
Strophe: ping_Strophe
} = converse.env;
ping_Strophe.addNamespace('PING', "urn:xmpp:ping");
converse.plugins.add('converse-ping', {
initialize() {
shared_api.settings.extend({
ping_interval: 60 //in seconds
});
Object.assign(shared_api, ping_api);
shared_api.listen.on('connected', registerHandlers);
shared_api.listen.on('reconnected', registerHandlers);
shared_api.listen.on('disconnected', unregisterIntervalHandler);
shared_api.listen.on('windowStateChanged', utils_onWindowStateChanged);
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/pubsub.js
/**
* @module converse-pubsub
* @copyright The Converse.js contributors
* @license Mozilla Public License (MPLv2)
*/
const {
Strophe: pubsub_Strophe,
$iq: pubsub_$iq
} = converse.env;
pubsub_Strophe.addNamespace('PUBSUB_ERROR', pubsub_Strophe.NS.PUBSUB + "#errors");
converse.plugins.add('converse-pubsub', {
dependencies: ["converse-disco"],
initialize() {
/************************ BEGIN API ************************/
// We extend the default converse.js API to add methods specific to MUC groupchats.
Object.assign(shared_converse.api, {
/**
* The "pubsub" namespace groups methods relevant to PubSub
*
* @namespace _converse.api.pubsub
* @memberOf _converse.api
*/
'pubsub': {
/**
* Publshes an item to a PubSub node
*
* @method _converse.api.pubsub.publish
* @param { string } jid The JID of the pubsub service where the node resides.
* @param { string } node The node being published to
* @param {Strophe.Builder} item The Strophe.Builder representation of the XML element being published
* @param { object } options An object representing the publisher options
* (see https://xmpp.org/extensions/xep-0060.html#publisher-publish-options)
* @param { boolean } strict_options Indicates whether the publisher
* options are a strict requirement or not. If they're NOT
* strict, then Converse will publish to the node even if
* the publish options precondication cannot be met.
*/
async 'publish'(jid, node, item, options) {
let strict_options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
const stanza = pubsub_$iq({
'from': shared_converse.bare_jid,
'type': 'set',
'to': jid
}).c('pubsub', {
'xmlns': pubsub_Strophe.NS.PUBSUB
}).c('publish', {
'node': node
}).cnode(item.tree()).up().up();
if (options) {
jid = jid || shared_converse.bare_jid;
if (await shared_api.disco.supports(pubsub_Strophe.NS.PUBSUB + '#publish-options', jid)) {
stanza.c('publish-options').c('x', {
'xmlns': pubsub_Strophe.NS.XFORM,
'type': 'submit'
}).c('field', {
'var': 'FORM_TYPE',
'type': 'hidden'
}).c('value').t(`${pubsub_Strophe.NS.PUBSUB}#publish-options`).up().up();
Object.keys(options).forEach(k => stanza.c('field', {
'var': k
}).c('value').t(options[k]).up().up());
} else {
log.warn(`_converse.api.publish: ${jid} does not support #publish-options, ` + `so we didn't set them even though they were provided.`);
}
}
try {
await shared_api.sendIQ(stanza);
} catch (iq) {
if (iq instanceof Element && strict_options && iq.querySelector(`precondition-not-met[xmlns="${pubsub_Strophe.NS.PUBSUB_ERROR}"]`)) {
// The publish-options precondition couldn't be
// met. We re-publish but without publish-options.
const el = stanza.tree();
el.querySelector('publish-options').outerHTML = '';
log.warn(`PubSub: Republishing without publish options. ${el.outerHTML}`);
await shared_api.sendIQ(el);
} else {
throw iq;
}
}
}
}
});
/************************ END API ************************/
}
});
;// CONCATENATED MODULE: ./node_modules/lodash-es/isNumber.js
/** `Object#toString` result references. */
var isNumber_numberTag = '[object Number]';
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(lodash_es_isObjectLike(value) && _baseGetTag(value) == isNumber_numberTag);
}
/* harmony default export */ const lodash_es_isNumber = (isNumber);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isNaN.js
/**
* Checks if `value` is `NaN`.
*
* **Note:** This method is based on
* [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
* global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
* `undefined` and other non-number values.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN_isNaN(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return lodash_es_isNumber(value) && value != +value;
}
/* harmony default export */ const lodash_es_isNaN = (isNaN_isNaN);
;// CONCATENATED MODULE: ./src/headless/plugins/status/status.js
const {
Strophe: status_Strophe,
$pres: status_$pres
} = converse.env;
class XMPPStatus extends Model {
defaults() {
// eslint-disable-line class-methods-use-this
return {
"status": shared_api.settings.get("default_state")
};
}
initialize() {
this.on('change', item => {
if (!lodash_es_isObject(item.changed)) {
return;
}
if ('status' in item.changed || 'status_message' in item.changed) {
shared_api.user.presence.send(this.get('status'), null, this.get('status_message'));
}
});
}
getDisplayName() {
return this.getFullname() || this.getNickname() || shared_converse.bare_jid;
}
getNickname() {
// eslint-disable-line class-methods-use-this
return shared_api.settings.get('nickname');
}
getFullname() {
// eslint-disable-line class-methods-use-this
return ''; // Gets overridden in converse-vcard
}
/** Constructs a presence stanza
* @param { string } [type]
* @param { string } [to] - The JID to which this presence should be sent
* @param { string } [status_message]
*/
async constructPresence(type) {
let to = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
let status_message = arguments.length > 2 ? arguments[2] : undefined;
type = typeof type === 'string' ? type : this.get('status') || shared_api.settings.get("default_state");
status_message = typeof status_message === 'string' ? status_message : this.get('status_message');
let presence;
if (type === 'subscribe') {
presence = status_$pres({
to,
type
});
const {
xmppstatus
} = shared_converse;
const nick = xmppstatus.getNickname();
if (nick) presence.c('nick', {
'xmlns': status_Strophe.NS.NICK
}).t(nick).up();
} else if (type === 'unavailable' || type === 'probe' || type === 'error' || type === 'unsubscribe' || type === 'unsubscribed' || type === 'subscribed') {
presence = status_$pres({
to,
type
});
} else if (type === 'offline') {
presence = status_$pres({
to,
type: 'unavailable'
});
} else if (type === 'online') {
presence = status_$pres({
to
});
} else {
presence = status_$pres({
to
}).c('show').t(type).up();
}
if (status_message) presence.c('status').t(status_message).up();
const priority = shared_api.settings.get("priority");
presence.c('priority').t(lodash_es_isNaN(Number(priority)) ? 0 : priority).up();
const {
idle,
idle_seconds
} = shared_converse;
if (idle) {
const idle_since = new Date();
idle_since.setSeconds(idle_since.getSeconds() - idle_seconds);
presence.c('idle', {
xmlns: status_Strophe.NS.IDLE,
since: idle_since.toISOString()
});
}
/**
* *Hook* which allows plugins to modify a presence stanza
* @event _converse#constructedPresence
*/
presence = await shared_api.hook('constructedPresence', null, presence);
return presence;
}
}
;// CONCATENATED MODULE: ./src/headless/plugins/status/api.js
/* harmony default export */ const status_api = ({
/**
* Set and get the user's chat status, also called their *availability*.
* @namespace _converse.api.user.status
* @memberOf _converse.api.user
*/
status: {
/**
* Return the current user's availability status.
* @async
* @method _converse.api.user.status.get
* @example _converse.api.user.status.get();
*/
async get() {
await shared_api.waitUntil('statusInitialized');
return shared_converse.xmppstatus.get('status');
},
/**
* The user's status can be set to one of the following values:
*
* @async
* @method _converse.api.user.status.set
* @param { string } value The user's chat status (e.g. 'away', 'dnd', 'offline', 'online', 'unavailable' or 'xa')
* @param { string } [message] A custom status message
*
* @example _converse.api.user.status.set('dnd');
* @example _converse.api.user.status.set('dnd', 'In a meeting');
*/
async set(value, message) {
const data = {
'status': value
};
if (!Object.keys(constants_STATUS_WEIGHTS).includes(value)) {
throw new Error('Invalid availability value. See https://xmpp.org/rfcs/rfc3921.html#rfc.section.2.2.2.1');
}
if (typeof message === 'string') {
data.status_message = message;
}
await shared_api.waitUntil('statusInitialized');
shared_converse.xmppstatus.save(data);
},
/**
* Set and retrieve the user's custom status message.
*
* @namespace _converse.api.user.status.message
* @memberOf _converse.api.user.status
*/
message: {
/**
* @async
* @method _converse.api.user.status.message.get
* @returns { Promise<string> } The status message
* @example const message = _converse.api.user.status.message.get()
*/
async get() {
await shared_api.waitUntil('statusInitialized');
return shared_converse.xmppstatus.get('status_message');
},
/**
* @async
* @method _converse.api.user.status.message.set
* @param { string } status The status message
* @example _converse.api.user.status.message.set('In a meeting');
*/
async set(status) {
await shared_api.waitUntil('statusInitialized');
shared_converse.xmppstatus.save({
status_message: status
});
}
}
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/status/utils.js
const {
Strophe: status_utils_Strophe,
$build: status_utils_$build
} = converse.env;
function utils_onStatusInitialized(reconnecting) {
/**
* Triggered when the user's own chat status has been initialized.
* @event _converse#statusInitialized
* @example _converse.api.listen.on('statusInitialized', status => { ... });
* @example _converse.api.waitUntil('statusInitialized').then(() => { ... });
*/
shared_api.trigger('statusInitialized', reconnecting);
}
function initStatus(reconnecting) {
// If there's no xmppstatus obj, then we were never connected to
// begin with, so we set reconnecting to false.
reconnecting = shared_converse.xmppstatus === undefined ? false : reconnecting;
if (reconnecting) {
utils_onStatusInitialized(reconnecting);
} else {
const id = `converse.xmppstatus-${shared_converse.bare_jid}`;
shared_converse.xmppstatus = new shared_converse.XMPPStatus({
id
});
initStorage(shared_converse.xmppstatus, id, 'session');
shared_converse.xmppstatus.fetch({
'success': () => utils_onStatusInitialized(reconnecting),
'error': () => utils_onStatusInitialized(reconnecting),
'silent': true
});
}
}
function onUserActivity() {
/* Resets counters and flags relating to CSI and auto_away/auto_xa */
if (shared_converse.idle_seconds > 0) {
shared_converse.idle_seconds = 0;
}
if (!shared_converse.connection?.authenticated) {
// We can't send out any stanzas when there's no authenticated connection.
// This can happen when the connection reconnects.
return;
}
if (shared_converse.inactive) {
shared_converse.sendCSI(shared_converse.ACTIVE);
}
if (shared_converse.idle) {
shared_converse.idle = false;
shared_api.user.presence.send();
}
if (shared_converse.auto_changed_status === true) {
shared_converse.auto_changed_status = false;
// XXX: we should really remember the original state here, and
// then set it back to that...
shared_converse.xmppstatus.set('status', shared_api.settings.get("default_state"));
}
}
function utils_onEverySecond() {
/* An interval handler running every second.
* Used for CSI and the auto_away and auto_xa features.
*/
if (!shared_converse.connection?.authenticated) {
// We can't send out any stanzas when there's no authenticated connection.
// This can happen when the connection reconnects.
return;
}
const stat = shared_converse.xmppstatus.get('status');
shared_converse.idle_seconds++;
if (shared_api.settings.get("csi_waiting_time") > 0 && shared_converse.idle_seconds > shared_api.settings.get("csi_waiting_time") && !shared_converse.inactive) {
shared_converse.sendCSI(shared_converse.INACTIVE);
}
if (shared_api.settings.get("idle_presence_timeout") > 0 && shared_converse.idle_seconds > shared_api.settings.get("idle_presence_timeout") && !shared_converse.idle) {
shared_converse.idle = true;
shared_api.user.presence.send();
}
if (shared_api.settings.get("auto_away") > 0 && shared_converse.idle_seconds > shared_api.settings.get("auto_away") && stat !== 'away' && stat !== 'xa' && stat !== 'dnd') {
shared_converse.auto_changed_status = true;
shared_converse.xmppstatus.set('status', 'away');
} else if (shared_api.settings.get("auto_xa") > 0 && shared_converse.idle_seconds > shared_api.settings.get("auto_xa") && stat !== 'xa' && stat !== 'dnd') {
shared_converse.auto_changed_status = true;
shared_converse.xmppstatus.set('status', 'xa');
}
}
/**
* Send out a Client State Indication (XEP-0352)
* @function sendCSI
* @param { String } stat - The user's chat status
*/
function sendCSI(stat) {
shared_api.send(status_utils_$build(stat, {
xmlns: status_utils_Strophe.NS.CSI
}));
shared_converse.inactive = stat === shared_converse.INACTIVE ? true : false;
}
/**
* Set an interval of one second and register a handler for it.
* Required for the auto_away, auto_xa and csi_waiting_time features.
*/
function registerIntervalHandler() {
if (shared_api.settings.get("auto_away") < 1 && shared_api.settings.get("auto_xa") < 1 && shared_api.settings.get("csi_waiting_time") < 1 && shared_api.settings.get("idle_presence_timeout") < 1) {
// Waiting time of less then one second means features aren't used.
return;
}
shared_converse.idle_seconds = 0;
shared_converse.auto_changed_status = false; // Was the user's status changed by Converse?
const {
unloadevent
} = shared_converse;
window.addEventListener('click', shared_converse.onUserActivity);
window.addEventListener('focus', shared_converse.onUserActivity);
window.addEventListener('keypress', shared_converse.onUserActivity);
window.addEventListener('mousemove', shared_converse.onUserActivity);
window.addEventListener(unloadevent, shared_converse.onUserActivity, {
'once': true,
'passive': true
});
shared_converse.everySecondTrigger = window.setInterval(shared_converse.onEverySecond, 1000);
}
function addStatusToMUCJoinPresence(_, stanza) {
const {
xmppstatus
} = shared_converse;
const status = xmppstatus.get('status');
if (['away', 'chat', 'dnd', 'xa'].includes(status)) {
stanza.c('show').t(status).up();
}
const status_message = xmppstatus.get('status_message');
if (status_message) {
stanza.c('status').t(status_message).up();
}
return stanza;
}
;// CONCATENATED MODULE: ./src/headless/plugins/status/index.js
/**
* @copyright The Converse.js contributors
* @license Mozilla Public License (MPLv2)
*/
const {
Strophe: plugins_status_Strophe
} = converse.env;
plugins_status_Strophe.addNamespace('IDLE', 'urn:xmpp:idle:1');
converse.plugins.add('converse-status', {
initialize() {
shared_api.settings.extend({
auto_away: 0,
// Seconds after which user status is set to 'away'
auto_xa: 0,
// Seconds after which user status is set to 'xa'
csi_waiting_time: 0,
// Support for XEP-0352. Seconds before client is considered idle and CSI is sent out.
default_state: 'online',
idle_presence_timeout: 300,
// Seconds after which an idle presence is sent
priority: 0
});
shared_api.promises.add(['statusInitialized']);
shared_converse.XMPPStatus = XMPPStatus;
shared_converse.onUserActivity = onUserActivity;
shared_converse.onEverySecond = utils_onEverySecond;
shared_converse.sendCSI = sendCSI;
shared_converse.registerIntervalHandler = registerIntervalHandler;
Object.assign(shared_converse.api.user, status_api);
if (shared_api.settings.get("idle_presence_timeout") > 0) {
shared_api.listen.on('addClientFeatures', () => shared_api.disco.own.features.add(plugins_status_Strophe.NS.IDLE));
}
shared_api.listen.on('presencesInitialized', reconnecting => {
if (!reconnecting) {
shared_converse.registerIntervalHandler();
}
});
shared_api.listen.on('clearSession', () => {
if (shouldClearCache() && shared_converse.xmppstatus) {
shared_converse.xmppstatus.destroy();
delete shared_converse.xmppstatus;
shared_api.promises.add(['statusInitialized']);
}
});
shared_api.listen.on('connected', () => initStatus(false));
shared_api.listen.on('reconnected', () => initStatus(true));
shared_api.listen.on('constructedMUCPresence', addStatusToMUCJoinPresence);
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/roster/filter.js
const RosterFilter = Model.extend({
initialize() {
this.set({
'filter_text': '',
'filter_type': 'contacts',
'chat_state': 'online'
});
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/roster/utils.js
const {
$pres: utils_$pres
} = converse.env;
function initRoster() {
// Initialize the collections that represent the roster contacts and groups
const roster = shared_converse.roster = new shared_converse.RosterContacts();
let id = `converse.contacts-${shared_converse.bare_jid}`;
initStorage(roster, id);
const filter = shared_converse.roster_filter = new RosterFilter();
filter.id = `_converse.rosterfilter-${shared_converse.bare_jid}`;
initStorage(filter, filter.id);
filter.fetch();
id = `converse-roster-model-${shared_converse.bare_jid}`;
roster.data = new Model();
roster.data.id = id;
initStorage(roster.data, id);
roster.data.fetch();
/**
* Triggered once the `_converse.RosterContacts`
* been created, but not yet populated with data.
* This event is useful when you want to create views for these collections.
* @event _converse#chatBoxMaximized
* @example _converse.api.listen.on('rosterInitialized', () => { ... });
* @example _converse.api.waitUntil('rosterInitialized').then(() => { ... });
*/
shared_api.trigger('rosterInitialized');
}
/**
* Fetch all the roster groups, and then the roster contacts.
* Emit an event after fetching is done in each case.
* @private
* @param { Bool } ignore_cache - If set to to true, the local cache
* will be ignored it's guaranteed that the XMPP server
* will be queried for the roster.
*/
async function populateRoster() {
let ignore_cache = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (ignore_cache) {
shared_converse.send_initial_presence = true;
}
try {
await shared_converse.roster.fetchRosterContacts();
shared_api.trigger('rosterContactsFetched');
} catch (reason) {
log.error(reason);
} finally {
shared_converse.send_initial_presence && shared_api.user.presence.send();
}
}
function updateUnreadCounter(chatbox) {
const contact = shared_converse.roster?.get(chatbox.get('jid'));
contact?.save({
'num_unread': chatbox.get('num_unread')
});
}
function registerPresenceHandler() {
unregisterPresenceHandler();
shared_converse.presence_ref = shared_converse.connection.addHandler(presence => {
shared_converse.roster.presenceHandler(presence);
return true;
}, null, 'presence', null);
}
function unregisterPresenceHandler() {
if (shared_converse.presence_ref !== undefined) {
shared_converse.connection.deleteHandler(shared_converse.presence_ref);
delete shared_converse.presence_ref;
}
}
async function clearPresences() {
await shared_converse.presences?.clearStore();
}
/**
* Roster specific event handler for the clearSession event
*/
async function utils_onClearSession() {
await clearPresences();
if (shouldClearCache()) {
if (shared_converse.rostergroups) {
await shared_converse.rostergroups.clearStore();
delete shared_converse.rostergroups;
}
if (shared_converse.roster) {
shared_converse.roster.data?.destroy();
await shared_converse.roster.clearStore();
delete shared_converse.roster;
}
}
}
/**
* Roster specific event handler for the presencesInitialized event
* @param { Boolean } reconnecting
*/
function onPresencesInitialized(reconnecting) {
if (reconnecting) {
/**
* Similar to `rosterInitialized`, but instead pertaining to reconnection.
* This event indicates that the roster and its groups are now again
* available after Converse.js has reconnected.
* @event _converse#rosterReadyAfterReconnection
* @example _converse.api.listen.on('rosterReadyAfterReconnection', () => { ... });
*/
shared_api.trigger('rosterReadyAfterReconnection');
} else {
initRoster();
}
shared_converse.roster.onConnected();
registerPresenceHandler();
populateRoster(!shared_converse.connection.restored);
}
/**
* Roster specific event handler for the statusInitialized event
* @param { Boolean } reconnecting
*/
async function roster_utils_onStatusInitialized(reconnecting) {
if (reconnecting) {
// When reconnecting and not resuming a previous session,
// we clear all cached presence data, since it might be stale
// and we'll receive new presence updates
!shared_converse.connection.hasResumed() && (await clearPresences());
} else {
shared_converse.presences = new shared_converse.Presences();
const id = `converse.presences-${shared_converse.bare_jid}`;
initStorage(shared_converse.presences, id, 'session');
// We might be continuing an existing session, so we fetch
// cached presence data.
shared_converse.presences.fetch();
}
/**
* Triggered once the _converse.Presences collection has been
* initialized and its cached data fetched.
* Returns a boolean indicating whether this event has fired due to
* Converse having reconnected.
* @event _converse#presencesInitialized
* @type { bool }
* @example _converse.api.listen.on('presencesInitialized', reconnecting => { ... });
*/
shared_api.trigger('presencesInitialized', reconnecting);
}
/**
* Roster specific event handler for the chatBoxesInitialized event
*/
function onChatBoxesInitialized() {
shared_converse.chatboxes.on('change:num_unread', updateUnreadCounter);
shared_converse.chatboxes.on('add', chatbox => {
if (chatbox.get('type') === shared_converse.PRIVATE_CHAT_TYPE) {
chatbox.setRosterContact(chatbox.get('jid'));
}
});
}
/**
* Roster specific handler for the rosterContactsFetched promise
*/
function onRosterContactsFetched() {
shared_converse.roster.on('add', contact => {
// When a new contact is added, check if we already have a
// chatbox open for it, and if so attach it to the chatbox.
const chatbox = shared_converse.chatboxes.findWhere({
'jid': contact.get('jid')
});
chatbox?.setRosterContact(contact.get('jid'));
});
}
/**
* Reject or cancel another user's subscription to our presence updates.
* @function rejectPresenceSubscription
* @param { String } jid - The Jabber ID of the user whose subscription is being canceled
* @param { String } message - An optional message to the user
*/
function rejectPresenceSubscription(jid, message) {
const pres = utils_$pres({
to: jid,
type: "unsubscribed"
});
if (message && message !== "") {
pres.c("status").t(message);
}
shared_api.send(pres);
}
function contactsComparator(contact1, contact2) {
const status1 = contact1.presence.get('show') || 'offline';
const status2 = contact2.presence.get('show') || 'offline';
if (STATUS_WEIGHTS[status1] === STATUS_WEIGHTS[status2]) {
const name1 = contact1.getDisplayName().toLowerCase();
const name2 = contact2.getDisplayName().toLowerCase();
return name1 < name2 ? -1 : name1 > name2 ? 1 : 0;
} else {
return STATUS_WEIGHTS[status1] < STATUS_WEIGHTS[status2] ? -1 : 1;
}
}
function groupsComparator(a, b) {
const HEADER_WEIGHTS = {};
HEADER_WEIGHTS[_converse.HEADER_UNREAD] = 0;
HEADER_WEIGHTS[_converse.HEADER_REQUESTING_CONTACTS] = 1;
HEADER_WEIGHTS[_converse.HEADER_CURRENT_CONTACTS] = 2;
HEADER_WEIGHTS[_converse.HEADER_UNGROUPED] = 3;
HEADER_WEIGHTS[_converse.HEADER_PENDING_CONTACTS] = 4;
const WEIGHTS = HEADER_WEIGHTS;
const special_groups = Object.keys(HEADER_WEIGHTS);
const a_is_special = special_groups.includes(a);
const b_is_special = special_groups.includes(b);
if (!a_is_special && !b_is_special) {
return a.toLowerCase() < b.toLowerCase() ? -1 : a.toLowerCase() > b.toLowerCase() ? 1 : 0;
} else if (a_is_special && b_is_special) {
return WEIGHTS[a] < WEIGHTS[b] ? -1 : WEIGHTS[a] > WEIGHTS[b] ? 1 : 0;
} else if (!a_is_special && b_is_special) {
const a_header = _converse.HEADER_CURRENT_CONTACTS;
return WEIGHTS[a_header] < WEIGHTS[b] ? -1 : WEIGHTS[a_header] > WEIGHTS[b] ? 1 : 0;
} else if (a_is_special && !b_is_special) {
const b_header = _converse.HEADER_CURRENT_CONTACTS;
return WEIGHTS[a] < WEIGHTS[b_header] ? -1 : WEIGHTS[a] > WEIGHTS[b_header] ? 1 : 0;
}
}
function getGroupsAutoCompleteList() {
const {
roster
} = _converse;
const groups = roster.reduce((groups, contact) => groups.concat(contact.get('groups')), []);
return [...new Set(groups.filter(i => i))];
}
;// CONCATENATED MODULE: ./src/headless/plugins/roster/contact.js
const {
Strophe: contact_Strophe,
$iq: contact_$iq,
$pres: contact_$pres
} = converse.env;
/**
* @class
* @namespace RosterContact
*/
const RosterContact = Model.extend({
idAttribute: 'jid',
defaults: {
'chat_state': undefined,
'groups': [],
'image': shared_converse.DEFAULT_IMAGE,
'image_type': shared_converse.DEFAULT_IMAGE_TYPE,
'num_unread': 0,
'status': undefined
},
async initialize(attributes) {
this.initialized = getOpenPromise();
this.setPresence();
const {
jid
} = attributes;
this.set({
...attributes,
...{
'jid': contact_Strophe.getBareJidFromJid(jid).toLowerCase(),
'user_id': contact_Strophe.getNodeFromJid(jid)
}
});
/**
* When a contact's presence status has changed.
* The presence status is either `online`, `offline`, `dnd`, `away` or `xa`.
* @event _converse#contactPresenceChanged
* @type { _converse.RosterContact }
* @example _converse.api.listen.on('contactPresenceChanged', contact => { ... });
*/
this.listenTo(this.presence, 'change:show', () => shared_api.trigger('contactPresenceChanged', this));
this.listenTo(this.presence, 'change:show', () => this.trigger('presenceChanged'));
/**
* Synchronous event which provides a hook for further initializing a RosterContact
* @event _converse#rosterContactInitialized
* @param { _converse.RosterContact } contact
*/
await shared_api.trigger('rosterContactInitialized', this, {
'Synchronous': true
});
this.initialized.resolve();
},
setPresence() {
const jid = this.get('jid');
this.presence = shared_converse.presences.findWhere(jid) || shared_converse.presences.create({
jid
});
},
openChat() {
const attrs = this.attributes;
shared_api.chats.open(attrs.jid, attrs, true);
},
/**
* Return a string of tab-separated values that are to be used when
* matching against filter text.
*
* The goal is to be able to filter against the VCard fullname,
* roster nickname and JID.
* @returns { String } Lower-cased, tab-separated values
*/
getFilterCriteria() {
const nick = this.get('nickname');
const jid = this.get('jid');
let criteria = this.getDisplayName();
criteria = !criteria.includes(jid) ? criteria.concat(` ${jid}`) : criteria;
criteria = !criteria.includes(nick) ? criteria.concat(` ${nick}`) : criteria;
return criteria.toLowerCase();
},
getDisplayName() {
// Gets overridden in converse-vcard where the fullname is may be returned
if (this.get('nickname')) {
return this.get('nickname');
} else {
return this.get('jid');
}
},
getFullname() {
// Gets overridden in converse-vcard where the fullname may be returned
return this.get('jid');
},
/**
* Send a presence subscription request to this roster contact
* @method _converse.RosterContacts#subscribe
* @param { String } message - An optional message to explain the
* reason for the subscription request.
*/
subscribe(message) {
shared_api.user.presence.send('subscribe', this.get('jid'), message);
this.save('ask', "subscribe"); // ask === 'subscribe' Means we have asked to subscribe to them.
return this;
},
/**
* Upon receiving the presence stanza of type "subscribed",
* the user SHOULD acknowledge receipt of that subscription
* state notification by sending a presence stanza of type
* "subscribe" to the contact
* @private
* @method _converse.RosterContacts#ackSubscribe
*/
ackSubscribe() {
shared_api.send(contact_$pres({
'type': 'subscribe',
'to': this.get('jid')
}));
},
/**
* Upon receiving the presence stanza of type "unsubscribed",
* the user SHOULD acknowledge receipt of that subscription state
* notification by sending a presence stanza of type "unsubscribe"
* this step lets the user's server know that it MUST no longer
* send notification of the subscription state change to the user.
* @private
* @method _converse.RosterContacts#ackUnsubscribe
*/
ackUnsubscribe() {
shared_api.send(contact_$pres({
'type': 'unsubscribe',
'to': this.get('jid')
}));
this.removeFromRoster();
this.destroy();
},
/**
* Unauthorize this contact's presence subscription
* @private
* @method _converse.RosterContacts#unauthorize
* @param { String } message - Optional message to send to the person being unauthorized
*/
unauthorize(message) {
rejectPresenceSubscription(this.get('jid'), message);
return this;
},
/**
* Authorize presence subscription
* @private
* @method _converse.RosterContacts#authorize
* @param { String } message - Optional message to send to the person being authorized
*/
authorize(message) {
const pres = contact_$pres({
'to': this.get('jid'),
'type': "subscribed"
});
if (message && message !== "") {
pres.c("status").t(message);
}
shared_api.send(pres);
return this;
},
/**
* Instruct the XMPP server to remove this contact from our roster
* @private
* @method _converse.RosterContacts#
* @returns { Promise }
*/
removeFromRoster() {
const iq = contact_$iq({
type: 'set'
}).c('query', {
xmlns: contact_Strophe.NS.ROSTER
}).c('item', {
jid: this.get('jid'),
subscription: "remove"
});
return shared_api.sendIQ(iq);
}
});
/* harmony default export */ const contact = (RosterContact);
;// CONCATENATED MODULE: ./src/headless/plugins/roster/contacts.js
const {
Strophe: contacts_Strophe,
$iq: contacts_$iq,
sizzle: contacts_sizzle,
u: contacts_u
} = converse.env;
const RosterContacts = Collection.extend({
model: contact,
initialize() {
const id = `roster.state-${shared_converse.bare_jid}-${this.get('jid')}`;
this.state = new Model({
id,
'collapsed_groups': []
});
initStorage(this.state, id);
this.state.fetch();
},
onConnected() {
// Called as soon as the connection has been established
// (either after initial login, or after reconnection).
// Use the opportunity to register stanza handlers.
this.registerRosterHandler();
this.registerRosterXHandler();
},
registerRosterHandler() {
// Register a handler for roster IQ "set" stanzas, which update
// roster contacts.
shared_converse.connection.addHandler(iq => {
shared_converse.roster.onRosterPush(iq);
return true;
}, contacts_Strophe.NS.ROSTER, 'iq', "set");
},
registerRosterXHandler() {
// Register a handler for RosterX message stanzas, which are
// used to suggest roster contacts to a user.
let t = 0;
shared_converse.connection.addHandler(function (msg) {
window.setTimeout(function () {
shared_converse.connection.flush();
shared_converse.roster.subscribeToSuggestedItems.bind(shared_converse.roster)(msg);
}, t);
t += msg.querySelectorAll('item').length * 250;
return true;
}, contacts_Strophe.NS.ROSTERX, 'message', null);
},
/**
* Fetches the roster contacts, first by trying the browser cache,
* and if that's empty, then by querying the XMPP server.
* @returns {promise} Promise which resolves once the contacts have been fetched.
*/
async fetchRosterContacts() {
const result = await new Promise((resolve, reject) => {
this.fetch({
'add': true,
'silent': true,
'success': resolve,
'error': (_, e) => reject(e)
});
});
if (contacts_u.isErrorObject(result)) {
log.error(result);
// Force a full roster refresh
shared_converse.session.save('roster_cached', false);
this.data.save('version', undefined);
}
if (shared_converse.session.get('roster_cached')) {
/**
* The contacts roster has been retrieved from the local cache (`sessionStorage`).
* @event _converse#cachedRoster
* @type { _converse.RosterContacts }
* @example _converse.api.listen.on('cachedRoster', (items) => { ... });
* @example _converse.api.waitUntil('cachedRoster').then(items => { ... });
*/
shared_api.trigger('cachedRoster', result);
} else {
shared_converse.send_initial_presence = true;
return shared_converse.roster.fetchFromServer();
}
},
subscribeToSuggestedItems(msg) {
Array.from(msg.querySelectorAll('item')).forEach(item => {
if (item.getAttribute('action') === 'add') {
shared_converse.roster.addAndSubscribe(item.getAttribute('jid'), shared_converse.xmppstatus.getNickname() || shared_converse.xmppstatus.getFullname());
}
});
return true;
},
isSelf(jid) {
return contacts_u.isSameBareJID(jid, shared_converse.connection.jid);
},
/**
* Add a roster contact and then once we have confirmation from
* the XMPP server we subscribe to that contact's presence updates.
* @method _converse.RosterContacts#addAndSubscribe
* @param { String } jid - The Jabber ID of the user being added and subscribed to.
* @param { String } name - The name of that user
* @param { Array<String> } groups - Any roster groups the user might belong to
* @param { String } message - An optional message to explain the reason for the subscription request.
* @param { Object } attributes - Any additional attributes to be stored on the user's model.
*/
async addAndSubscribe(jid, name, groups, message, attributes) {
const contact = await this.addContactToRoster(jid, name, groups, attributes);
if (contact instanceof shared_converse.RosterContact) {
contact.subscribe(message);
}
},
/**
* Send an IQ stanza to the XMPP server to add a new roster contact.
* @method _converse.RosterContacts#sendContactAddIQ
* @param { String } jid - The Jabber ID of the user being added
* @param { String } name - The name of that user
* @param { Array<String> } groups - Any roster groups the user might belong to
*/
sendContactAddIQ(jid, name, groups) {
name = name ? name : null;
const iq = contacts_$iq({
'type': 'set'
}).c('query', {
'xmlns': contacts_Strophe.NS.ROSTER
}).c('item', {
jid,
name
});
groups.forEach(g => iq.c('group').t(g).up());
return shared_api.sendIQ(iq);
},
/**
* Adds a RosterContact instance to _converse.roster and
* registers the contact on the XMPP server.
* Returns a promise which is resolved once the XMPP server has responded.
* @method _converse.RosterContacts#addContactToRoster
* @param { String } jid - The Jabber ID of the user being added and subscribed to.
* @param { String } name - The name of that user
* @param { Array<String> } groups - Any roster groups the user might belong to
* @param { Object } attributes - Any additional attributes to be stored on the user's model.
*/
async addContactToRoster(jid, name, groups, attributes) {
await shared_api.waitUntil('rosterContactsFetched');
groups = groups || [];
try {
await this.sendContactAddIQ(jid, name, groups);
} catch (e) {
const {
__
} = shared_converse;
log.error(e);
alert(__('Sorry, there was an error while trying to add %1$s as a contact.', name || jid));
return e;
}
return this.create(Object.assign({
'ask': undefined,
'nickname': name,
groups,
jid,
'requesting': false,
'subscription': 'none'
}, attributes), {
'sort': false
});
},
async subscribeBack(bare_jid, presence) {
const contact = this.get(bare_jid);
if (contact instanceof shared_converse.RosterContact) {
contact.authorize().subscribe();
} else {
// Can happen when a subscription is retried or roster was deleted
const nickname = contacts_sizzle(`nick[xmlns="${contacts_Strophe.NS.NICK}"]`, presence).pop()?.textContent || null;
const contact = await this.addContactToRoster(bare_jid, nickname, [], {
'subscription': 'from'
});
if (contact instanceof shared_converse.RosterContact) {
contact.authorize().subscribe();
}
}
},
/**
* Handle roster updates from the XMPP server.
* See: https://xmpp.org/rfcs/rfc6121.html#roster-syntax-actions-push
* @method _converse.RosterContacts#onRosterPush
* @param { Element } iq - The IQ stanza received from the XMPP server.
*/
onRosterPush(iq) {
const id = iq.getAttribute('id');
const from = iq.getAttribute('from');
if (from && from !== shared_converse.bare_jid) {
// https://tools.ietf.org/html/rfc6121#page-15
//
// A receiving client MUST ignore the stanza unless it has no 'from'
// attribute (i.e., implicitly from the bare JID of the user's
// account) or it has a 'from' attribute whose value matches the
// user's bare JID <user@domainpart>.
log.warn(`Ignoring roster illegitimate roster push message from ${iq.getAttribute('from')}`);
return;
}
shared_api.send(contacts_$iq({
type: 'result',
id,
from: shared_converse.connection.jid
}));
const query = contacts_sizzle(`query[xmlns="${contacts_Strophe.NS.ROSTER}"]`, iq).pop();
this.data.save('version', query.getAttribute('ver'));
const items = contacts_sizzle(`item`, query);
if (items.length > 1) {
log.error(iq);
throw new Error('Roster push query may not contain more than one "item" element.');
}
if (items.length === 0) {
log.warn(iq);
log.warn('Received a roster push stanza without an "item" element.');
return;
}
this.updateContact(items.pop());
/**
* When the roster receives a push event from server (i.e. new entry in your contacts roster).
* @event _converse#rosterPush
* @type { Element }
* @example _converse.api.listen.on('rosterPush', iq => { ... });
*/
shared_api.trigger('rosterPush', iq);
return;
},
rosterVersioningSupported() {
return shared_api.disco.stream.getFeature('ver', 'urn:xmpp:features:rosterver') && this.data.get('version');
},
/**
* Fetch the roster from the XMPP server
* @emits _converse#roster
* @returns {promise}
*/
async fetchFromServer() {
const stanza = contacts_$iq({
'type': 'get',
'id': contacts_u.getUniqueId('roster')
}).c('query', {
xmlns: contacts_Strophe.NS.ROSTER
});
if (this.rosterVersioningSupported()) {
stanza.attrs({
'ver': this.data.get('version')
});
}
const iq = await shared_api.sendIQ(stanza, null, false);
if (iq.getAttribute('type') === 'result') {
const query = contacts_sizzle(`query[xmlns="${contacts_Strophe.NS.ROSTER}"]`, iq).pop();
if (query) {
const items = contacts_sizzle(`item`, query);
if (!this.data.get('version') && this.models.length) {
// We're getting the full roster, so remove all cached
// contacts that aren't included in it.
const jids = items.map(item => item.getAttribute('jid'));
this.forEach(m => !m.get('requesting') && !jids.includes(m.get('jid')) && m.destroy());
}
items.forEach(item => this.updateContact(item));
this.data.save('version', query.getAttribute('ver'));
}
} else if (!contacts_u.isServiceUnavailableError(iq)) {
// Some unknown error happened, so we will try to fetch again if the page reloads.
log.error(iq);
log.error("Error while trying to fetch roster from the server");
return;
}
shared_converse.session.save('roster_cached', true);
/**
* When the roster has been received from the XMPP server.
* See also the `cachedRoster` event further up, which gets called instead of
* `roster` if its already in `sessionStorage`.
* @event _converse#roster
* @type { Element }
* @example _converse.api.listen.on('roster', iq => { ... });
* @example _converse.api.waitUntil('roster').then(iq => { ... });
*/
shared_api.trigger('roster', iq);
},
/**
* Update or create RosterContact models based on the given `item` XML
* node received in the resulting IQ stanza from the server.
* @param { Element } item
*/
updateContact(item) {
const jid = item.getAttribute('jid');
const contact = this.get(jid);
const subscription = item.getAttribute("subscription");
if (subscription === "remove") {
return contact?.destroy();
}
const ask = item.getAttribute("ask");
const nickname = item.getAttribute('name');
const groups = [...new Set(contacts_sizzle('group', item).map(e => e.textContent))];
if (contact) {
// We only find out about requesting contacts via the
// presence handler, so if we receive a contact
// here, we know they aren't requesting anymore.
contact.save({
subscription,
ask,
nickname,
groups,
'requesting': null
});
} else {
this.create({
nickname,
ask,
groups,
jid,
subscription
}, {
sort: false
});
}
},
createRequestingContact(presence) {
const bare_jid = contacts_Strophe.getBareJidFromJid(presence.getAttribute('from'));
const nickname = contacts_sizzle(`nick[xmlns="${contacts_Strophe.NS.NICK}"]`, presence).pop()?.textContent || null;
const user_data = {
'jid': bare_jid,
'subscription': 'none',
'ask': null,
'requesting': true,
'nickname': nickname
};
/**
* Triggered when someone has requested to subscribe to your presence (i.e. to be your contact).
* @event _converse#contactRequest
* @type { _converse.RosterContact }
* @example _converse.api.listen.on('contactRequest', contact => { ... });
*/
shared_api.trigger('contactRequest', this.create(user_data));
},
handleIncomingSubscription(presence) {
const jid = presence.getAttribute('from'),
bare_jid = contacts_Strophe.getBareJidFromJid(jid),
contact = this.get(bare_jid);
if (!shared_api.settings.get('allow_contact_requests')) {
const {
__
} = shared_converse;
rejectPresenceSubscription(jid, __("This client does not allow presence subscriptions"));
}
if (shared_api.settings.get('auto_subscribe')) {
if (!contact || contact.get('subscription') !== 'to') {
this.subscribeBack(bare_jid, presence);
} else {
contact.authorize();
}
} else {
if (contact) {
if (contact.get('subscription') !== 'none') {
contact.authorize();
} else if (contact.get('ask') === "subscribe") {
contact.authorize();
}
} else {
this.createRequestingContact(presence);
}
}
},
handleOwnPresence(presence) {
const jid = presence.getAttribute('from'),
resource = contacts_Strophe.getResourceFromJid(jid),
presence_type = presence.getAttribute('type');
if (shared_converse.connection.jid !== jid && presence_type !== 'unavailable' && (shared_api.settings.get('synchronize_availability') === true || shared_api.settings.get('synchronize_availability') === resource)) {
// Another resource has changed its status and
// synchronize_availability option set to update,
// we'll update ours as well.
const show = presence.querySelector('show')?.textContent || 'online';
shared_converse.xmppstatus.save({
'status': show
}, {
'silent': true
});
const status_message = presence.querySelector('status')?.textContent;
if (status_message) shared_converse.xmppstatus.save({
status_message
});
}
if (shared_converse.jid === jid && presence_type === 'unavailable') {
// XXX: We've received an "unavailable" presence from our
// own resource. Apparently this happens due to a
// Prosody bug, whereby we send an IQ stanza to remove
// a roster contact, and Prosody then sends
// "unavailable" globally, instead of directed to the
// particular user that's removed.
//
// Here is the bug report: https://prosody.im/issues/1121
//
// I'm not sure whether this might legitimately happen
// in other cases.
//
// As a workaround for now we simply send our presence again,
// otherwise we're treated as offline.
shared_api.user.presence.send();
}
},
presenceHandler(presence) {
const presence_type = presence.getAttribute('type');
if (presence_type === 'error') return true;
const jid = presence.getAttribute('from');
const bare_jid = contacts_Strophe.getBareJidFromJid(jid);
if (this.isSelf(bare_jid)) {
return this.handleOwnPresence(presence);
} else if (contacts_sizzle(`query[xmlns="${contacts_Strophe.NS.MUC}"]`, presence).length) {
return; // Ignore MUC
}
const contact = this.get(bare_jid);
if (contact) {
const status = presence.querySelector('status')?.textContent;
if (contact.get('status') !== status) contact.save({
status
});
}
if (presence_type === 'subscribed' && contact) {
contact.ackSubscribe();
} else if (presence_type === 'unsubscribed' && contact) {
contact.ackUnsubscribe();
} else if (presence_type === 'unsubscribe') {
return;
} else if (presence_type === 'subscribe') {
this.handleIncomingSubscription(presence);
} else if (presence_type === 'unavailable' && contact) {
const resource = contacts_Strophe.getResourceFromJid(jid);
contact.presence.removeResource(resource);
} else if (contact) {
// presence_type is undefined
contact.presence.addResource(presence);
}
}
});
/* harmony default export */ const contacts = (RosterContacts);
;// CONCATENATED MODULE: ./src/headless/plugins/roster/api.js
const {
Strophe: roster_api_Strophe
} = converse.env;
/* harmony default export */ const roster_api = ({
/**
* @namespace _converse.api.contacts
* @memberOf _converse.api
*/
contacts: {
/**
* This method is used to retrieve roster contacts.
*
* @method _converse.api.contacts.get
* @params {(string[]|string)} jid|jids The JID or JIDs of
* the contacts to be returned.
* @returns {promise} Promise which resolves with the
* _converse.RosterContact (or an array of them) representing the contact.
*
* @example
* // Fetch a single contact
* _converse.api.listen.on('rosterContactsFetched', function () {
* const contact = await _converse.api.contacts.get('buddy@example.com')
* // ...
* });
*
* @example
* // To get multiple contacts, pass in an array of JIDs:
* _converse.api.listen.on('rosterContactsFetched', function () {
* const contacts = await _converse.api.contacts.get(
* ['buddy1@example.com', 'buddy2@example.com']
* )
* // ...
* });
*
* @example
* // To return all contacts, simply call ``get`` without any parameters:
* _converse.api.listen.on('rosterContactsFetched', function () {
* const contacts = await _converse.api.contacts.get();
* // ...
* });
*/
async get(jids) {
await shared_api.waitUntil('rosterContactsFetched');
const _getter = jid => shared_converse.roster.get(roster_api_Strophe.getBareJidFromJid(jid));
if (jids === undefined) {
jids = shared_converse.roster.pluck('jid');
} else if (typeof jids === 'string') {
return _getter(jids);
}
return jids.map(_getter);
},
/**
* Add a contact.
*
* @method _converse.api.contacts.add
* @param { string } jid The JID of the contact to be added
* @param { string } [name] A custom name to show the user by in the roster
* @example
* _converse.api.contacts.add('buddy@example.com')
* @example
* _converse.api.contacts.add('buddy@example.com', 'Buddy')
*/
async add(jid, name) {
await shared_api.waitUntil('rosterContactsFetched');
if (typeof jid !== 'string' || !jid.includes('@')) {
throw new TypeError('contacts.add: invalid jid');
}
return shared_converse.roster.addAndSubscribe(jid, name);
}
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/roster/presence.js
const {
Strophe: presence_Strophe,
dayjs: presence_dayjs,
sizzle: presence_sizzle
} = converse.env;
const Resource = Model.extend({
'idAttribute': 'name'
});
const Resources = Collection.extend({
'model': Resource
});
const Presence = Model.extend({
idAttribute: 'jid',
defaults: {
'show': 'offline'
},
initialize() {
this.resources = new Resources();
const id = `converse.identities-${this.get('jid')}`;
initStorage(this.resources, id, 'session');
this.listenTo(this.resources, 'update', this.onResourcesChanged);
this.listenTo(this.resources, 'change', this.onResourcesChanged);
},
onResourcesChanged() {
const hpr = this.getHighestPriorityResource();
const show = hpr?.attributes?.show || 'offline';
if (this.get('show') !== show) {
this.save({
show
});
}
},
/**
* Return the resource with the highest priority.
* If multiple resources have the same priority, take the latest one.
* @private
*/
getHighestPriorityResource() {
return this.resources.sortBy(r => `${r.get('priority')}-${r.get('timestamp')}`).reverse()[0];
},
/**
* Adds a new resource and it's associated attributes as taken
* from the passed in presence stanza.
* Also updates the presence if the resource has higher priority (and is newer).
* @private
* @param { Element } presence: The presence stanza
*/
addResource(presence) {
const jid = presence.getAttribute('from');
const name = presence_Strophe.getResourceFromJid(jid);
const delay = presence_sizzle(`delay[xmlns="${presence_Strophe.NS.DELAY}"]`, presence).pop();
const priority = presence.querySelector('priority')?.textContent;
const resource = this.resources.get(name);
const settings = {
name,
'priority': lodash_es_isNaN(parseInt(priority, 10)) ? 0 : parseInt(priority, 10),
'show': presence.querySelector('show')?.textContent ?? 'online',
'timestamp': delay ? presence_dayjs(delay.getAttribute('stamp')).toISOString() : new Date().toISOString()
};
if (resource) {
resource.save(settings);
} else {
this.resources.create(settings);
}
},
/**
* Remove the passed in resource from the resources map.
* Also redetermines the presence given that there's one less
* resource.
* @private
* @param { string } name: The resource name
*/
removeResource(name) {
const resource = this.resources.get(name);
resource?.destroy();
}
});
const Presences = Collection.extend({
'model': Presence
});
;// CONCATENATED MODULE: ./src/headless/plugins/roster/index.js
/**
* @copyright The Converse.js contributors
* @license Mozilla Public License (MPLv2)
*/
converse.plugins.add('converse-roster', {
dependencies: ['converse-status'],
initialize() {
shared_api.settings.extend({
'allow_contact_requests': true,
'auto_subscribe': false,
'synchronize_availability': true
});
shared_api.promises.add(['cachedRoster', 'roster', 'rosterContactsFetched', 'rosterInitialized']);
// API methods only available to plugins
Object.assign(shared_converse.api, roster_api);
const {
__
} = shared_converse;
shared_converse.HEADER_CURRENT_CONTACTS = __('My contacts');
shared_converse.HEADER_PENDING_CONTACTS = __('Pending contacts');
shared_converse.HEADER_REQUESTING_CONTACTS = __('Contact requests');
shared_converse.HEADER_UNGROUPED = __('Ungrouped');
shared_converse.HEADER_UNREAD = __('New messages');
shared_converse.Presence = Presence;
shared_converse.Presences = Presences;
shared_converse.RosterContact = contact;
shared_converse.RosterContacts = contacts;
shared_api.listen.on('beforeTearDown', () => unregisterPresenceHandler());
shared_api.listen.on('chatBoxesInitialized', onChatBoxesInitialized);
shared_api.listen.on('clearSession', utils_onClearSession);
shared_api.listen.on('presencesInitialized', onPresencesInitialized);
shared_api.listen.on('statusInitialized', roster_utils_onStatusInitialized);
shared_api.listen.on('streamResumptionFailed', () => shared_converse.session.set('roster_cached', false));
shared_api.waitUntil('rosterContactsFetched').then(onRosterContactsFetched);
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/smacks/utils.js
const {
Strophe: smacks_utils_Strophe
} = converse.env;
const smacks_utils_u = converse.env.utils;
function isStreamManagementSupported() {
if (shared_api.connection.isType('bosh') && !shared_converse.isTestEnv()) {
return false;
}
return shared_api.disco.stream.getFeature('sm', smacks_utils_Strophe.NS.SM);
}
function handleAck(el) {
if (!shared_converse.session.get('smacks_enabled')) {
return true;
}
const handled = parseInt(el.getAttribute('h'), 10);
const last_known_handled = shared_converse.session.get('num_stanzas_handled_by_server');
const delta = handled - last_known_handled;
if (delta < 0) {
const err_msg = `New reported stanza count lower than previous. ` + `New: ${handled} - Previous: ${last_known_handled}`;
log.error(err_msg);
}
const unacked_stanzas = shared_converse.session.get('unacked_stanzas');
if (delta > unacked_stanzas.length) {
const err_msg = `Higher reported acknowledge count than unacknowledged stanzas. ` + `Reported Acknowledged Count: ${delta} -` + `Unacknowledged Stanza Count: ${unacked_stanzas.length} -` + `New: ${handled} - Previous: ${last_known_handled}`;
log.error(err_msg);
}
shared_converse.session.save({
'num_stanzas_handled_by_server': handled,
'num_stanzas_since_last_ack': 0,
'unacked_stanzas': unacked_stanzas.slice(delta)
});
return true;
}
function sendAck() {
if (shared_converse.session.get('smacks_enabled')) {
const h = shared_converse.session.get('num_stanzas_handled');
const stanza = smacks_utils_u.toStanza(`<a xmlns="${smacks_utils_Strophe.NS.SM}" h="${h}"/>`);
shared_api.send(stanza);
}
return true;
}
function stanzaHandler(el) {
if (shared_converse.session.get('smacks_enabled')) {
if (smacks_utils_u.isTagEqual(el, 'iq') || smacks_utils_u.isTagEqual(el, 'presence') || smacks_utils_u.isTagEqual(el, 'message')) {
const h = shared_converse.session.get('num_stanzas_handled');
shared_converse.session.save('num_stanzas_handled', h + 1);
}
}
return true;
}
function initSessionData() {
shared_converse.session.save({
'smacks_enabled': shared_converse.session.get('smacks_enabled') || false,
'num_stanzas_handled': shared_converse.session.get('num_stanzas_handled') || 0,
'num_stanzas_handled_by_server': shared_converse.session.get('num_stanzas_handled_by_server') || 0,
'num_stanzas_since_last_ack': shared_converse.session.get('num_stanzas_since_last_ack') || 0,
'unacked_stanzas': shared_converse.session.get('unacked_stanzas') || []
});
}
function resetSessionData() {
shared_converse.session?.save({
'smacks_enabled': false,
'num_stanzas_handled': 0,
'num_stanzas_handled_by_server': 0,
'num_stanzas_since_last_ack': 0,
'unacked_stanzas': []
});
}
function saveSessionData(el) {
const data = {
'smacks_enabled': true
};
if (['1', 'true'].includes(el.getAttribute('resume'))) {
data['smacks_stream_id'] = el.getAttribute('id');
}
shared_converse.session.save(data);
return true;
}
function onFailedStanza(el) {
if (el.querySelector('item-not-found')) {
// Stream resumption must happen before resource binding but
// enabling a new stream must happen after resource binding.
// Since resumption failed, we simply continue.
//
// After resource binding, sendEnableStanza will be called
// based on the afterResourceBinding event.
log.warn('Could not resume previous SMACKS session, session id not found. ' + 'A new session will be established.');
} else {
log.error('Failed to enable stream management');
log.error(el.outerHTML);
}
resetSessionData();
/**
* Triggered when the XEP-0198 stream could not be resumed.
* @event _converse#streamResumptionFailed
*/
shared_api.trigger('streamResumptionFailed');
return true;
}
function resendUnackedStanzas() {
const stanzas = shared_converse.session.get('unacked_stanzas');
// We clear the unacked_stanzas array because it'll get populated
// again in `onStanzaSent`
shared_converse.session.save('unacked_stanzas', []);
// XXX: Currently we're resending *all* unacked stanzas, including
// IQ[type="get"] stanzas that longer have handlers (because the
// page reloaded or we reconnected, causing removal of handlers).
//
// *Side-note:* Is it necessary to clear handlers upon reconnection?
//
// I've considered not resending those stanzas, but then keeping
// track of what's been sent and ack'd and their order gets
// prohibitively complex.
//
// It's unclear how much of a problem this poses.
//
// Two possible solutions are running @converse/headless as a
// service worker or handling IQ[type="result"] stanzas
// differently, more like push stanzas, so that they don't need
// explicit handlers.
stanzas.forEach(s => shared_api.send(s));
}
function onResumedStanza(el) {
saveSessionData(el);
handleAck(el);
resendUnackedStanzas();
shared_converse.connection.do_bind = false; // No need to bind our resource anymore
shared_converse.connection.authenticated = true;
shared_converse.connection.restored = true;
shared_converse.connection._changeConnectStatus(smacks_utils_Strophe.Status.CONNECTED, null);
}
async function sendResumeStanza() {
const promise = getOpenPromise();
shared_converse.connection._addSysHandler(el => promise.resolve(onResumedStanza(el)), smacks_utils_Strophe.NS.SM, 'resumed');
shared_converse.connection._addSysHandler(el => promise.resolve(onFailedStanza(el)), smacks_utils_Strophe.NS.SM, 'failed');
const previous_id = shared_converse.session.get('smacks_stream_id');
const h = shared_converse.session.get('num_stanzas_handled');
const stanza = smacks_utils_u.toStanza(`<resume xmlns="${smacks_utils_Strophe.NS.SM}" h="${h}" previd="${previous_id}"/>`);
shared_api.send(stanza);
shared_converse.connection.flush();
await promise;
}
async function sendEnableStanza() {
if (!shared_api.settings.get('enable_smacks') || shared_converse.session.get('smacks_enabled')) {
return;
}
if (await isStreamManagementSupported()) {
const promise = getOpenPromise();
shared_converse.connection._addSysHandler(el => promise.resolve(saveSessionData(el)), smacks_utils_Strophe.NS.SM, 'enabled');
shared_converse.connection._addSysHandler(el => promise.resolve(onFailedStanza(el)), smacks_utils_Strophe.NS.SM, 'failed');
const resume = shared_api.connection.isType('websocket') || shared_converse.isTestEnv();
const stanza = smacks_utils_u.toStanza(`<enable xmlns="${smacks_utils_Strophe.NS.SM}" resume="${resume}"/>`);
shared_api.send(stanza);
shared_converse.connection.flush();
await promise;
}
}
const smacks_handlers = [];
async function enableStreamManagement() {
if (!shared_api.settings.get('enable_smacks')) {
return;
}
if (!(await isStreamManagementSupported())) {
return;
}
const conn = shared_converse.connection;
while (smacks_handlers.length) {
conn.deleteHandler(smacks_handlers.pop());
}
smacks_handlers.push(conn.addHandler(stanzaHandler));
smacks_handlers.push(conn.addHandler(sendAck, smacks_utils_Strophe.NS.SM, 'r'));
smacks_handlers.push(conn.addHandler(handleAck, smacks_utils_Strophe.NS.SM, 'a'));
if (shared_converse.session?.get('smacks_stream_id')) {
await sendResumeStanza();
} else {
resetSessionData();
}
}
function onStanzaSent(stanza) {
if (!shared_converse.session) {
log.warn('No _converse.session!');
return;
}
if (!shared_converse.session.get('smacks_enabled')) {
return;
}
if (smacks_utils_u.isTagEqual(stanza, 'iq') || smacks_utils_u.isTagEqual(stanza, 'presence') || smacks_utils_u.isTagEqual(stanza, 'message')) {
const stanza_string = smacks_utils_Strophe.serialize(stanza);
shared_converse.session.save('unacked_stanzas', (shared_converse.session.get('unacked_stanzas') || []).concat([stanza_string]));
const max_unacked = shared_api.settings.get('smacks_max_unacked_stanzas');
if (max_unacked > 0) {
const num = shared_converse.session.get('num_stanzas_since_last_ack') + 1;
if (num % max_unacked === 0) {
// Request confirmation of sent stanzas
shared_api.send(smacks_utils_u.toStanza(`<r xmlns="${smacks_utils_Strophe.NS.SM}"/>`));
}
shared_converse.session.save({
'num_stanzas_since_last_ack': num
});
}
}
}
;// CONCATENATED MODULE: ./src/headless/plugins/smacks/index.js
/**
* @copyright The Converse.js contributors
* @license Mozilla Public License (MPLv2)
* @description Converse.js plugin which adds support for XEP-0198: Stream Management
*/
const {
Strophe: smacks_Strophe
} = converse.env;
smacks_Strophe.addNamespace('SM', 'urn:xmpp:sm:3');
converse.plugins.add('converse-smacks', {
initialize() {
// Configuration values for this plugin
// ====================================
// Refer to docs/source/configuration.rst for explanations of these
// configuration settings.
shared_api.settings.extend({
'enable_smacks': true,
'smacks_max_unacked_stanzas': 5
});
shared_api.listen.on('afterResourceBinding', sendEnableStanza);
shared_api.listen.on('beforeResourceBinding', enableStreamManagement);
shared_api.listen.on('send', onStanzaSent);
shared_api.listen.on('userSessionInitialized', initSessionData);
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/vcard/vcard.js
/**
* Represents a VCard
* @class
* @namespace _converse.VCard
* @memberOf _converse
*/
const VCard = Model.extend({
idAttribute: 'jid',
defaults: {
'image': shared_converse.DEFAULT_IMAGE,
'image_type': shared_converse.DEFAULT_IMAGE_TYPE
},
set(key, val, options) {
// Override Model.prototype.set to make sure that the
// default `image` and `image_type` values are maintained.
let attrs;
if (typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
if ('image' in attrs && !attrs['image']) {
attrs['image'] = shared_converse.DEFAULT_IMAGE;
attrs['image_type'] = shared_converse.DEFAULT_IMAGE_TYPE;
return Model.prototype.set.call(this, attrs, options);
} else {
return Model.prototype.set.apply(this, arguments);
}
},
getDisplayName() {
return this.get('nickname') || this.get('fullname') || this.get('jid');
}
});
/* harmony default export */ const vcard = (VCard);
;// CONCATENATED MODULE: ./src/headless/plugins/vcard/utils.js
const {
Strophe: vcard_utils_Strophe,
$iq: vcard_utils_$iq,
u: vcard_utils_u
} = converse.env;
async function onVCardData(jid, iq) {
const vcard = iq.querySelector('vCard');
let result = {};
if (vcard !== null) {
result = {
'stanza': iq,
'fullname': vcard.querySelector('FN')?.textContent,
'nickname': vcard.querySelector('NICKNAME')?.textContent,
'image': vcard.querySelector('PHOTO BINVAL')?.textContent,
'image_type': vcard.querySelector('PHOTO TYPE')?.textContent,
'url': vcard.querySelector('URL')?.textContent,
'role': vcard.querySelector('ROLE')?.textContent,
'email': vcard.querySelector('EMAIL USERID')?.textContent,
'vcard_updated': new Date().toISOString(),
'vcard_error': undefined
};
}
if (result.image) {
const buffer = vcard_utils_u.base64ToArrayBuffer(result['image']);
const ab = await crypto.subtle.digest('SHA-1', buffer);
result['image_hash'] = vcard_utils_u.arrayBufferToHex(ab);
}
return result;
}
function createStanza(type, jid, vcard_el) {
const iq = vcard_utils_$iq(jid ? {
'type': type,
'to': jid
} : {
'type': type
});
if (!vcard_el) {
iq.c("vCard", {
'xmlns': vcard_utils_Strophe.NS.VCARD
});
} else {
iq.cnode(vcard_el);
}
return iq;
}
function onOccupantAvatarChanged(occupant) {
const hash = occupant.get('image_hash');
const vcards = [];
if (occupant.get('jid')) {
vcards.push(shared_converse.vcards.get(occupant.get('jid')));
}
vcards.push(shared_converse.vcards.get(occupant.get('from')));
vcards.forEach(v => hash && v?.get('image_hash') !== hash && shared_api.vcard.update(v, true));
}
async function setVCardOnModel(model) {
let jid;
if (model instanceof shared_converse.Message) {
if (['error', 'info'].includes(model.get('type'))) {
return;
}
jid = model.get('from');
} else {
jid = model.get('jid');
}
if (!jid) {
log.warn(`Could not set VCard on model because no JID found!`);
return;
}
await shared_api.waitUntil('VCardsInitialized');
model.vcard = shared_converse.vcards.get(jid) || shared_converse.vcards.create({
jid
});
model.vcard.on('change', () => model.trigger('vcard:change'));
model.trigger('vcard:add');
}
function getVCardForOccupant(occupant) {
const muc = occupant?.collection?.chatroom;
const nick = occupant.get('nick');
if (nick && muc?.get('nick') === nick) {
return shared_converse.xmppstatus.vcard;
} else {
const jid = occupant.get('jid') || occupant.get('from');
if (jid) {
return shared_converse.vcards.get(jid) || shared_converse.vcards.create({
jid
});
} else {
log.warn(`Could not get VCard for occupant because no JID found!`);
return;
}
}
}
async function setVCardOnOccupant(occupant) {
await shared_api.waitUntil('VCardsInitialized');
occupant.vcard = getVCardForOccupant(occupant);
if (occupant.vcard) {
occupant.vcard.on('change', () => occupant.trigger('vcard:change'));
occupant.trigger('vcard:add');
}
}
function getVCardForMUCMessage(message) {
const muc = message?.collection?.chatbox;
const nick = vcard_utils_Strophe.getResourceFromJid(message.get('from'));
if (nick && muc?.get('nick') === nick) {
return shared_converse.xmppstatus.vcard;
} else {
const jid = message.occupant?.get('jid') || message.get('from');
if (jid) {
return shared_converse.vcards.get(jid) || shared_converse.vcards.create({
jid
});
} else {
log.warn(`Could not get VCard for message because no JID found! msgid: ${message.get('msgid')}`);
return;
}
}
}
async function setVCardOnMUCMessage(message) {
if (['error', 'info'].includes(message.get('type'))) {
return;
} else {
await shared_api.waitUntil('VCardsInitialized');
message.vcard = getVCardForMUCMessage(message);
if (message.vcard) {
message.vcard.on('change', () => message.trigger('vcard:change'));
message.trigger('vcard:add');
}
}
}
async function initVCardCollection() {
shared_converse.vcards = new shared_converse.VCards();
const id = `${shared_converse.bare_jid}-converse.vcards`;
initStorage(shared_converse.vcards, id);
await new Promise(resolve => {
shared_converse.vcards.fetch({
'success': resolve,
'error': resolve
}, {
'silent': true
});
});
const vcards = shared_converse.vcards;
if (shared_converse.session) {
const jid = shared_converse.session.get('bare_jid');
const status = shared_converse.xmppstatus;
status.vcard = vcards.get(jid) || vcards.create({
'jid': jid
});
if (status.vcard) {
status.vcard.on('change', () => status.trigger('vcard:change'));
status.trigger('vcard:add');
}
}
/**
* Triggered as soon as the `_converse.vcards` collection has been initialized and populated from cache.
* @event _converse#VCardsInitialized
*/
shared_api.trigger('VCardsInitialized');
}
function clearVCardsSession() {
if (shouldClearCache()) {
shared_api.promises.add('VCardsInitialized');
if (shared_converse.vcards) {
shared_converse.vcards.clearStore();
delete shared_converse.vcards;
}
}
}
async function getVCard(jid) {
const to = vcard_utils_Strophe.getBareJidFromJid(jid) === shared_converse.bare_jid ? null : jid;
let iq;
try {
iq = await shared_api.sendIQ(createStanza("get", to));
} catch (iq) {
return {
jid,
'stanza': iq,
'vcard_error': new Date().toISOString()
};
}
return onVCardData(jid, iq);
}
;// CONCATENATED MODULE: ./src/headless/plugins/vcard/api.js
const {
dayjs: api_dayjs,
u: vcard_api_u
} = converse.env;
/* harmony default export */ const vcard_api = ({
/**
* The XEP-0054 VCard API
*
* This API lets you access and update user VCards
*
* @namespace _converse.api.vcard
* @memberOf _converse.api
*/
vcard: {
/**
* Enables setting new values for a VCard.
*
* Sends out an IQ stanza to set the user's VCard and if
* successful, it updates the {@link _converse.VCard}
* for the passed in JID.
*
* @method _converse.api.vcard.set
* @param { string } jid The JID for which the VCard should be set
* @param { object } data A map of VCard keys and values
* @example
* let jid = _converse.bare_jid;
* _converse.api.vcard.set( jid, {
* 'fn': 'John Doe',
* 'nickname': 'jdoe'
* }).then(() => {
* // Succes
* }).catch((e) => {
* // Failure, e is your error object
* }).
*/
async set(jid, data) {
if (!jid) {
throw Error("No jid provided for the VCard data");
}
const div = document.createElement('div');
const vcard_el = vcard_api_u.toStanza(`
<vCard xmlns="vcard-temp">
<FN>${data.fn}</FN>
<NICKNAME>${data.nickname}</NICKNAME>
<URL>${data.url}</URL>
<ROLE>${data.role}</ROLE>
<EMAIL><INTERNET/><PREF/><USERID>${data.email}</USERID></EMAIL>
<PHOTO>
<TYPE>${data.image_type}</TYPE>
<BINVAL>${data.image}</BINVAL>
</PHOTO>
</vCard>`, div);
let result;
try {
result = await shared_api.sendIQ(createStanza("set", jid, vcard_el));
} catch (e) {
throw e;
}
await shared_api.vcard.update(jid, true);
return result;
},
/**
* @method _converse.api.vcard.get
* @param {Model|string} model Either a `Model` instance, or a string JID.
* If a `Model` instance is passed in, then it must have either a `jid`
* attribute or a `muc_jid` attribute.
* @param { boolean } [force] A boolean indicating whether the vcard should be
* fetched from the server even if it's been fetched before.
* @returns {promise} A Promise which resolves with the VCard data for a particular JID or for
* a `Model` instance which represents an entity with a JID (such as a roster contact,
* chat or chatroom occupant).
*
* @example
* const { api } = _converse;
* api.waitUntil('rosterContactsFetched').then(() => {
* api.vcard.get('someone@example.org').then(
* (vcard) => {
* // Do something with the vcard...
* }
* );
* });
*/
get(model, force) {
if (typeof model === 'string') {
return getVCard(model);
}
const error_date = model.get('vcard_error');
const already_tried_today = error_date && api_dayjs(error_date).isSame(new Date(), "day");
if (force || !model.get('vcard_updated') && !already_tried_today) {
const jid = model.get('jid');
if (!jid) {
log.error("No JID to get vcard for");
}
return getVCard(jid);
} else {
return Promise.resolve({});
}
},
/**
* Fetches the VCard associated with a particular `Model` instance
* (by using its `jid` or `muc_jid` attribute) and then updates the model with the
* returned VCard data.
*
* @method _converse.api.vcard.update
* @param { Model } model A `Model` instance
* @param { boolean } [force] A boolean indicating whether the vcard should be
* fetched again even if it's been fetched before.
* @returns {promise} A promise which resolves once the update has completed.
* @example
* const { api } = _converse;
* api.waitUntil('rosterContactsFetched').then(async () => {
* const chatbox = await api.chats.get('someone@example.org');
* api.vcard.update(chatbox);
* });
*/
async update(model, force) {
const data = await this.get(model, force);
model = typeof model === 'string' ? shared_converse.vcards.get(model) : model;
if (!model) {
log.error(`Could not find a VCard model for ${model}`);
return;
}
if (Object.keys(data).length) {
delete data['stanza'];
model.save(data);
}
}
}
});
;// CONCATENATED MODULE: ./src/headless/plugins/vcard/index.js
/**
* @copyright The Converse.js contributors
* @license Mozilla Public License (MPLv2)
*/
const {
Strophe: vcard_Strophe
} = converse.env;
converse.plugins.add('converse-vcard', {
dependencies: ["converse-status", "converse-roster"],
// Overrides mentioned here will be picked up by converse.js's
// plugin architecture they will replace existing methods on the
// relevant objects or classes.
// New functions which don't exist yet can also be added.
overrides: {
XMPPStatus: {
getNickname() {
const {
_converse
} = this.__super__;
const nick = this.__super__.getNickname.apply(this);
if (!nick && _converse.xmppstatus.vcard) {
return _converse.xmppstatus.vcard.get('nickname');
} else {
return nick;
}
},
getFullname() {
const {
_converse
} = this.__super__;
const fullname = this.__super__.getFullname.apply(this);
if (!fullname && _converse.xmppstatus.vcard) {
return _converse.xmppstatus.vcard.get('fullname');
} else {
return fullname;
}
}
},
RosterContact: {
getDisplayName() {
if (!this.get('nickname') && this.vcard) {
return this.vcard.getDisplayName();
} else {
return this.__super__.getDisplayName.apply(this);
}
},
getFullname() {
if (this.vcard) {
return this.vcard.get('fullname');
} else {
return this.__super__.getFullname.apply(this);
}
}
}
},
initialize() {
shared_api.promises.add('VCardsInitialized');
shared_converse.VCard = vcard;
shared_converse.VCards = Collection.extend({
model: shared_converse.VCard,
initialize() {
this.on('add', v => v.get('jid') && shared_api.vcard.update(v));
}
});
shared_api.listen.on('chatRoomInitialized', m => {
setVCardOnModel(m);
m.occupants.forEach(setVCardOnOccupant);
m.listenTo(m.occupants, 'add', setVCardOnOccupant);
m.listenTo(m.occupants, 'change:image_hash', o => onOccupantAvatarChanged(o));
});
shared_api.listen.on('chatBoxInitialized', m => setVCardOnModel(m));
shared_api.listen.on('chatRoomMessageInitialized', m => setVCardOnMUCMessage(m));
shared_api.listen.on('addClientFeatures', () => shared_api.disco.own.features.add(vcard_Strophe.NS.VCARD));
shared_api.listen.on('clearSession', () => clearVCardsSession());
shared_api.listen.on('messageInitialized', m => setVCardOnModel(m));
shared_api.listen.on('rosterContactInitialized', m => setVCardOnModel(m));
shared_api.listen.on('statusInitialized', initVCardCollection);
Object.assign(shared_converse.api, vcard_api);
}
});
;// CONCATENATED MODULE: ./src/headless/index.js
/* START: Removable components
* --------------------
* Any of the following components may be removed if they're not needed.
*/
// XEP-0199 XMPP Ping
// XEP-0206 BOSH
// XEP-0115 Entity Capabilities
// RFC-6121 Instant messaging
// XEP-0030 Service discovery
// XEP-0050 Ad Hoc Commands
// Support for headline messages
// XEP-0313 Message Archive Management
// XEP-0045 Multi-user chat
// XEP-0199 XMPP Ping
// XEP-0060 Pubsub
// RFC-6121 Contacts Roster
// XEP-0198 Stream Management
// XEP-0054 VCard-temp
/* END: Removable components */
/* harmony default export */ const headless = (converse);
})();
/******/ return __webpack_exports__;
/******/ })()
;
});
//# sourceMappingURL=converse-headless.js.map